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
5ab041f61a469269bdea06e30349119f68b488e9
314
package com.chinayin.wework.chatdata.service; /** * @author chianyin <[email protected]> */ public interface MediaService { /** * 下载企业微信媒体文件 * * @param sdkFileId * @param file * @param fileSize */ void downloadMediaFile(String sdkFileId, String file, long fileSize); }
17.444444
73
0.640127
f62d9531acbb4b172e7b302f1e9facd1a6b0bf82
76,215
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ******************************************************************************/ package org.apache.olingo.odata2.core.ep.producer; import static org.custommonkey.xmlunit.XMLAssert.assertXpathEvaluatesTo; import static org.custommonkey.xmlunit.XMLAssert.assertXpathExists; import static org.custommonkey.xmlunit.XMLAssert.assertXpathNotExists; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLStreamException; import junit.framework.Assert; import org.apache.olingo.odata2.api.ODataCallback; import org.apache.olingo.odata2.api.edm.Edm; import org.apache.olingo.odata2.api.edm.EdmConcurrencyMode; import org.apache.olingo.odata2.api.edm.EdmCustomizableFeedMappings; import org.apache.olingo.odata2.api.edm.EdmEntitySet; import org.apache.olingo.odata2.api.edm.EdmEntityType; import org.apache.olingo.odata2.api.edm.EdmFacets; import org.apache.olingo.odata2.api.edm.EdmMapping; import org.apache.olingo.odata2.api.edm.EdmProperty; import org.apache.olingo.odata2.api.edm.EdmTargetPath; import org.apache.olingo.odata2.api.edm.EdmTyped; import org.apache.olingo.odata2.api.ep.EntityProviderException; import org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties; import org.apache.olingo.odata2.api.ep.callback.OnWriteEntryContent; import org.apache.olingo.odata2.api.ep.callback.WriteEntryCallbackContext; import org.apache.olingo.odata2.api.ep.callback.WriteEntryCallbackResult; import org.apache.olingo.odata2.api.exception.ODataApplicationException; import org.apache.olingo.odata2.api.exception.ODataException; import org.apache.olingo.odata2.api.exception.ODataMessageException; import org.apache.olingo.odata2.api.processor.ODataResponse; import org.apache.olingo.odata2.api.rt.RuntimeDelegate; import org.apache.olingo.odata2.api.uri.ExpandSelectTreeNode; import org.apache.olingo.odata2.api.uri.PathSegment; import org.apache.olingo.odata2.api.uri.UriInfo; import org.apache.olingo.odata2.core.ODataPathSegmentImpl; import org.apache.olingo.odata2.core.commons.ContentType; import org.apache.olingo.odata2.core.ep.AbstractProviderTest; import org.apache.olingo.odata2.core.ep.AtomEntityProvider; import org.apache.olingo.odata2.core.ep.EntityProviderProducerException; import org.apache.olingo.odata2.core.uri.ExpandSelectTreeCreator; import org.apache.olingo.odata2.core.uri.UriParserImpl; import org.apache.olingo.odata2.testutil.helper.StringHelper; import org.apache.olingo.odata2.testutil.helper.XMLUnitHelper; import org.apache.olingo.odata2.testutil.mock.EdmTestProvider; import org.apache.olingo.odata2.testutil.mock.MockFacade; import org.custommonkey.xmlunit.SimpleNamespaceContext; import org.custommonkey.xmlunit.XMLUnit; import org.custommonkey.xmlunit.exceptions.XpathException; import org.junit.Test; import org.xml.sax.SAXException; public class AtomEntryProducerTest extends AbstractProviderTest { private String buildingXPathString = "/a:entry/a:link[@href=\"Rooms('1')/nr_Building\" and @title='nr_Building']"; public AtomEntryProducerTest(final StreamWriterImplType type) { super(type); } @Test public void omitETagTestPropertyPresent() throws Exception { final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).omitETag(true).build(); AtomEntityProvider ser = createAtomEntityProvider(); Map<String, Object> localRoomData = new HashMap<String, Object>(); localRoomData.put("Id", "1"); localRoomData.put("Name", "Neu Schwanstein"); localRoomData.put("Seats", new Integer(20)); localRoomData.put("Version", new Integer(3)); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), localRoomData, properties); String xmlString = verifyResponse(response); assertXpathNotExists("/a:entry[@m:etag]", xmlString); } @Test public void omitETagTestPropertyNOTPresentMustNotResultInException() throws Exception { final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).omitETag(true).build(); AtomEntityProvider ser = createAtomEntityProvider(); Map<String, Object> localRoomData = new HashMap<String, Object>(); localRoomData.put("Id", "1"); localRoomData.put("Name", "Neu Schwanstein"); localRoomData.put("Seats", new Integer(20)); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), localRoomData, properties); String xmlString = verifyResponse(response); assertXpathNotExists("/a:entry[@m:etag]", xmlString); } @Test public void omitETagTestNonNullablePropertyNOTPresentMustNotResultInException() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); EdmProperty versionProperty = (EdmProperty) entitySet.getEntityType().getProperty("Version"); EdmFacets facets = versionProperty.getFacets(); when(facets.isNullable()).thenReturn(new Boolean(false)); List<String> selectedPropertyNames = new ArrayList<String>(); selectedPropertyNames.add("Id"); selectedPropertyNames.add("Name"); selectedPropertyNames.add("Seats"); ExpandSelectTreeNode selectNode = ExpandSelectTreeNode.entitySet(entitySet).selectedProperties(selectedPropertyNames).build(); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).omitETag(true).expandSelectTree(selectNode).build(); AtomEntityProvider ser = createAtomEntityProvider(); Map<String, Object> localRoomData = new HashMap<String, Object>(); localRoomData.put("Id", "1"); localRoomData.put("Name", "Neu Schwanstein"); localRoomData.put("Seats", new Integer(20)); ODataResponse response = ser.writeEntry(entitySet, localRoomData, properties); String xmlString = verifyResponse(response); assertXpathNotExists("/a:entry[@m:etag]", xmlString); } @Test public void contentOnly() throws Exception { final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).contentOnly(true).build(); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), employeeData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathNotExists("/a:entry[@m:etag]", xmlString); assertXpathNotExists("/a:entry/a:id", xmlString); assertXpathNotExists("/a:entry/a:title", xmlString); assertXpathNotExists("/a:entry/a:updated", xmlString); assertXpathNotExists("/a:entry/a:category", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Team\"and @href=\"Employees('1')/ne_Team\"]", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Room\"and @href=\"Employees('1')/ne_Room\"]", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Manager\" and @href=\"Employees('1')/ne_Manager\"]", xmlString); assertXpathNotExists("/a:entry/a:content", xmlString); assertXpathExists("/a:entry/m:properties", xmlString); } @Test public void contentOnlyRoom() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); List<String> selectedPropertyNames = new ArrayList<String>(); selectedPropertyNames.add("Name"); ExpandSelectTreeNode expandSelectTree = ExpandSelectTreeNode.entitySet(entitySet).selectedProperties(selectedPropertyNames).build(); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).contentOnly(true).expandSelectTree(expandSelectTree) .build(); Map<String, Object> localRoomData = new HashMap<String, Object>(); localRoomData.put("Name", "Neu Schwanstein"); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(entitySet, localRoomData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathNotExists("/a:entry[@m:etag]", xmlString); assertXpathNotExists("/a:entry/a:id", xmlString); assertXpathNotExists("/a:entry/a:title", xmlString); assertXpathNotExists("/a:entry/a:updated", xmlString); assertXpathNotExists("/a:entry/a:category", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"nr_Employees\"and @href=\"Rooms('1')/nr_Employees\"]", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"nr_Building\"and @href=\"Rooms('1')/nr_Building\"]", xmlString); assertXpathExists("/a:entry/a:content/m:properties/d:Name", xmlString); } @Test public void contentOnlyRoomSelectedOrExpandedLinksMustBeIgnored() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); List<String> selectedPropertyNames = new ArrayList<String>(); selectedPropertyNames.add("Name"); List<String> navigationPropertyNames = new ArrayList<String>(); navigationPropertyNames.add("nr_Employees"); navigationPropertyNames.add("nr_Building"); ExpandSelectTreeNode expandSelectTree = ExpandSelectTreeNode.entitySet(entitySet).selectedProperties(selectedPropertyNames).expandedLinks( navigationPropertyNames).build(); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).contentOnly(true).expandSelectTree(expandSelectTree) .build(); Map<String, Object> localRoomData = new HashMap<String, Object>(); localRoomData.put("Name", "Neu Schwanstein"); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(entitySet, localRoomData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathNotExists("/a:entry[@m:etag]", xmlString); assertXpathNotExists("/a:entry/a:id", xmlString); assertXpathNotExists("/a:entry/a:title", xmlString); assertXpathNotExists("/a:entry/a:updated", xmlString); assertXpathNotExists("/a:entry/a:category", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"nr_Employees\"and @href=\"Rooms('1')/nr_Employees\"]", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"nr_Building\"and @href=\"Rooms('1')/nr_Building\"]", xmlString); assertXpathExists("/a:entry/a:content/m:properties/d:Name", xmlString); } @Test public void contentOnlyRoomWithAdditionalLink() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); List<String> selectedPropertyNames = new ArrayList<String>(); selectedPropertyNames.add("Name"); ExpandSelectTreeNode expandSelectTree = ExpandSelectTreeNode.entitySet(entitySet).selectedProperties(selectedPropertyNames).build(); Map<String, Map<String, Object>> additinalLinks = new HashMap<String, Map<String, Object>>(); Map<String, Object> buildingLink = new HashMap<String, Object>(); buildingLink.put("Id", "1"); additinalLinks.put("nr_Building", buildingLink); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).contentOnly(true).expandSelectTree(expandSelectTree) .additionalLinks(additinalLinks).build(); Map<String, Object> localRoomData = new HashMap<String, Object>(); localRoomData.put("Name", "Neu Schwanstein"); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(entitySet, localRoomData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathNotExists("/a:entry[@m:etag]", xmlString); assertXpathNotExists("/a:entry/a:id", xmlString); assertXpathNotExists("/a:entry/a:title", xmlString); assertXpathNotExists("/a:entry/a:updated", xmlString); assertXpathNotExists("/a:entry/a:category", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"nr_Employees\"and @href=\"Rooms('1')/nr_Employees\"]", xmlString); assertXpathExists("/a:entry/a:content/m:properties/d:Name", xmlString); assertXpathExists("/a:entry/a:link[@title=\"nr_Building\"and @href=\"Buildings('1')\"]", xmlString); } @Test public void contentOnlyWithoutKey() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); List<String> selectedPropertyNames = new ArrayList<String>(); selectedPropertyNames.add("ManagerId"); ExpandSelectTreeNode select = ExpandSelectTreeNode.entitySet(entitySet).selectedProperties(selectedPropertyNames).build(); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).contentOnly(true).expandSelectTree(select).build(); Map<String, Object> localEmployeeData = new HashMap<String, Object>(); localEmployeeData.put("ManagerId", "1"); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(entitySet, localEmployeeData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathNotExists("/a:entry[@m:etag]", xmlString); assertXpathNotExists("/a:entry/a:id", xmlString); assertXpathNotExists("/a:entry/a:title", xmlString); assertXpathNotExists("/a:entry/a:updated", xmlString); assertXpathNotExists("/a:entry/a:category", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Manager\"]", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Team\"]", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Room\"]", xmlString); assertXpathNotExists("/a:entry/a:content", xmlString); assertXpathExists("/a:entry/m:properties", xmlString); assertXpathNotExists("/a:entry/m:properties/d:EmployeeId", xmlString); assertXpathExists("/a:entry/m:properties/d:ManagerId", xmlString); } @Test public void contentOnlySelectedOrExpandedLinksMustBeIgnored() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); List<String> selectedPropertyNames = new ArrayList<String>(); selectedPropertyNames.add("ManagerId"); List<String> expandedNavigationNames = new ArrayList<String>(); expandedNavigationNames.add("ne_Manager"); expandedNavigationNames.add("ne_Team"); expandedNavigationNames.add("ne_Room"); ExpandSelectTreeNode select = ExpandSelectTreeNode.entitySet(entitySet).selectedProperties(selectedPropertyNames).expandedLinks( expandedNavigationNames).build(); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).contentOnly(true).expandSelectTree(select).build(); Map<String, Object> localEmployeeData = new HashMap<String, Object>(); localEmployeeData.put("ManagerId", "1"); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(entitySet, localEmployeeData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathNotExists("/a:entry[@m:etag]", xmlString); assertXpathNotExists("/a:entry/a:id", xmlString); assertXpathNotExists("/a:entry/a:title", xmlString); assertXpathNotExists("/a:entry/a:updated", xmlString); assertXpathNotExists("/a:entry/a:category", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Manager\"]", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Team\"]", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Room\"]", xmlString); assertXpathNotExists("/a:entry/a:content", xmlString); assertXpathExists("/a:entry/m:properties", xmlString); assertXpathNotExists("/a:entry/m:properties/d:EmployeeId", xmlString); assertXpathExists("/a:entry/m:properties/d:ManagerId", xmlString); } @Test public void contentOnlyWithAdditinalLink() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); List<String> selectedPropertyNames = new ArrayList<String>(); selectedPropertyNames.add("ManagerId"); ExpandSelectTreeNode select = ExpandSelectTreeNode.entitySet(entitySet).selectedProperties(selectedPropertyNames).build(); Map<String, Map<String, Object>> additinalLinks = new HashMap<String, Map<String, Object>>(); Map<String, Object> managerLink = new HashMap<String, Object>(); managerLink.put("EmployeeId", "1"); additinalLinks.put("ne_Manager", managerLink); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).contentOnly(true).expandSelectTree(select).additionalLinks( additinalLinks).build(); Map<String, Object> localEmployeeData = new HashMap<String, Object>(); localEmployeeData.put("ManagerId", "1"); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(entitySet, localEmployeeData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathNotExists("/a:entry[@m:etag]", xmlString); assertXpathNotExists("/a:entry/a:id", xmlString); assertXpathNotExists("/a:entry/a:title", xmlString); assertXpathNotExists("/a:entry/a:updated", xmlString); assertXpathNotExists("/a:entry/a:category", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Team\"]", xmlString); assertXpathNotExists("/a:entry/a:link[@title=\"ne_Room\"]", xmlString); assertXpathNotExists("/a:entry/a:content", xmlString); assertXpathExists("/a:entry/m:properties", xmlString); assertXpathNotExists("/a:entry/m:properties/d:EmployeeId", xmlString); assertXpathExists("/a:entry/m:properties/d:ManagerId", xmlString); assertXpathExists("/a:entry/a:link[@href=\"Managers('1')\" and @title=\"ne_Manager\"]", xmlString); } @Test public void noneSyndicationKeepInContentFalseMustNotShowInProperties() throws Exception { // prepare Mock EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); EdmCustomizableFeedMappings employeeCustomPropertyMapping = mock(EdmCustomizableFeedMappings.class); when(employeeCustomPropertyMapping.isFcKeepInContent()).thenReturn(Boolean.FALSE); when(employeeCustomPropertyMapping.getFcNsPrefix()).thenReturn("customPre"); when(employeeCustomPropertyMapping.getFcNsUri()).thenReturn("http://customUri.com"); EdmTyped employeeEntryDateProperty = employeesSet.getEntityType().getProperty("EmployeeName"); when(((EdmProperty) employeeEntryDateProperty).getCustomizableFeedMappings()).thenReturn( employeeCustomPropertyMapping); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("a", Edm.NAMESPACE_ATOM_2005); prefixMap.put("d", Edm.NAMESPACE_D_2007_08); prefixMap.put("m", Edm.NAMESPACE_M_2007_08); prefixMap.put("xml", Edm.NAMESPACE_XML_1998); prefixMap.put("customPre", "http://customUri.com"); XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap)); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(employeesSet, employeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry/customPre:EmployeeName", xmlString); assertXpathNotExists("/a:entry/m:properties/d:EmployeeName", xmlString); } @Test public void noneSyndicationKeepInContentTrueMustShowInProperties() throws Exception { // prepare Mock EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); EdmCustomizableFeedMappings employeeCustomPropertyMapping = mock(EdmCustomizableFeedMappings.class); when(employeeCustomPropertyMapping.isFcKeepInContent()).thenReturn(Boolean.TRUE); when(employeeCustomPropertyMapping.getFcNsPrefix()).thenReturn("customPre"); when(employeeCustomPropertyMapping.getFcNsUri()).thenReturn("http://customUri.com"); EdmTyped employeeEntryDateProperty = employeesSet.getEntityType().getProperty("EmployeeName"); when(((EdmProperty) employeeEntryDateProperty).getCustomizableFeedMappings()).thenReturn( employeeCustomPropertyMapping); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("a", Edm.NAMESPACE_ATOM_2005); prefixMap.put("d", Edm.NAMESPACE_D_2007_08); prefixMap.put("m", Edm.NAMESPACE_M_2007_08); prefixMap.put("xml", Edm.NAMESPACE_XML_1998); prefixMap.put("customPre", "http://customUri.com"); XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap)); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(employeesSet, employeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry/customPre:EmployeeName", xmlString); assertXpathExists("/a:entry/m:properties/d:EmployeeName", xmlString); } @Test public void noneSyndicationWithNullPrefix() throws Exception { // prepare Mock EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); EdmCustomizableFeedMappings employeeCustomPropertyMapping = mock(EdmCustomizableFeedMappings.class); when(employeeCustomPropertyMapping.isFcKeepInContent()).thenReturn(Boolean.TRUE); when(employeeCustomPropertyMapping.getFcNsUri()).thenReturn("http://customUri.com"); EdmTyped employeeEntryDateProperty = employeesSet.getEntityType().getProperty("EmployeeName"); when(((EdmProperty) employeeEntryDateProperty).getCustomizableFeedMappings()).thenReturn( employeeCustomPropertyMapping); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("a", Edm.NAMESPACE_ATOM_2005); prefixMap.put("d", Edm.NAMESPACE_D_2007_08); prefixMap.put("m", Edm.NAMESPACE_M_2007_08); prefixMap.put("xml", Edm.NAMESPACE_XML_1998); prefixMap.put("customPre", "http://customUri.com"); XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap)); AtomEntityProvider ser = createAtomEntityProvider(); boolean thrown = false; try { ser.writeEntry(employeesSet, employeeData, DEFAULT_PROPERTIES); } catch (EntityProviderException e) { verifyRootCause(EntityProviderProducerException.class, EntityProviderException.INVALID_NAMESPACE.getKey(), e); thrown = true; } if (!thrown) { fail("Exception should have been thrown"); } } @Test public void noneSyndicationWithNullUri() throws Exception { // prepare Mock EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); EdmCustomizableFeedMappings employeeCustomPropertyMapping = mock(EdmCustomizableFeedMappings.class); when(employeeCustomPropertyMapping.isFcKeepInContent()).thenReturn(Boolean.TRUE); when(employeeCustomPropertyMapping.getFcNsPrefix()).thenReturn("customPre"); EdmTyped employeeEntryDateProperty = employeesSet.getEntityType().getProperty("EmployeeName"); when(((EdmProperty) employeeEntryDateProperty).getCustomizableFeedMappings()).thenReturn( employeeCustomPropertyMapping); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("a", Edm.NAMESPACE_ATOM_2005); prefixMap.put("d", Edm.NAMESPACE_D_2007_08); prefixMap.put("m", Edm.NAMESPACE_M_2007_08); prefixMap.put("xml", Edm.NAMESPACE_XML_1998); prefixMap.put("customPre", "http://customUri.com"); XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap)); AtomEntityProvider ser = createAtomEntityProvider(); boolean thrown = false; try { ser.writeEntry(employeesSet, employeeData, DEFAULT_PROPERTIES); } catch (EntityProviderException e) { verifyRootCause(EntityProviderProducerException.class, EntityProviderException.INVALID_NAMESPACE.getKey(), e); thrown = true; } if (!thrown) { fail("Exception should have been thrown"); } } @Test public void noneSyndicationWithNullUriAndNullPrefix() throws Exception { // prepare Mock EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); EdmCustomizableFeedMappings employeeCustomPropertyMapping = mock(EdmCustomizableFeedMappings.class); when(employeeCustomPropertyMapping.isFcKeepInContent()).thenReturn(Boolean.TRUE); EdmTyped employeeEntryDateProperty = employeesSet.getEntityType().getProperty("EmployeeName"); when(((EdmProperty) employeeEntryDateProperty).getCustomizableFeedMappings()).thenReturn( employeeCustomPropertyMapping); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("a", Edm.NAMESPACE_ATOM_2005); prefixMap.put("d", Edm.NAMESPACE_D_2007_08); prefixMap.put("m", Edm.NAMESPACE_M_2007_08); prefixMap.put("xml", Edm.NAMESPACE_XML_1998); prefixMap.put("f", "http://customUri.com"); XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap)); AtomEntityProvider ser = createAtomEntityProvider(); boolean thrown = false; try { ser.writeEntry(employeesSet, employeeData, DEFAULT_PROPERTIES); } catch (EntityProviderException e) { verifyRootCause(EntityProviderProducerException.class, EntityProviderException.INVALID_NAMESPACE.getKey(), e); thrown = true; } if (!thrown) { fail("Exception should have been thrown"); } } @Test public void syndicationWithComplexProperty() throws Exception { // prepare Mock EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); EdmCustomizableFeedMappings employeeCustomPropertyMapping = mock(EdmCustomizableFeedMappings.class); when(employeeCustomPropertyMapping.isFcKeepInContent()).thenReturn(Boolean.TRUE); when(employeeCustomPropertyMapping.getFcNsPrefix()).thenReturn("customPre"); when(employeeCustomPropertyMapping.getFcNsUri()).thenReturn("http://customUri.com"); EdmTyped employeeLocationProperty = employeesSet.getEntityType().getProperty("Location"); when(((EdmProperty) employeeLocationProperty).getCustomizableFeedMappings()).thenReturn( employeeCustomPropertyMapping); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("a", Edm.NAMESPACE_ATOM_2005); prefixMap.put("d", Edm.NAMESPACE_D_2007_08); prefixMap.put("m", Edm.NAMESPACE_M_2007_08); prefixMap.put("xml", Edm.NAMESPACE_XML_1998); prefixMap.put("customPre", "http://customUri.com"); XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap)); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(employeesSet, employeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathNotExists("/a:entry/customPre:Location", xmlString); assertXpathExists("/a:entry/m:properties/d:Location", xmlString); } private void verifyRootCause(final Class<?> class1, final String key, final ODataMessageException e) { Throwable thrownException = e; Throwable lastFoundException = null; if (e.getClass().equals(class1)) { lastFoundException = e; } while (thrownException.getCause() != null) { thrownException = thrownException.getCause(); if (thrownException.getClass().equals(class1)) { lastFoundException = thrownException; } } if (lastFoundException != null) { ODataMessageException msgException = (ODataMessageException) lastFoundException; assertEquals(key, msgException.getMessageReference().getKey()); } else { fail("Exception of class: " + class1.getCanonicalName() + " in stacktrace not found."); } } @Test public void serializeAtomMediaResource() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), employeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathExists("/a:entry/a:content", xmlString); assertXpathEvaluatesTo("", "/a:entry/a:content", xmlString); assertXpathEvaluatesTo(ContentType.APPLICATION_OCTET_STREAM.toString(), "/a:entry/a:content/@type", xmlString); assertXpathEvaluatesTo("Employees('1')/$value", "/a:entry/a:content/@src", xmlString); assertXpathExists("/a:entry/m:properties", xmlString); assertXpathExists("/a:entry/a:link[@href=\"Employees('1')/$value\"]", xmlString); assertXpathExists("/a:entry/a:link[@rel='edit-media']", xmlString); assertXpathExists("/a:entry/a:link[@type='application/octet-stream']", xmlString); assertXpathExists("/a:entry/a:link[@href=\"Employees('1')\"]", xmlString); assertXpathExists("/a:entry/a:link[@rel='edit']", xmlString); assertXpathExists("/a:entry/a:link[@title='Employee']", xmlString); // assert navigation link order verifyTagOrdering(xmlString, "link((?:(?!link).)*?)edit", "link((?:(?!link).)*?)edit-media", "link((?:(?!link).)*?)ne_Manager", "link((?:(?!link).)*?)ne_Team", "link((?:(?!link).)*?)ne_Room"); } private String verifyResponse(final ODataResponse response) throws IOException { assertNotNull(response); assertNotNull(response.getEntity()); assertNull("EntityProvider should not set content header", response.getContentHeader()); String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity()); return xmlString; } @Test public void serializeAtomMediaResourceWithMimeType() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build(); Map<String, Object> localEmployeeData = new HashMap<String, Object>(); Calendar date = Calendar.getInstance(TimeZone.getTimeZone("GMT")); date.clear(); date.set(1999, 0, 1); localEmployeeData.put("EmployeeId", "1"); localEmployeeData.put("ImmageUrl", null); localEmployeeData.put("ManagerId", "1"); localEmployeeData.put("Age", new Integer(52)); localEmployeeData.put("RoomId", "1"); localEmployeeData.put("EntryDate", date); localEmployeeData.put("TeamId", "42"); localEmployeeData.put("EmployeeName", "Walter Winter"); localEmployeeData.put("getImageType", "abc"); Map<String, Object> locationData = new HashMap<String, Object>(); Map<String, Object> cityData = new HashMap<String, Object>(); cityData.put("PostalCode", "33470"); cityData.put("CityName", "Duckburg"); locationData.put("City", cityData); locationData.put("Country", "Calisota"); localEmployeeData.put("Location", locationData); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), localEmployeeData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathExists("/a:entry/a:content", xmlString); assertXpathEvaluatesTo("abc", "/a:entry/a:content/@type", xmlString); assertXpathEvaluatesTo("Employees('1')/$value", "/a:entry/a:content/@src", xmlString); assertXpathExists("/a:entry/m:properties", xmlString); } /** * Test serialization of empty syndication title property. EmployeeName is set to NULL after the update (which is * allowed because EmployeeName has default Nullable behavior which is true). * Write of an empty atom title tag is allowed within RFC4287 (http://tools.ietf.org/html/rfc4287#section-4.2.14). */ @Test public void serializeEmployeeWithNullSyndicationTitleProperty() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build(); employeeData.put("EmployeeName", null); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), employeeData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry/a:title", xmlString); assertXpathEvaluatesTo("", "/a:entry/a:title", xmlString); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathExists("/a:entry/a:content", xmlString); assertXpathEvaluatesTo("Employees('1')/$value", "/a:entry/a:content/@src", xmlString); assertXpathExists("/a:entry/m:properties", xmlString); } @Test public void serializeEmployeeAndCheckOrderOfTags() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build(); Map<String, Object> localEmployeeData = new HashMap<String, Object>(); Calendar date = Calendar.getInstance(TimeZone.getTimeZone("GMT")); date.clear(); date.set(1999, 0, 1); localEmployeeData.put("EmployeeId", "1"); localEmployeeData.put("ImmageUrl", null); localEmployeeData.put("ManagerId", "1"); localEmployeeData.put("Age", new Integer(52)); localEmployeeData.put("RoomId", "1"); localEmployeeData.put("EntryDate", date); localEmployeeData.put("TeamId", "42"); localEmployeeData.put("EmployeeName", "Walter Winter"); localEmployeeData.put("getImageType", "abc"); Map<String, Object> locationData = new HashMap<String, Object>(); Map<String, Object> cityData = new HashMap<String, Object>(); cityData.put("PostalCode", "33470"); cityData.put("CityName", "Duckburg"); locationData.put("City", cityData); locationData.put("Country", "Calisota"); localEmployeeData.put("Location", locationData); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), localEmployeeData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathExists("/a:entry/a:content", xmlString); // verify self link assertXpathExists("/a:entry/a:link[@href=\"Employees('1')\"]", xmlString); // verify content media link assertXpathExists("/a:entry/a:link[@href=\"Employees('1')/$value\"]", xmlString); // verify one navigation link assertXpathExists("/a:entry/a:link[@title='ne_Manager']", xmlString); // verify content assertXpathExists("/a:entry/a:content[@type='abc']", xmlString); // verify properties assertXpathExists("/a:entry/m:properties", xmlString); assertXpathEvaluatesTo("9", "count(/a:entry/m:properties/*)", xmlString); // verify order of tags verifyTagOrdering(xmlString, "id", "title", "updated", "category", "link((?:(?!link).)*?)edit", "link((?:(?!link).)*?)edit-media", "link((?:(?!link).)*?)ne_Manager", "content", "properties"); } @Test public void serializeEmployeeAndCheckOrderOfPropertyTags() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build(); EdmEntitySet employeeEntitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); ODataResponse response = ser.writeEntry(employeeEntitySet, employeeData, properties); String xmlString = verifyResponse(response); // log.debug(xmlString); assertXpathExists("/a:entry", xmlString); assertXpathExists("/a:entry/a:content", xmlString); // verify properties assertXpathExists("/a:entry/m:properties", xmlString); assertXpathEvaluatesTo("9", "count(/a:entry/m:properties/*)", xmlString); // verify order of tags List<String> expectedPropertyNamesFromEdm = employeeEntitySet.getEntityType().getPropertyNames(); verifyTagOrdering(xmlString, expectedPropertyNamesFromEdm.toArray(new String[0])); } @Test public void serializeEmployeeAndCheckKeepInContentFalse() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build(); EdmEntitySet employeeEntitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); // set "keepInContent" to false for EntryDate EdmCustomizableFeedMappings employeeUpdatedMappings = mock(EdmCustomizableFeedMappings.class); when(employeeUpdatedMappings.getFcTargetPath()).thenReturn(EdmTargetPath.SYNDICATION_UPDATED); when(employeeUpdatedMappings.isFcKeepInContent()).thenReturn(Boolean.FALSE); EdmTyped employeeEntryDateProperty = employeeEntitySet.getEntityType().getProperty("EntryDate"); when(((EdmProperty) employeeEntryDateProperty).getCustomizableFeedMappings()).thenReturn(employeeUpdatedMappings); ODataResponse response = ser.writeEntry(employeeEntitySet, employeeData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathExists("/a:entry/a:content", xmlString); // verify properties assertXpathExists("/a:entry/m:properties", xmlString); assertXpathEvaluatesTo("8", "count(/a:entry/m:properties/*)", xmlString); // assertXpathNotExists("/a:entry/m:properties/d:EntryDate", xmlString); // verify order of tags List<String> expectedPropertyNamesFromEdm = new ArrayList<String>(employeeEntitySet.getEntityType().getPropertyNames()); expectedPropertyNamesFromEdm.remove(String.valueOf("EntryDate")); verifyTagOrdering(xmlString, expectedPropertyNamesFromEdm.toArray(new String[0])); } @Test(expected = EntityProviderException.class) public void serializeAtomEntryWithNullData() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build(); AtomEntityProvider ser = createAtomEntityProvider(); ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), null, properties); } @Test(expected = EntityProviderException.class) public void serializeAtomEntryWithEmptyHashMap() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build(); AtomEntityProvider ser = createAtomEntityProvider(); ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), new HashMap<String, Object>(), properties); } @Test public void serializeAtomEntry() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build(); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), roomData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathExists("/a:entry/a:content", xmlString); assertXpathEvaluatesTo(ContentType.APPLICATION_XML.toString(), "/a:entry/a:content/@type", xmlString); assertXpathExists("/a:entry/a:content/m:properties", xmlString); } @Test public void serializeAtomEntryWithSimplePropertyTypeInformation() throws Exception { final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).includeSimplePropertyType(true).build(); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), roomData, properties); String xmlString = verifyResponse(response); assertXpathExists("/a:entry/a:content/m:properties", xmlString); assertXpathExists("/a:entry/a:content/m:properties/d:Id[@m:type=\"Edm.String\"]", xmlString); assertXpathExists("/a:entry/a:content/m:properties/d:Name[@m:type=\"Edm.String\"]", xmlString); assertXpathExists("/a:entry/a:content/m:properties/d:Seats[@m:type=\"Edm.Int16\"]", xmlString); assertXpathExists("/a:entry/a:content/m:properties/d:Version[@m:type=\"Edm.Int16\"]", xmlString); } @Test public void serializeEntryId() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), employeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathExists("/a:entry/a:id", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString() + "Employees('1')", "/a:entry/a:id/text()", xmlString); } @Test public void serializeEntryTitle() throws Exception { AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), employeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry/a:title", xmlString); assertXpathEvaluatesTo("text", "/a:entry/a:title/@type", xmlString); assertXpathEvaluatesTo((String) employeeData.get("EmployeeName"), "/a:entry/a:title/text()", xmlString); } @Test public void serializeEntryUpdated() throws Exception { AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), employeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry/a:updated", xmlString); assertXpathEvaluatesTo("1999-01-01T00:00:00Z", "/a:entry/a:updated/text()", xmlString); } @Test public void serializeIds() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"), photoData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathExists("/a:entry/a:id", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString() + "Container2.Photos(Id=1,Type='image%2Fpng')", "/a:entry/a:id/text()", xmlString); } @Test public void serializeProperties() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), employeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry/m:properties", xmlString); assertXpathEvaluatesTo((String) employeeData.get("RoomId"), "/a:entry/m:properties/d:RoomId/text()", xmlString); assertXpathEvaluatesTo((String) employeeData.get("TeamId"), "/a:entry/m:properties/d:TeamId/text()", xmlString); } @Test public void serializeWithValueEncoding() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { photoData.put("Type", "< Ö >"); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"), photoData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString); assertXpathExists("/a:entry/a:id", xmlString); assertXpathEvaluatesTo(BASE_URI.toASCIIString() + "Container2.Photos(Id=1,Type='%3C%20%C3%96%20%3E')", "/a:entry/a:id/text()", xmlString); assertXpathEvaluatesTo("Container2.Photos(Id=1,Type='%3C%20%C3%96%20%3E')", "/a:entry/a:link/@href", xmlString); } @Test public void serializeCategory() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), employeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry/a:category", xmlString); assertXpathExists("/a:entry/a:category/@term", xmlString); assertXpathExists("/a:entry/a:category/@scheme", xmlString); assertXpathEvaluatesTo("RefScenario.Employee", "/a:entry/a:category/@term", xmlString); assertXpathEvaluatesTo(Edm.NAMESPACE_SCHEME_2007_08, "/a:entry/a:category/@scheme", xmlString); } @Test public void serializeETag() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"), photoData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathExists("/a:entry/@m:etag", xmlString); assertXpathEvaluatesTo("W/\"1\"", "/a:entry/@m:etag", xmlString); assertEquals("W/\"1\"", response.getETag()); } @Test public void serializeETagEncoding() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { Edm edm = MockFacade.getMockEdm(); EdmTyped roomIdProperty = edm.getEntityType("RefScenario", "Room").getProperty("Id"); EdmFacets facets = mock(EdmFacets.class); when(facets.getConcurrencyMode()).thenReturn(EdmConcurrencyMode.Fixed); when(facets.getMaxLength()).thenReturn(3); when(((EdmProperty) roomIdProperty).getFacets()).thenReturn(facets); roomData.put("Id", "<\">"); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(edm.getDefaultEntityContainer().getEntitySet("Rooms"), roomData, DEFAULT_PROPERTIES); assertNotNull(response); assertNotNull(response.getEntity()); assertNull("EntityProvider should not set content header", response.getContentHeader()); assertEquals("W/\"<\">.3\"", response.getETag()); String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertXpathExists("/a:entry", xmlString); assertXpathExists("/a:entry/@m:etag", xmlString); assertXpathEvaluatesTo("W/\"<\">.3\"", "/a:entry/@m:etag", xmlString); } @Test(expected = EntityProviderException.class) public void serializeWithFacetsValidation() throws Exception { Edm edm = MockFacade.getMockEdm(); EdmTyped roomNameProperty = edm.getEntityType("RefScenario", "Room").getProperty("Name"); EdmFacets facets = mock(EdmFacets.class); when(facets.getMaxLength()).thenReturn(3); when(((EdmProperty) roomNameProperty).getFacets()).thenReturn(facets); roomData.put("Name", "1234567"); AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(edm.getDefaultEntityContainer().getEntitySet("Rooms"), roomData, DEFAULT_PROPERTIES); Assert.assertNotNull(response); } @Test public void serializeWithoutFacetsValidation() throws Exception { Edm edm = MockFacade.getMockEdm(); EdmTyped roomNameProperty = edm.getEntityType("RefScenario", "Room").getProperty("Name"); EdmFacets facets = mock(EdmFacets.class); when(facets.getMaxLength()).thenReturn(3); when(((EdmProperty) roomNameProperty).getFacets()).thenReturn(facets); String name = "1234567"; roomData.put("Name", name); AtomEntityProvider ser = createAtomEntityProvider(); EntityProviderWriteProperties properties = EntityProviderWriteProperties .fromProperties(DEFAULT_PROPERTIES).validatingFacets(false).build(); ODataResponse response = ser.writeEntry(edm.getDefaultEntityContainer().getEntitySet("Rooms"), roomData, properties); assertNotNull(response); assertNotNull(response.getEntity()); String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertXpathEvaluatesTo(name, "/a:entry/a:content/m:properties/d:Name/text()", xmlString); } @Test public void serializeCustomMapping() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"), photoData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathExists("/a:entry/ру:Содержание", xmlString); assertXpathEvaluatesTo((String) photoData.get("Содержание"), "/a:entry/ру:Содержание/text()", xmlString); verifyTagOrdering(xmlString, "category", "Содержание", "content", "properties"); } @Test public void testCustomProperties() throws Exception { AtomEntityProvider ser = createAtomEntityProvider(); EdmEntitySet entitySet = MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"); ODataResponse response = ser.writeEntry(entitySet, photoData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathExists("/a:entry/custom:CustomProperty", xmlString); assertXpathNotExists("/a:entry/custom:CustomProperty/text()", xmlString); assertXpathEvaluatesTo("true", "/a:entry/custom:CustomProperty/@m:null", xmlString); verifyTagOrdering(xmlString, "category", "Содержание", "CustomProperty", "content", "properties"); } @Test public void testKeepInContentNull() throws Exception { AtomEntityProvider ser = createAtomEntityProvider(); EdmEntitySet entitySet = MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"); EdmProperty customProperty = (EdmProperty) entitySet.getEntityType().getProperty("CustomProperty"); when(customProperty.getCustomizableFeedMappings().isFcKeepInContent()).thenReturn(null); ODataResponse response = ser.writeEntry(entitySet, photoData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists("/a:entry", xmlString); assertXpathExists("/a:entry/custom:CustomProperty", xmlString); assertXpathNotExists("/a:entry/custom:CustomProperty/text()", xmlString); assertXpathEvaluatesTo("true", "/a:entry/custom:CustomProperty/@m:null", xmlString); assertXpathExists("/a:entry/m:properties/d:CustomProperty", xmlString); verifyTagOrdering(xmlString, "category", "Содержание", "CustomProperty", "content", "properties"); } @Test public void serializeAtomMediaResourceLinks() throws IOException, XpathException, SAXException, XMLStreamException, FactoryConfigurationError, ODataException { AtomEntityProvider ser = createAtomEntityProvider(); ODataResponse response = ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"), employeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); String rel = Edm.NAMESPACE_REL_2007_08 + "ne_Manager"; assertXpathExists("/a:entry/a:link[@href=\"Employees('1')/ne_Manager\"]", xmlString); assertXpathExists("/a:entry/a:link[@rel='" + rel + "']", xmlString); assertXpathExists("/a:entry/a:link[@type='application/atom+xml;type=entry']", xmlString); assertXpathExists("/a:entry/a:link[@title='ne_Manager']", xmlString); } @Test public void additionalLink() throws Exception { Map<String, Map<String, Object>> links = new HashMap<String, Map<String, Object>>(); links.put("nr_Building", buildingData); final ODataResponse response = createAtomEntityProvider().writeEntry( MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), roomData, EntityProviderWriteProperties.serviceRoot(BASE_URI).additionalLinks(links).build()); final String xmlString = verifyResponse(response); assertXpathExists("/a:entry/a:link[@title='nr_Building']", xmlString); assertXpathNotExists("/a:entry/a:link[@href=\"Rooms('1')/nr_Building\"]", xmlString); assertXpathExists("/a:entry/a:link[@href=\"Buildings('1')\"]", xmlString); assertXpathExists("/a:entry/a:link[@type='application/atom+xml;type=entry']", xmlString); } @Test public void additionalLinkToOneOfMany() throws Exception { Map<String, Map<String, Object>> links = new HashMap<String, Map<String, Object>>(); links.put("nr_Employees", employeeData); final ODataResponse response = createAtomEntityProvider().writeEntry( MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), roomData, EntityProviderWriteProperties.serviceRoot(BASE_URI).additionalLinks(links).build()); final String xmlString = verifyResponse(response); assertXpathExists("/a:entry/a:link[@title='nr_Employees']", xmlString); assertXpathNotExists("/a:entry/a:link[@href=\"Rooms('1')/nr_Employees\"]", xmlString); assertXpathExists("/a:entry/a:link[@href=\"Employees('1')\"]", xmlString); assertXpathExists("/a:entry/a:link[@type='application/atom+xml;type=feed']", xmlString); } @Test public void serializeWithCustomSrcAttributeOnEmployee() throws Exception { AtomEntityProvider ser = createAtomEntityProvider(); Map<String, Object> localEmployeeData = new HashMap<String, Object>(employeeData); String mediaResourceSourceKey = "~src"; localEmployeeData.put(mediaResourceSourceKey, "http://localhost:8080/images/image1"); EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); EdmMapping mapping = employeesSet.getEntityType().getMapping(); when(mapping.getMediaResourceSourceKey()).thenReturn(mediaResourceSourceKey); ODataResponse response = ser.writeEntry(employeesSet, localEmployeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists( "/a:entry/a:link[@href=\"Employees('1')/$value\" and" + " @rel=\"edit-media\" and @type=\"application/octet-stream\"]", xmlString); assertXpathExists("/a:entry/a:content[@type=\"application/octet-stream\"]", xmlString); assertXpathExists("/a:entry/a:content[@src=\"http://localhost:8080/images/image1\"]", xmlString); } @Test public void serializeWithCustomSrcAndTypeAttributeOnEmployee() throws Exception { AtomEntityProvider ser = createAtomEntityProvider(); Map<String, Object> localEmployeeData = new HashMap<String, Object>(employeeData); String mediaResourceSourceKey = "~src"; localEmployeeData.put(mediaResourceSourceKey, "http://localhost:8080/images/image1"); String mediaResourceMimeTypeKey = "~type"; localEmployeeData.put(mediaResourceMimeTypeKey, "image/jpeg"); EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); EdmMapping mapping = employeesSet.getEntityType().getMapping(); when(mapping.getMediaResourceSourceKey()).thenReturn(mediaResourceSourceKey); when(mapping.getMediaResourceMimeTypeKey()).thenReturn(mediaResourceMimeTypeKey); ODataResponse response = ser.writeEntry(employeesSet, localEmployeeData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathExists( "/a:entry/a:link[@href=\"Employees('1')/$value\" and" + " @rel=\"edit-media\" and @type=\"image/jpeg\"]", xmlString); assertXpathExists("/a:entry/a:content[@type=\"image/jpeg\"]", xmlString); assertXpathExists("/a:entry/a:content[@src=\"http://localhost:8080/images/image1\"]", xmlString); } @Test public void serializeWithCustomSrcAttributeOnRoom() throws Exception { AtomEntityProvider ser = createAtomEntityProvider(); Map<String, Object> localRoomData = new HashMap<String, Object>(roomData); String mediaResourceSourceKey = "~src"; localRoomData.put(mediaResourceSourceKey, "http://localhost:8080/images/image1"); EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); EdmEntityType roomType = roomsSet.getEntityType(); EdmMapping mapping = mock(EdmMapping.class); when(roomType.getMapping()).thenReturn(mapping); when(mapping.getMediaResourceSourceKey()).thenReturn(mediaResourceSourceKey); ODataResponse response = ser.writeEntry(roomsSet, localRoomData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathNotExists( "/a:entry/a:link[@href=\"Rooms('1')/$value\" and" + " @rel=\"edit-media\" and @type=\"application/octet-stream\"]", xmlString); assertXpathNotExists("/a:entry/a:content[@type=\"application/octet-stream\"]", xmlString); assertXpathNotExists("/a:entry/a:content[@src=\"http://localhost:8080/images/image1\"]", xmlString); } @Test public void serializeWithCustomSrcAndTypeAttributeOnRoom() throws Exception { AtomEntityProvider ser = createAtomEntityProvider(); Map<String, Object> localRoomData = new HashMap<String, Object>(roomData); String mediaResourceSourceKey = "~src"; localRoomData.put(mediaResourceSourceKey, "http://localhost:8080/images/image1"); String mediaResourceMimeTypeKey = "~type"; localRoomData.put(mediaResourceMimeTypeKey, "image/jpeg"); EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); EdmEntityType roomType = roomsSet.getEntityType(); EdmMapping mapping = mock(EdmMapping.class); when(roomType.getMapping()).thenReturn(mapping); when(mapping.getMediaResourceSourceKey()).thenReturn(mediaResourceSourceKey); when(mapping.getMediaResourceMimeTypeKey()).thenReturn(mediaResourceMimeTypeKey); ODataResponse response = ser.writeEntry(roomsSet, localRoomData, DEFAULT_PROPERTIES); String xmlString = verifyResponse(response); assertXpathNotExists( "/a:entry/a:link[@href=\"Rooms('1')/$value\" and" + " @rel=\"edit-media\" and @type=\"image/jpeg\"]", xmlString); assertXpathNotExists("/a:entry/a:content[@type=\"image/jpeg\"]", xmlString); assertXpathNotExists("/a:entry/a:content[@src=\"http://localhost:8080/images/image1\"]", xmlString); } // @Test // public void assureGetMimeTypeWinsOverGetMediaResourceMimeTypeKey() throws Exception { // // Keep this test till version 1.2 // AtomEntityProvider ser = createAtomEntityProvider(); // Map<String, Object> localEmployeeData = new HashMap<String, Object>(employeeData); // String mediaResourceMimeTypeKey = "~type"; // localEmployeeData.put(mediaResourceMimeTypeKey, "wrong"); // String originalMimeTypeKey = "~originalType"; // localEmployeeData.put(originalMimeTypeKey, "right"); // EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); // EdmMapping mapping = employeesSet.getEntityType().getMapping(); // when(mapping.getMediaResourceMimeTypeKey()).thenReturn(mediaResourceMimeTypeKey); // when(mapping.getMimeType()).thenReturn(originalMimeTypeKey); // ODataResponse response = ser.writeEntry(employeesSet, localEmployeeData, DEFAULT_PROPERTIES); // String xmlString = verifyResponse(response); // // assertXpathExists("/a:entry/a:content[@type=\"right\"]", xmlString); // assertXpathNotExists("/a:entry/a:content[@type=\"wrong\"]", xmlString); // } private void verifyTagOrdering(final String xmlString, final String... toCheckTags) { XMLUnitHelper.verifyTagOrdering(xmlString, toCheckTags); } @Test public void unbalancedPropertyEntryWithInlineEntry() throws Exception { ExpandSelectTreeNode selectTree = getSelectExpandTree("Rooms('1')", "nr_Building", "nr_Building"); Map<String, Object> roomData = new HashMap<String, Object>(); roomData.put("Id", "1"); roomData.put("Name", "Neu Schwanstein"); roomData.put("Seats", new Integer(20)); class EntryCallback implements OnWriteEntryContent { @Override public WriteEntryCallbackResult retrieveEntryResult(final WriteEntryCallbackContext context) throws ODataApplicationException { Map<String, Object> buildingData = new HashMap<String, Object>(); buildingData.put("Id", "1"); buildingData.put("Name", "Building1"); WriteEntryCallbackResult result = new WriteEntryCallbackResult(); result.setEntryData(buildingData); EntityProviderWriteProperties inlineProperties = EntityProviderWriteProperties.serviceRoot(BASE_URI).expandSelectTree( context.getCurrentExpandSelectTreeNode()).build(); result.setInlineProperties(inlineProperties); return result; } } EntryCallback callback = new EntryCallback(); Map<String, ODataCallback> callbacks = new HashMap<String, ODataCallback>(); callbacks.put("nr_Building", callback); EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).expandSelectTree(selectTree).callbacks(callbacks). isDataBasedPropertySerialization(true).build(); AtomEntityProvider provider = createAtomEntityProvider(); ODataResponse response = provider.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), roomData, properties); String xmlString = verifyResponse(response); assertXpathNotExists("/a:entry/m:properties", xmlString); assertXpathExists("/a:entry/a:link", xmlString); verifyBuilding(buildingXPathString, xmlString); } private ExpandSelectTreeNode getSelectExpandTree(final String pathSegment, final String selectString, final String expandString) throws Exception { Edm edm = RuntimeDelegate.createEdm(new EdmTestProvider()); UriParserImpl uriParser = new UriParserImpl(edm); List<PathSegment> pathSegments = new ArrayList<PathSegment>(); pathSegments.add(new ODataPathSegmentImpl(pathSegment, null)); Map<String, String> queryParameters = new HashMap<String, String>(); if (selectString != null) { queryParameters.put("$select", selectString); } if (expandString != null) { queryParameters.put("$expand", expandString); } UriInfo uriInfo = uriParser.parse(pathSegments, queryParameters); ExpandSelectTreeCreator expandSelectTreeCreator = new ExpandSelectTreeCreator(uriInfo.getSelect(), uriInfo.getExpand()); ExpandSelectTreeNode expandSelectTree = expandSelectTreeCreator.create(); assertNotNull(expandSelectTree); return expandSelectTree; } private void verifyBuilding(final String path, final String xmlString) throws XpathException, IOException, SAXException { assertXpathExists(path, xmlString); assertXpathExists(path + "/m:inline", xmlString); assertXpathExists(path + "/m:inline/a:entry[@xml:base='" + BASE_URI + "']", xmlString); assertXpathExists(path + "/m:inline/a:entry", xmlString); assertXpathExists(path + "/m:inline/a:entry/a:id", xmlString); assertXpathExists(path + "/m:inline/a:entry/a:title", xmlString); assertXpathExists(path + "/m:inline/a:entry/a:updated", xmlString); assertXpathExists(path + "/m:inline/a:entry/a:category", xmlString); assertXpathExists(path + "/m:inline/a:entry/a:link", xmlString); assertXpathExists(path + "/m:inline/a:entry/a:content", xmlString); assertXpathExists(path + "/m:inline/a:entry/a:content/m:properties", xmlString); assertXpathExists(path + "/m:inline/a:entry/a:content/m:properties/d:Id", xmlString); assertXpathExists(path + "/m:inline/a:entry/a:content/m:properties/d:Name", xmlString); assertXpathExists("/a:entry/a:content/m:properties/d:Id", xmlString); assertXpathExists("/a:entry/a:content/m:properties/d:Name", xmlString); assertXpathExists("/a:entry/a:content/m:properties/d:Seats", xmlString); } @Test public void contentOnlyWithoutKeyWithoutSelectedProperties() throws Exception { HashMap<String, Object> employeeData = new HashMap<String, Object>(); employeeData.put("ManagerId", "1"); employeeData.put("Age", new Integer(52)); employeeData.put("RoomId", "1"); employeeData.put("TeamId", "42"); List<String> selectedProperties = new ArrayList<String>(); selectedProperties.add("ManagerId"); selectedProperties.add("Age"); selectedProperties.add("RoomId"); selectedProperties.add("TeamId"); final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); EntityProviderWriteProperties properties = EntityProviderWriteProperties.fromProperties(DEFAULT_PROPERTIES).contentOnly(true).build(); AtomEntityProvider ser = createAtomEntityProvider(); try { ser.writeEntry(entitySet, employeeData, properties); } catch (EntityProviderProducerException e) { assertTrue(e.getMessage().contains("The metadata do not allow a null value for property 'EmployeeId'")); } } @Test public void testWithoutKey() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); List<String> selectedPropertyNames = new ArrayList<String>(); selectedPropertyNames.add("ManagerId"); ExpandSelectTreeNode select = ExpandSelectTreeNode.entitySet(entitySet).selectedProperties(selectedPropertyNames).build(); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).expandSelectTree(select).build(); Map<String, Object> localEmployeeData = new HashMap<String, Object>(); localEmployeeData.put("ManagerId", "1"); AtomEntityProvider ser = createAtomEntityProvider(); try { ser.writeEntry(entitySet, localEmployeeData, properties); } catch (EntityProviderProducerException e) { assertTrue(e.getMessage().contains("The metadata do not allow a null value for property 'EmployeeId'")); } } @Test public void testWithoutCompositeKey() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build(); Map<String, Object> photoData = new HashMap<String, Object>(); photoData.put("Name", "Mona Lisa"); AtomEntityProvider ser = createAtomEntityProvider(); try { ser.writeEntry(entitySet, photoData, properties); } catch (EntityProviderProducerException e) { assertTrue(e.getMessage().contains("The metadata do not allow a null value for property 'Id'")); } } @Test public void testWithoutCompositeKeyWithOneKeyNull() throws Exception { Edm edm = MockFacade.getMockEdm(); EdmEntitySet entitySet = edm.getEntityContainer("Container2").getEntitySet("Photos"); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build(); Map<String, Object> photoData = new HashMap<String, Object>(); photoData.put("Name", "Mona Lisa"); photoData.put("Id", Integer.valueOf(1)); EdmTyped typeProperty = edm.getEntityContainer("Container2").getEntitySet("Photos"). getEntityType().getProperty("Type"); EdmFacets facets = mock(EdmFacets.class); when(facets.getConcurrencyMode()).thenReturn(EdmConcurrencyMode.Fixed); when(facets.getMaxLength()).thenReturn(3); when(((EdmProperty) typeProperty).getFacets()).thenReturn(facets); AtomEntityProvider ser = createAtomEntityProvider(); try { ser.writeEntry(entitySet, photoData, properties); } catch (EntityProviderProducerException e) { assertTrue(e.getMessage().contains("The metadata do not allow a null value for property 'Type'")); } } @Test public void testExceptionWithNonNullablePropertyIsNull() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Organizations"); EdmProperty nameProperty = (EdmProperty) entitySet.getEntityType().getProperty("Name"); EdmFacets facets = nameProperty.getFacets(); when(facets.isNullable()).thenReturn(new Boolean(false)); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).omitETag(true). isDataBasedPropertySerialization(true).build(); AtomEntityProvider ser = createAtomEntityProvider(); Map<String, Object> orgData = new HashMap<String, Object>(); orgData.put("Id", "1"); try { ser.writeEntry(entitySet, orgData, properties); } catch (EntityProviderProducerException e) { assertTrue(e.getMessage().contains("The metadata do not allow a null value for property 'Name'")); } } @Test public void testExceptionWithNonNullablePropertyIsNull1() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Organizations"); EdmProperty kindProperty = (EdmProperty) entitySet.getEntityType().getProperty("Kind"); EdmFacets facets = kindProperty.getFacets(); when(facets.isNullable()).thenReturn(new Boolean(false)); EdmProperty nameProperty = (EdmProperty) entitySet.getEntityType().getProperty("Name"); when(nameProperty.getFacets()).thenReturn(null); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).omitETag(true). isDataBasedPropertySerialization(true).build(); AtomEntityProvider ser = createAtomEntityProvider(); Map<String, Object> orgData = new HashMap<String, Object>(); orgData.put("Id", "1"); orgData.put("Name", "Org1"); try { ser.writeEntry(entitySet, orgData, properties); } catch (EntityProviderProducerException e) { assertTrue(e.getMessage().contains("The metadata do not allow a null value for property 'Kind'")); } } @Test public void testExceptionWithNonNullablePropertyIsNull2() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Organizations"); EdmProperty kindProperty = (EdmProperty) entitySet.getEntityType().getProperty("Kind"); EdmFacets facets = kindProperty.getFacets(); when(facets.isNullable()).thenReturn(new Boolean(false)); EdmProperty nameProperty = (EdmProperty) entitySet.getEntityType().getProperty("Name"); EdmFacets facets1 = nameProperty.getFacets(); when(facets1.isNullable()).thenReturn(new Boolean(false)); final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).omitETag(true). isDataBasedPropertySerialization(true).build(); AtomEntityProvider ser = createAtomEntityProvider(); Map<String, Object> orgData = new HashMap<String, Object>(); orgData.put("Id", "1"); orgData.put("Name", "Org1"); try { ser.writeEntry(entitySet, orgData, properties); } catch (EntityProviderProducerException e) { assertTrue(e.getMessage().contains("do not allow to format the value 'Org1' for property 'Name'.")); } } }
49.586858
120
0.741914
fcc58cf361d3991b6ec68eca0fb7851e8614fd62
1,146
package me.desht.pneumaticcraft.api.item; import net.minecraft.item.Item; import java.util.List; public interface IItemRegistry { enum EnumUpgrade { VOLUME, DISPENSER, ITEM_LIFE, ENTITY_TRACKER, BLOCK_TRACKER, SPEED, SEARCH, COORDINATE_TRACKER, RANGE, SECURITY, THAUMCRAFT /*Only around when Thaumcraft is */ } /** * See {@link me.desht.pneumaticcraft.api.item.IInventoryItem} * * @param handler */ void registerInventoryItem(IInventoryItem handler); /** * Returns the upgrade item that is mapped to the asked type. */ Item getUpgrade(EnumUpgrade type); /** * When an instance of this registered, this will only add to the applicable upgrade's tooltip. * * @param upgradeAcceptor */ void registerUpgradeAcceptor(IUpgradeAcceptor upgradeAcceptor); /** * Can be used for custom upgrade items to handle tooltips. This will work for implementors registered via {@link IItemRegistry#registerUpgradeAcceptor(IUpgradeAcceptor)}. * * @param upgrade * @param tooltip */ void addTooltip(Item upgrade, List<String> tooltip); }
29.384615
175
0.693717
1ef4bc951acfd4eb08da12625cb9280f0fcaf825
632
/* Desafio 011 problema: Faça um programa que leia a largura e a algura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2m². resolução: */ import java.util.Scanner; class Main { public static void main(String[] args) { Scanner x = new Scanner(System.in); System.out.print("Largura: "); float largura = x.nextFloat(); System.out.print("Altura: "); float altura = x.nextFloat(); float area = largura * altura; System.out.printf("%.2fL de tinta\n", area/2); } }
30.095238
77
0.639241
5217ec740d74a8eb1c4e4ad579f5e63154025a64
6,486
package io.kubernetes.client.extended.controller.builder; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.junit.Assert.*; import com.github.tomakehurst.wiremock.junit.WireMockRule; import io.kubernetes.client.ApiClient; import io.kubernetes.client.JSON; import io.kubernetes.client.apis.CoreV1Api; import io.kubernetes.client.extended.controller.Controller; import io.kubernetes.client.extended.controller.reconciler.Reconciler; import io.kubernetes.client.extended.controller.reconciler.Request; import io.kubernetes.client.extended.controller.reconciler.Result; import io.kubernetes.client.informer.SharedIndexInformer; import io.kubernetes.client.informer.SharedInformerFactory; import io.kubernetes.client.models.*; import io.kubernetes.client.util.CallGeneratorParams; import io.kubernetes.client.util.ClientBuilder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Function; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class DefaultControllerBuilderTest { private SharedInformerFactory informerFactory = new SharedInformerFactory(); private ExecutorService controllerThead = Executors.newSingleThreadExecutor(); private ApiClient client; private static final int PORT = 8089; @Rule public WireMockRule wireMockRule = new WireMockRule(PORT); private final int stepCooldownIntervalInMillis = 500; private void cooldown() { try { Thread.sleep(stepCooldownIntervalInMillis); } catch (InterruptedException e) { e.printStackTrace(); } } @Before public void setUp() throws Exception { client = new ClientBuilder().setBasePath("http://localhost:" + PORT).build(); } @After public void tearDown() throws Exception {} @Test public void testWithLeaderElectorProxiesDefaultController() {} @Test(expected = IllegalStateException.class) public void testDummyBuildShouldFail() { ControllerBuilder.defaultBuilder(informerFactory).build(); } @Test public void testBuildWatchShouldWorkIfInformerPresent() { CoreV1Api api = new CoreV1Api(); informerFactory.sharedIndexInformerFor( (CallGeneratorParams params) -> { return api.listPodForAllNamespacesCall( null, null, null, null, null, params.resourceVersion, params.timeoutSeconds, params.watch, null, null); }, V1Pod.class, V1PodList.class); ControllerBuilder.defaultBuilder(informerFactory) .watch( (workQueue) -> ControllerBuilder.controllerWatchBuilder(V1Pod.class, workQueue).build()) .withReconciler( new Reconciler() { @Override public Result reconcile(Request request) { return new Result(false); } }) .build(); } @Test public void testControllerBuilderCustomizationShouldWork() { String testName = "test-controller"; int testWorkerCount = 1024; ExecutorService threadPool = Executors.newCachedThreadPool(); ControllerBuilder.defaultBuilder(informerFactory) .withName(testName) .withWorkerCount(testWorkerCount) .withWorkQueue(null) .withReconciler( new Reconciler() { @Override public Result reconcile(Request request) { return new Result(false); } }) .build(); } @Test public void testBuildWatchEventNotificationShouldWork() { V1PodList podList = new V1PodList() .metadata(new V1ListMeta().resourceVersion("0")) .items( Arrays.asList( new V1Pod() .metadata(new V1ObjectMeta().name("test-pod1")) .spec(new V1PodSpec().hostname("hostname1")))); stubFor( get(urlPathEqualTo("/api/v1/pods")) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(new JSON().serialize(podList)))); CoreV1Api api = new CoreV1Api(client); SharedIndexInformer<V1Pod> podInformer = informerFactory.sharedIndexInformerFor( (CallGeneratorParams params) -> { return api.listPodForAllNamespacesCall( null, null, null, null, null, params.resourceVersion, params.timeoutSeconds, params.watch, null, null); }, V1Pod.class, V1PodList.class); List<Request> keyFuncReceivingRequests = new ArrayList<>(); Function<V1Pod, Request> podKeyFunc = (V1Pod pod) -> { // twisting pod name key Request request = new Request(pod.getSpec().getHostname() + "/" + pod.getMetadata().getName()); keyFuncReceivingRequests.add(request); return request; }; List<Request> controllerReceivingRequests = new ArrayList<>(); Controller testController = ControllerBuilder.defaultBuilder(informerFactory) .withReconciler( new Reconciler() { @Override public Result reconcile(Request request) { controllerReceivingRequests.add(request); return new Result(false); } }) .watch( (workQueue) -> ControllerBuilder.controllerWatchBuilder(V1Pod.class, workQueue) .withWorkQueueKeyFunc(podKeyFunc) .build()) .build(); controllerThead.submit(testController::run); informerFactory.startAllRegisteredInformers(); Request expectedRequest = new Request("hostname1/test-pod1"); cooldown(); assertEquals(1, keyFuncReceivingRequests.size()); assertEquals(expectedRequest, keyFuncReceivingRequests.get(0)); assertEquals(1, controllerReceivingRequests.size()); assertEquals(expectedRequest, controllerReceivingRequests.get(0)); } }
32.592965
100
0.63136
60d46866148862ff43703ee5ea08e57500de7190
10,129
/* * Copyright (C) 2008 Google Inc. Licensed under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package ca.jvsh.cpu; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.ScrollView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; /** * * Main controller activity for CPUStatusLED application. * * Creates the display (table plus graph view) and connects to the * CPUStatusLEDService, starting it if necessary. Since the service will * directly update the display when it generates new data, references of the * display elements are passed to the service after binding. */ public class CPUStatusLEDActivity extends Activity implements OnSeekBarChangeListener /* seekbar */, OnClickListener/* buttons */ { private String TAG; View chart = null; public static boolean disabledLEDs = false; CPUStatusChart cpuStatusChart; /** * Service connection callback object used to establish communication with * the service after binding to it. */ private myServiceConnection mConnection; /** * Framework method called when the activity is first created. * */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TAG = this.getResources().getText(R.string.app_name).toString(); setContentView(R.layout.layout); startService(new Intent(this, CPUStatusLEDService.class)); mConnection = new myServiceConnection(this); if (cpuStatusChart == null) cpuStatusChart = new CPUStatusChart(); } /** * Framework method to create menu structure. */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); } /** * Framework method called when activity menu option is selected. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.disableleds: break; case R.id.help: break; case R.id.stop: stopService(new Intent(this, CPUStatusLEDService.class)); mConnection.mService.stopSelf(); mConnection.mService.stopService(getIntent()); finish(); if (mConnection.mService != null) System.exit(RESULT_OK);//service just wont die otherwise!!! case R.id.menu_settings: LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.settings, (ViewGroup) findViewById(R.id.layout_root)); AlertDialog.Builder builder; builder = new AlertDialog.Builder(this); builder.setView(layout); alertDialog = builder.create(); alertDialog.show(); dialogView = layout; setListenersAndValues(alertDialog); break; } return true; } private View dialogView; private AlertDialog alertDialog; private void setListenersAndValues(AlertDialog alertDialog) { Button ok = (Button) (dialogView.findViewById(R.id.buttonok)); ok.setOnClickListener(this); Button cancel = (Button) (dialogView.findViewById(R.id.buttoncancel)); cancel.setOnClickListener(this); //row1 SeekBar t1 = (SeekBar) dialogView.findViewById(R.id.seekbar1); t1.setOnSeekBarChangeListener(this); t1.setMax(100); t1.setKeyProgressIncrement(1); TextView tv1 = (TextView) dialogView.findViewById(R.id.threshold1); tv1.setText("" + t1.getProgress()); //row2 SeekBar t2 = (SeekBar) dialogView.findViewById(R.id.seekbar2); t2.setOnSeekBarChangeListener(this); t2.setMax(100); t2.setKeyProgressIncrement(1); TextView tv2 = (TextView) dialogView.findViewById(R.id.threshold2); tv2.setText("" + t2.getProgress()); //row3 SeekBar t3 = (SeekBar) dialogView.findViewById(R.id.seekbar3); t3.setOnSeekBarChangeListener(this); t3.setMax(100); t3.setKeyProgressIncrement(1); TextView tv3 = (TextView) dialogView.findViewById(R.id.threshold3); tv3.setText("" + t3.getProgress()); //row4 SeekBar t4 = (SeekBar) dialogView.findViewById(R.id.seekbar4); t4.setOnSeekBarChangeListener(this); t4.setMax(100); t4.setKeyProgressIncrement(1); TextView tv4 = (TextView) dialogView.findViewById(R.id.threshold4); tv4.setText("" + t4.getProgress()); } /** * Framework method called when activity becomes the foreground activity. * * onResume/onPause implement the most narrow window of activity life-cycle * during which the activity is in focus and foreground. */ @Override public void onResume() { super.onResume(); bindService(new Intent(this, CPUStatusLEDService.class), mConnection, Context.BIND_AUTO_CREATE); } /** * Framework method called when activity looses foreground position */ @Override public void onPause() { super.onPause(); unbindService(mConnection); } public void setCPUValues(String value) { TextView tv = (TextView) this.findViewById(R.id.widget31); tv.setText(value); } public void updateGraph(ArrayList<Integer> userHistory, ArrayList<Integer> systemHistory, ArrayList<Integer> signalHistory, ArrayList<String> topProcesses) { if (topProcesses != null && topProcesses.size() >= 3) { ((TextView) this.findViewById(R.id.top_process)).setText(topProcesses.get(0) + " " + topProcesses.get(1) + " " + topProcesses.get(2)); } else { ((TextView) this.findViewById(R.id.top_process)).setText(""); } chart = cpuStatusChart.createView(this, userHistory, systemHistory, signalHistory); chart.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); ScrollView sv = (ScrollView) this.findViewById(R.id.scrollview); sv.removeAllViews(); sv.addView(chart); } public void showExitContinueAlert(String msg) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(msg).setCancelable(false).setPositiveButton("Exit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //mConnection.mService.stopSelf(); mConnection.mService.stopService(getIntent()); CPUStatusLEDActivity.this.finish(); System.exit(0); } }).setNegativeButton("Continue", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.create().show(); } public void onProgressChanged(SeekBar view, int progress, boolean fromuser) { if (!fromuser) return; Log.i(TAG, "onProgressChanged"); if (view.getId() == R.id.seekbar1) { ((TextView) dialogView.findViewById(R.id.threshold1)).setText("" + progress); adjustSeekBars(); } if (view.getId() == R.id.seekbar2) { ((TextView) dialogView.findViewById(R.id.threshold2)).setText("" + progress); adjustSeekBars(); } if (view.getId() == R.id.seekbar3) { ((TextView) dialogView.findViewById(R.id.threshold3)).setText("" + progress); adjustSeekBars(); } if (view.getId() == R.id.seekbar4) { ((TextView) dialogView.findViewById(R.id.threshold4)).setText("" + progress); adjustSeekBars(); } } private void adjustSeekBars() { //1->4 if (((SeekBar) dialogView.findViewById(R.id.seekbar1)).getProgress() > ((SeekBar) dialogView.findViewById(R.id.seekbar2)).getProgress()) { ((SeekBar) dialogView.findViewById(R.id.seekbar2)).setProgress((((SeekBar) dialogView.findViewById(R.id.seekbar1)).getProgress() + 1 % 101)); ((TextView) dialogView.findViewById(R.id.threshold2)).setText("" + ((SeekBar) dialogView.findViewById(R.id.seekbar2)).getProgress()); } if (((SeekBar) dialogView.findViewById(R.id.seekbar2)).getProgress() > ((SeekBar) dialogView.findViewById(R.id.seekbar3)).getProgress()) { ((SeekBar) dialogView.findViewById(R.id.seekbar3)).setProgress((((SeekBar) dialogView.findViewById(R.id.seekbar2)).getProgress() + 1 % 101)); ((TextView) dialogView.findViewById(R.id.threshold3)).setText("" + ((SeekBar) dialogView.findViewById(R.id.seekbar3)).getProgress()); } if (((SeekBar) dialogView.findViewById(R.id.seekbar3)).getProgress() > ((SeekBar) dialogView.findViewById(R.id.seekbar4)).getProgress()) { ((SeekBar) dialogView.findViewById(R.id.seekbar4)).setProgress((((SeekBar) dialogView.findViewById(R.id.seekbar3)).getProgress() + 1 % 101)); ((TextView) dialogView.findViewById(R.id.threshold4)).setText("" + ((SeekBar) dialogView.findViewById(R.id.seekbar4)).getProgress()); } } public void onStartTrackingTouch(SeekBar arg0) { } public void onStopTrackingTouch(SeekBar arg0) { } public void onClick(View view) { //Log.i(TAG,"onClick"); if (view.getId() == R.id.buttonok) { savePreferences(); alertDialog.dismiss(); } if (view.getId() == R.id.buttoncancel) { alertDialog.dismiss(); } } private void savePreferences() { Toast.makeText(this, "Preferences saved.", Toast.LENGTH_SHORT).show(); Log.i(TAG, "Saved prefs"); } //needed otherwise the activity/dialog is destroyed on rotate. public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } }
31.166154
156
0.728502
411b7b2d154dbe3e7abc53842351e67d811ea539
2,646
/* * Copyright 2020 Kato Shinya. * * 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.thinkit.formatter.ddl; import org.thinkit.common.exception.IllegalNumberFoundException; import org.thinkit.formatter.catalog.ddl.DdlStatement; import org.thinkit.formatter.common.Formatter; import lombok.EqualsAndHashCode; import lombok.NonNull; import lombok.ToString; /** * SQLにおけるDDLクエリを整形する処理を定義したフォーマッタクラスです。 * * @author Kato Shinya * @since 1.0 * @version 1.0 */ @ToString @EqualsAndHashCode public final class DdlFormatter implements Formatter { /** * インデント数 */ private int indent; /** * デフォルトコンストラクタ */ private DdlFormatter() { this.indent = 4; } /** * コンストラクタ * * @param indent インデント数 */ private DdlFormatter(int indent) { this.indent = indent; } /** * {@link DdlFormatter} クラスの新しいインスタンスを生成し返却します。 * * @return {@link DdlFormatter} クラスの新しいインスタンス */ public static Formatter of() { return new DdlFormatter(); } /** * 引数として指定された {@code indent} の数値に応じた {@link DdlFormatter} * クラスの新しいインスタンスを生成し返却します。 * * @param indent インデント数 * @return {@code indent} の数値に応じた {@link DdlFormatter} クラスの新しいインスタンス * * @throws IllegalNumberFoundException 引数として指定された {@code indent} の数値が負数の場合 */ public static Formatter withIndent(int indent) { return new DdlFormatter(indent); } @Override public String format(@NonNull final String sql) { final String trimmedSql = sql.trim(); final String lowercaseSql = sql.toLowerCase(); if (lowercaseSql.startsWith(DdlStatement.CREATE_TABLE.getTag())) { return CreateTableFormatter.withIndent(this.indent).format(sql); } else if (lowercaseSql.startsWith(DdlStatement.ALTER_TABLE.getTag())) { return AlterTableFormatter.withIndent(this.indent).format(sql); } else if (lowercaseSql.startsWith(DdlStatement.COMMENT_ON.getTag())) { return CommentOnFormatter.withIndent(this.indent).format(sql); } return trimmedSql; } }
27.852632
100
0.676493
c0f693f4614880a971225dddbac8b5bd044d53a4
12,440
package fortifyscanner.ui.view; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.ui.part.ViewPart; import fortifyscanner.listener.FortifyConsoleViewRightClickMenuSelectionListener; import fortifyscanner.listener.FortifyIssueDoubleClickListener; import fortifyscanner.model.FortifyIssueDto; import fortifyscanner.model.FortifyScanResultDto; import fortifyscanner.util.DBUtils; /** * Custom View Class named as Fortify On the Fly. Can be opened via the menu: * Window -> Show View -> Fortify-On-the-Fly. * * @author Umut * */ public class FortifyConsoleView extends ViewPart { public static final String RIGHT_CLICK_MENU_ITEM_1_STR = "Ignore Line just once"; public static final String RIGHT_CLICK_MENU_ITEM_2_STR = "Ignore Category just once"; public static final String RIGHT_CLICK_MENU_ITEM_3_STR = "Ignore Category for this Workspace Projects only"; public static final String RIGHT_CLICK_MENU_ITEM_4_STR = "Ignore Category for every Java Project in this computer"; private TableViewer viewer; private Table table; private FortifyScanResultDto data; /** * Refreshes the data of the Custom View * * @param newData new data of the view. */ public void refreshFortifyConsoleData(FortifyScanResultDto newData) { data = newData; List<FortifyIssueDto> issues = data.getIssues(); issues = DBUtils.eliminateIgnoredRulesAtWorkspaceScope(DBUtils.eliminateIgnoredRulesAtUserScope(issues)); data.setIssues(issues); viewer.setInput(data); } /** * Removes given row from the output set and refreshes the view, does not create an ignore list so if scan is refreshed * ignored item/items re appear again. * @param rowToRemove row to remove */ public void removeDataFromResult(FortifyIssueDto rowToRemove) { FortifyScanResultDto currentResult = (FortifyScanResultDto)viewer.getInput(); if(currentResult != null && currentResult.getIssues() != null) { List<FortifyIssueDto> currentIssues = currentResult.getIssues(); currentIssues.remove(rowToRemove); viewer.setInput(currentResult); } } /** * Removes all rows having the given category and subcategory from the scan outputs. If scan is refreshed they * reappear again. * @param category category to remove * @param subCategory subcategory to remove (if null, all nulls are taken into consideration) */ public void removeDataWithCategoryAndSubCategoryFromResult(String category, String subCategory) { FortifyScanResultDto currentResult = (FortifyScanResultDto)viewer.getInput(); if(currentResult != null && currentResult.getIssues() != null) { List<FortifyIssueDto> currentIssues = currentResult.getIssues(); List<Integer> indexesToRemove = new ArrayList<>(); int index = -1; for(FortifyIssueDto current : currentIssues) { index++; if(current.getReason().equals(category) && ((subCategory == null && current.getDescription() == null) || subCategory != null && subCategory.equals(current.getDescription()))) { indexesToRemove.add(index); } } indexesToRemove.sort(Comparator.reverseOrder()); for(int indexToRemove : indexesToRemove) { currentIssues.remove(indexToRemove); } viewer.setInput(currentResult); } } @Override public void createPartControl(Composite parent) { int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION; table = new Table(parent, style); setUpMouseRightClickListenerOnTable(); viewer = new TableViewer(table); enrichTable(table, parent, viewer); viewer.setContentProvider(new FortifyConsoleContentProvider()); viewer.setLabelProvider(new FortifyConsoleLabelProvider()); viewer.setInput(data); viewer.addDoubleClickListener(new FortifyIssueDoubleClickListener(viewer)); } private void setUpMouseRightClickListenerOnTable() { Menu menu = new Menu(table); table.setMenu(menu); MenuItem menuItem1 = new MenuItem(menu, SWT.None); MenuItem menuItem2 = new MenuItem(menu, SWT.None); MenuItem menuItem3 = new MenuItem(menu, SWT.None); MenuItem menuItem4 = new MenuItem(menu, SWT.None); menuItem1.setText(RIGHT_CLICK_MENU_ITEM_1_STR); menuItem2.setText(RIGHT_CLICK_MENU_ITEM_2_STR); menuItem3.setText(RIGHT_CLICK_MENU_ITEM_3_STR); menuItem4.setText(RIGHT_CLICK_MENU_ITEM_4_STR); FortifyConsoleViewRightClickMenuSelectionListener selectionListener = new FortifyConsoleViewRightClickMenuSelectionListener(this); menuItem1.addSelectionListener(selectionListener); menuItem2.addSelectionListener(selectionListener); menuItem3.addSelectionListener(selectionListener); menuItem4.addSelectionListener(selectionListener); table.addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { TableItem selectedItem = table.getItem(new Point(event.x,event.y)); if (selectedItem != null) { selectionListener.setSelectedFortifyIssueData(selectedItem); table.setMenu(menu); } else { table.setMenu(null); } } }); } private void enrichTable(Table table, Composite parent, TableViewer tableViewer) { GridData gridData = new GridData(GridData.FILL_BOTH); gridData.grabExcessVerticalSpace = true; gridData.horizontalSpan = 3; table.setLayoutData(gridData); table.setLinesVisible(true); table.setHeaderVisible(true); TableColumn column; // ID column = new TableColumn(table, SWT.LEFT, 0); column.setText("ID"); column.setWidth(150); column.addSelectionListener(new SearchResultSortListener("ID")); // SEVERITY column = new TableColumn(table, SWT.LEFT, 1); column.setText("Severity"); column.setWidth(100); column.addSelectionListener(new SearchResultSortListener("Criticality")); // LOCATION column = new TableColumn(table, SWT.LEFT, 2); column.setText("Location"); column.setWidth(200); column.addSelectionListener(new SearchResultSortListener("Path")); // REASON column = new TableColumn(table, SWT.LEFT, 3); column.setText("Reason"); column.setWidth(250); column.addSelectionListener(new SearchResultSortListener("Category")); // DESCRIPTION column = new TableColumn(table, SWT.LEFT, 4); column.setText("Description"); column.setWidth(450); column.addSelectionListener(new SearchResultSortListener("Subcategory")); // TYPE column = new TableColumn(table, SWT.LEFT, 5); column.setText("Type"); column.setWidth(140); column.addSelectionListener(new SearchResultSortListener("Analyzer")); } @Override public void setFocus() { viewer.getControl().setFocus(); } /** * Content provider - Content converter from a list of data into Array of data * to fill the custom table. * * @author Umut * */ class FortifyConsoleContentProvider implements IStructuredContentProvider { @Override public Object[] getElements(Object fcrAsObj) { FortifyScanResultDto fcr = (FortifyScanResultDto) fcrAsObj; return fcr.getIssues().toArray(); } } /** * Info mapper for the columns. * * @author Umut * */ class FortifyConsoleLabelProvider implements ITableLabelProvider { @Override public void addListener(ILabelProviderListener arg0) { } @Override public void dispose() { } @Override public boolean isLabelProperty(Object arg0, String arg1) { return false; } @Override public void removeListener(ILabelProviderListener arg0) { } @Override public Image getColumnImage(Object arg0, int arg1) { return null; } @Override public String getColumnText(Object el, int index) { String result = ""; FortifyIssueDto fi = (FortifyIssueDto) el; switch (index) { case 0: result = fi.getId(); break; case 1: result = fi.getSeverity(); break; case 2: result = fi.getLocation(); break; case 3: result = fi.getReason(); break; case 4: result = fi.getDescription(); break; case 5: result = fi.getType(); break; default: break; } return result; } } /** * Sorter Utility for each data attribute, triggered when the Column Headers is * clicked. * * @author Umut * */ class SearchResultSortListener extends SelectionAdapter { // I changed the column label names to more known expressions by fortify users. public static final String DESCRIPTION_KEY = "Subcategory"; public static final String ID_KEY = "ID"; public static final String SEVERITY_KEY = "Criticality"; public static final String LOCATION_KEY = "Path"; public static final String REASON_KEY = "Category"; public static final String TYPE_KEY = "Analyzer"; private Map<String, Integer> sortAscendingOrDescending = new HashMap<>(); private String sortType; public SearchResultSortListener(String sortType) { this.sortType = sortType; sortAscendingOrDescending.put(DESCRIPTION_KEY, 0); sortAscendingOrDescending.put(ID_KEY, 0); sortAscendingOrDescending.put(SEVERITY_KEY, 0); sortAscendingOrDescending.put(LOCATION_KEY, 0); sortAscendingOrDescending.put(REASON_KEY, 0); sortAscendingOrDescending.put(TYPE_KEY, 0); } @Override public void widgetSelected(final SelectionEvent e) { List<FortifyIssueDto> issues = data.getIssues(); switch (sortType) { case DESCRIPTION_KEY: if (sortAscendingOrDescending.get(DESCRIPTION_KEY) == 0) { issues.sort(Comparator.comparing(FortifyIssueDto::getDescription)); sortAscendingOrDescending.put(DESCRIPTION_KEY, 1); } else { // ==1 issues.sort(Comparator.comparing(FortifyIssueDto::getDescription, Comparator.reverseOrder())); sortAscendingOrDescending.put(DESCRIPTION_KEY, 0); } break; case ID_KEY: if (sortAscendingOrDescending.get(ID_KEY) == 0) { issues.sort(Comparator.comparing(FortifyIssueDto::getId)); sortAscendingOrDescending.put(ID_KEY, 1); } else { // ==1 issues.sort(Comparator.comparing(FortifyIssueDto::getId, Comparator.reverseOrder())); sortAscendingOrDescending.put(ID_KEY, 0); } break; case SEVERITY_KEY: if (sortAscendingOrDescending.get(SEVERITY_KEY) == 0) { issues.sort(Comparator.comparing(FortifyIssueDto::getSeverity)); sortAscendingOrDescending.put(SEVERITY_KEY, 1); } else { // ==1 issues.sort(Comparator.comparing(FortifyIssueDto::getSeverity, Comparator.reverseOrder())); sortAscendingOrDescending.put(SEVERITY_KEY, 0); } break; case LOCATION_KEY: if (sortAscendingOrDescending.get(LOCATION_KEY) == 0) { issues.sort(Comparator.comparing(FortifyIssueDto::getLocation)); sortAscendingOrDescending.put(LOCATION_KEY, 1); } else { // ==1 issues.sort(Comparator.comparing(FortifyIssueDto::getLocation, Comparator.reverseOrder())); sortAscendingOrDescending.put(LOCATION_KEY, 0); } break; case REASON_KEY: if (sortAscendingOrDescending.get(REASON_KEY) == 0) { issues.sort(Comparator.comparing(FortifyIssueDto::getReason)); sortAscendingOrDescending.put(REASON_KEY, 1); } else { // ==1 issues.sort(Comparator.comparing(FortifyIssueDto::getReason, Comparator.reverseOrder())); sortAscendingOrDescending.put(REASON_KEY, 0); } break; case TYPE_KEY: if (sortAscendingOrDescending.get(TYPE_KEY) == 0) { issues.sort(Comparator.comparing(FortifyIssueDto::getType)); sortAscendingOrDescending.put(TYPE_KEY, 1); } else { // ==1 issues.sort(Comparator.comparing(FortifyIssueDto::getType, Comparator.reverseOrder())); sortAscendingOrDescending.put(TYPE_KEY, 0); } break; } viewer.setInput(data); } } }
32.311688
132
0.741158
b9aa73b0e0ea4a80ffbe7084c070d36a7b498732
948
public class NonRecursiveMergeSort<T extends Comparable<T>> { public T[] MergeSort(T[] M) { int length = M.length; int size = 1; int p; while (size < length) { p = -1; while (p + size < length) { int left = p + 1; int right = left + size - 1; if (right + size <= length) { p = right + size; } else { p = length; } merge(M, left, right, p); } size = size * 2; } return M; } public T[] merge(T[] M, int left, int right, int p) { int i = left; int j = right + 1; int k = left; T[] M2 = M.clone(); for (int n = 0; n < M.length; n++) { M2[n] = null; } while (i <= right && j <= p) { if (M[i].compareTo(M[j]) <= 0) { M2[k] = M[i]; i = i + 1; } else { M2[k] = M[j]; j = j + 1; } k = k + 1; } for (int h = i; h <= right; h++) { M[k + (h - i)] = M[h]; } for (int h = left; h <= (k - 1); h++) { M[h] = M2[h]; } return M; } }
16.631579
61
0.440928
e761299e91a29cb4849f15f3d5a9b4b97249b5a3
950
/* * Copyright (C) 2020 Alibaba Group Holding Limited */ package com.aliyun.auth.model; /** * 创建视频凭证的Response * Created by Mulberry on 2017/11/3. */ public class CreateVideoForm { private String RequestId; private String UploadAddress; private String UploadAuth; private String VideoId; public String getRequestId() { return RequestId; } public void setRequestId(String requestId) { RequestId = requestId; } public String getUploadAddress() { return UploadAddress; } public void setUploadAddress(String uploadAddress) { UploadAddress = uploadAddress; } public String getUploadAuth() { return UploadAuth; } public void setUploadAuth(String uploadAuth) { UploadAuth = uploadAuth; } public String getVideoId() { return VideoId; } public void setVideoId(String videoId) { VideoId = videoId; } }
19.387755
56
0.649474
7fdc41f909b1092acd7e11b84b3fbc9a2e895672
4,702
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.intentions; import com.jetbrains.python.PyPsiBundle; import com.jetbrains.python.PyPsiBundle; import com.jetbrains.python.psi.LanguageLevel; /** * @author Mikhail Golubev */ public class PyConvertCollectionLiteralIntentionTest extends PyIntentionTestCase { // PY-9419 public void testConvertParenthesizedTupleToList() { doIntentionTest(getConvertTupleToList()); } // PY-9419 public void testConvertTupleWithoutParenthesesToList() { doIntentionTest(getConvertTupleToList()); } // PY-9419 public void testConvertTupleWithoutClosingParenthesisToList() { doIntentionTest(getConvertTupleToList()); } // PY-9419 public void testConvertParenthesizedTupleToSet() { doIntentionTest(getConvertTupleToSet()); } // PY-9419 public void testConvertTupleToSetNotAvailableWithoutSetLiterals() { runWithLanguageLevel(LanguageLevel.PYTHON26, () -> doNegativeTest(getConvertTupleToSet())); } // PY-9419 public void testConvertTupleToSetNotAvailableInAssignmentTarget() { doNegativeTest(getConvertTupleToSet()); } // PY-9419 public void testConvertTupleToSetNotAvailableInForLoop() { doNegativeTest(getConvertTupleToSet()); } // PY-9419 public void testConvertTupleToSetNotAvailableInComprehension() { doNegativeTest(getConvertTupleToSet()); } // PY-9419 public void testConvertListToTuple() { doIntentionTest(getConvertListToTuple()); } // PY-9419 public void testConvertListWithoutClosingBracketToTuple() { doIntentionTest(getConvertListToTuple()); } // PY-9419 public void testConvertListToSet() { doIntentionTest(getConvertListToSet()); } // PY-9419 public void testConvertSetToTuple() { doIntentionTest(getConvertSetToTuple()); } // PY-9419 public void testConvertSetWithoutClosingBraceToTuple() { doIntentionTest(getConvertSetToTuple()); } // PY-9419 public void testConvertSetToList() { doIntentionTest(getConvertSetToList()); } // PY-16335 public void testConvertLiteralPreservesFormattingAndComments() { doIntentionTest(getConvertTupleToList()); } // PY-16553 public void testConvertOneElementListToTuple() { doIntentionTest(getConvertListToTuple()); } // PY-16553 public void testConvertOneElementIncompleteListToTuple() { doIntentionTest(getConvertListToTuple()); } // PY-16553 public void testConvertOneElementListWithCommentToTuple() { doIntentionTest(getConvertListToTuple()); } // PY-16553 public void testConvertOneElementListWithCommaAfterCommentToTuple() { doIntentionTest(getConvertListToTuple()); } // PY-16553 public void testConvertOneElementTupleToList() { doIntentionTest(getConvertTupleToList()); } // PY-16553 public void testConvertOneElementTupleWithoutParenthesesToSet() { doIntentionTest(getConvertTupleToSet()); } // PY-16553 public void testConvertOneElementTupleWithCommentToList() { doIntentionTest(getConvertTupleToList()); } // PY-19399 public void testCannotConvertEmptyTupleToSet() { doNegativeTest(getConvertTupleToSet()); } // PY-19399 public void testCannotConvertEmptyListToSet() { doNegativeTest(getConvertListToSet()); } private static String getConvertTupleToList() { return PyPsiBundle.message("INTN.convert.collection.literal.text", "tuple", "list"); } private static String getConvertTupleToSet() { return PyPsiBundle.message("INTN.convert.collection.literal.text", "tuple", "set"); } private static String getConvertListToTuple() { return PyPsiBundle.message("INTN.convert.collection.literal.text", "list", "tuple"); } private static String getConvertListToSet() { return PyPsiBundle.message("INTN.convert.collection.literal.text", "list", "set"); } private static String getConvertSetToTuple() { return PyPsiBundle.message("INTN.convert.collection.literal.text", "set", "tuple"); } private static String getConvertSetToList() { return PyPsiBundle.message("INTN.convert.collection.literal.text", "set", "list"); } }
27.658824
95
0.744577
408702a262a338a891aacf27f1c94f5c95e71a70
6,185
/* * Copyright (c) 2017, Regents of the University of Massachusetts Amherst * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the University of Massachusetts Amherst nor the names of its contributors * may be used to endorse or promote products derived from this software without specific prior written * permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.umass.cs.sase.explanation.evaluation; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import edu.umass.cs.sase.explanation.distancefunction.TimeSeriesFeaturePair; /** * Used to evaluate the ground truth * Input: ground truth; results from some algorithms * Output: the precision/recall/f-measure of the results * @author haopeng * */ public class EvaluationEngine { String groundTruthFilePath; HashSet<String> groundTruth; ArrayList<HashSet<String>> clusterList; HashMap<String, TimeSeriesFeaturePair> topFeatureIndex; int totalFeatureSpaceSize; //set double setPrecision; double setRecall; double setFMeasure; double setAccuracy; //cluster int goodCluster; int badCluster; double clusterPrecision; double clusterRecall; double clusterFMeasure; double clusterAccuracy; public EvaluationEngine() { } public EvaluationEngine(String groundTruthFilePath) throws IOException { this.groundTruthFilePath = groundTruthFilePath; this.readGroundTruth(); } /** * * @param clusterList the clustered results * @param featureSet all features in one set */ public void evaluateResult(ArrayList<HashSet<String>> clusterList, HashMap<String, TimeSeriesFeaturePair> topFeatureIndex, int totalFeatures) { this.clusterList = clusterList; this.topFeatureIndex = topFeatureIndex; this.totalFeatureSpaceSize = totalFeatures; //evaluate precision recall for top features this.evaluateForFeatureSet(); //count good clusters, and compute precision/recall for cluster this.evaluateForCluster(); //print results this.printResult(); } public void printResult() { System.out.println("TotalNumOfFeatures\tSelectedFeatures\tNumOfClusters\tNumOfFeaturesInGroundTruth\t" + "SetPrecision\tSetRecall\tSetF-Measure\tSetAccuracy\t" + "NumOfGoodCluster\tNumOfBadCluster\tClusterPrecision"); System.out.println(this.totalFeatureSpaceSize + "\t" + this.topFeatureIndex.size() + "\t" + this.clusterList.size() + "\t" + this.groundTruth.size() + "\t" + this.setPrecision + "\t" + this.setRecall + "\t" + this.setFMeasure + "\t" + this.setAccuracy + "\t" + this.goodCluster + "\t" + this.badCluster + "\t" + this.clusterPrecision); } /** * How to define precision/recall for cluster?? */ public void evaluateForCluster() { this.goodCluster = 0; for (HashSet<String> cluster : this.clusterList) { for (String str : cluster) { if (this.groundTruth.contains(str)) { goodCluster ++; break; } } } this.badCluster = this.clusterList.size() - this.goodCluster; int tp = this.goodCluster; int fp = this.badCluster; this.clusterPrecision = (double)tp/(double)(tp + fp); } public void evaluateForFeatureSet() { int tp = 0;//in ground truth; in result int fp = 0;//not in ground truth; in result int tn = 0;//not in ground truth; not in result int fn = 0;//in ground truth; not in result for (String str: this.topFeatureIndex.keySet()) { if (this.groundTruth.contains(str)) { tp ++; } else { fp ++; } } fn = this.groundTruth.size() - tp; tn = this.totalFeatureSpaceSize - this.topFeatureIndex.size(); //precision:https://en.wikipedia.org/wiki/Precision_and_recall this.setPrecision = (double) tp / (double)(tp + fp); //recall: \mathit{TPR} = \mathit{TP} / P = \mathit{TP} / (\mathit{TP}+\mathit{FN}) this.setRecall = (double) tp / (double)(tp + fn); //f-measure this.setFMeasure = 2 * (double) tp / (double)(2 * tp + fp + fn); //accuracy this.setAccuracy = (double)(tp + tn)/(double)this.totalFeatureSpaceSize; } public void readGroundTruth() throws IOException { this.groundTruth = new HashSet<String>(); BufferedReader reader = new BufferedReader(new FileReader(this.groundTruthFilePath)); String line; while ((line = reader.readLine()) != null) { if (!line.startsWith("#")) { this.groundTruth.add(line); } } reader.close(); System.out.println("~~~~~~~~" + this.groundTruth.size() + " features are read as ground truth~~~~~~~~"); for (String str : groundTruth) { System.out.println(str); } System.out.println("~~~~~~~End of ground truth~~~~~~~~~~"); } public static void main(String[] args) throws IOException { String groundTruth = "/Users/haopeng/Dropbox/code/workspace/sase-opensource/queries/3rd/case1/b3.truth"; EvaluationEngine engine = new EvaluationEngine(groundTruth); } }
34.361111
157
0.720776
a85cfa48baa95461d6d4586edd2b749ea3875ebf
405
package edu.gemini.spModel.template; import edu.gemini.pot.sp.ISPFactory; import edu.gemini.pot.sp.ISPNode; import edu.gemini.pot.sp.ISPNodeInitializer; public final class TemplateParametersNI implements ISPNodeInitializer { public void initNode(ISPFactory factory, ISPNode node) { node.setDataObject(new TemplateParameters()); } public void updateNode(ISPNode node) { } }
22.5
71
0.753086
6d03c6232798af86b9cda990fd66d8a97bb1d7f7
1,745
package cj.solstice.swing.sfind; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JButton; import javax.swing.UIManager; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class TestSfind extends JFrame { private static final long serialVersionUID = 1L; private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); TestSfind frame = new TestSfind(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public TestSfind() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(); contentPane.add(scrollPane, BorderLayout.CENTER); final JTextArea textArea = new JTextArea("jhones\nhjones\njhones\njhones"); scrollPane.setViewportView(textArea); final SFind find = new SFind(textArea); JButton btnFind = new JButton("Find"); btnFind.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { find.setVisible(true); } }); contentPane.add(btnFind, BorderLayout.SOUTH); } }
25.661765
78
0.699713
e7a85dcea4fd08800c719386fc9832b37ec60d79
249
package RMI_Chat; import java.rmi.Remote; import java.rmi.RemoteException; public interface ChatClientInterface extends Remote { public String getName() throws RemoteException; public void print(String message) throws RemoteException; }
20.75
61
0.795181
95f0b9a64774941437887a1475e5a6096ae34e88
6,659
package seedu.exercise.model.util; import static seedu.exercise.model.resource.ResourceComparator.DEFAULT_EXERCISE_COMPARATOR; import static seedu.exercise.model.resource.ResourceComparator.DEFAULT_REGIME_COMPARATOR; import static seedu.exercise.model.resource.ResourceComparator.DEFAULT_SCHEDULE_COMPARATOR; import java.util.Arrays; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import seedu.exercise.model.ReadOnlyResourceBook; import seedu.exercise.model.SortedUniqueResourceList; import seedu.exercise.model.property.Calories; import seedu.exercise.model.property.Date; import seedu.exercise.model.property.Muscle; import seedu.exercise.model.property.Name; import seedu.exercise.model.property.Quantity; import seedu.exercise.model.property.Unit; import seedu.exercise.model.resource.Exercise; import seedu.exercise.model.resource.Regime; import seedu.exercise.model.resource.Schedule; /** * Contains utility methods for populating {@code ReadOnlyResourceBook} with sample data. */ public class SampleDataUtil { public static Exercise[] getSampleExercises() { return new Exercise[]{ new Exercise(new Name("Rope Skipping"), new Date("12/11/2019"), new Calories("100"), new Quantity("10"), new Unit("counts"), getMuscleSet("Legs"), new TreeMap<>()), new Exercise(new Name("Cycling"), new Date("11/11/2019"), new Calories("50"), new Quantity("5"), new Unit("km"), getMuscleSet("Legs"), new TreeMap<>()), new Exercise(new Name("Strength Training"), new Date("10/11/2019"), new Calories("249"), new Quantity("20"), new Unit("counts"), getMuscleSet("Chest"), new TreeMap<>()), new Exercise(new Name("Swimming"), new Date("09/11/2019"), new Calories("160"), new Quantity("10"), new Unit("laps"), getMuscleSet("Calves"), new TreeMap<>()), new Exercise(new Name("Bench Press"), new Date("08/11/2019"), new Calories("182"), new Quantity("30"), new Unit("counts"), getMuscleSet("Triceps"), new TreeMap<>()), new Exercise(new Name("Running"), new Date("07/11/2019"), new Calories("40"), new Quantity("2.4"), new Unit("km"), getMuscleSet("Legs"), new TreeMap<>()) }; } public static Regime[] getSampleRegimes() { SortedUniqueResourceList<Exercise> list1 = new SortedUniqueResourceList<>(DEFAULT_EXERCISE_COMPARATOR); list1.add(new Exercise(new Name("Rope Skipping"), new Date("17/11/2019"), new Calories("330"), new Quantity("10"), new Unit("counts"), getMuscleSet("Legs"), new TreeMap<>())); list1.add(new Exercise(new Name("Bench Press"), new Date("17/11/2019"), new Calories("222"), new Quantity("30"), new Unit("counts"), getMuscleSet("Triceps"), new TreeMap<>())); SortedUniqueResourceList<Exercise> list2 = new SortedUniqueResourceList<>(DEFAULT_EXERCISE_COMPARATOR); list2.add(new Exercise(new Name("Running"), new Date("20/11/2019"), new Calories("127"), new Quantity("2.4"), new Unit("km"), getMuscleSet("Legs"), new TreeMap<>())); list2.add(new Exercise(new Name("Bench Press"), new Date("20/11/2019"), new Calories("222"), new Quantity("30"), new Unit("counts"), getMuscleSet("Triceps"), new TreeMap<>())); list2.add(new Exercise(new Name("Swimming"), new Date("20/11/2019"), new Calories("354"), new Quantity("10"), new Unit("laps"), getMuscleSet("Calves"), new TreeMap<>())); SortedUniqueResourceList<Exercise> list3 = new SortedUniqueResourceList<>(DEFAULT_EXERCISE_COMPARATOR); list3.add(new Exercise(new Name("Rope Skipping"), new Date("22/11/2019"), new Calories("230"), new Quantity("10"), new Unit("counts"), getMuscleSet("Legs"), new TreeMap<>())); list3.add(new Exercise(new Name("Swimming"), new Date("22/11/2019"), new Calories("254"), new Quantity("10"), new Unit("laps"), getMuscleSet("Calves"), new TreeMap<>())); list3.add(new Exercise(new Name("Bench Press"), new Date("22/11/2019"), new Calories("122"), new Quantity("30"), new Unit("counts"), getMuscleSet("Triceps"), new TreeMap<>())); list3.add(new Exercise(new Name("Cycling"), new Date("22/11/2019"), new Calories("184"), new Quantity("5"), new Unit("km"), getMuscleSet("Legs"), new TreeMap<>())); list3.add(new Exercise(new Name("Strength Training"), new Date("22/11/2019"), new Calories("241"), new Quantity("20"), new Unit("counts"), getMuscleSet("Chest"), new TreeMap<>())); return new Regime[]{ new Regime(new Name("Level 1"), list1), new Regime(new Name("Level 2"), list2), new Regime(new Name("Level 3"), list3) }; } public static Schedule[] getSampleSchedules() { Regime[] sampleRegimes = getSampleRegimes(); return new Schedule[]{ new Schedule(sampleRegimes[0], new Date("17/11/2019")), new Schedule(sampleRegimes[1], new Date("20/11/2019")), new Schedule(sampleRegimes[2], new Date("22/11/2019")) }; } /** * Returns a muscle set containing the list of strings given. */ public static Set<Muscle> getMuscleSet(String... strings) { return Arrays.stream(strings) .map(Muscle::new) .collect(Collectors.toSet()); } public static ReadOnlyResourceBook<Exercise> getSampleExerciseBook() { ReadOnlyResourceBook<Exercise> sampleEb = new ReadOnlyResourceBook<>(DEFAULT_EXERCISE_COMPARATOR); for (Exercise sampleExercise : getSampleExercises()) { sampleEb.addResource(sampleExercise); } return sampleEb; } public static ReadOnlyResourceBook<Schedule> getSampleScheduleBook() { ReadOnlyResourceBook<Schedule> sampleSb = new ReadOnlyResourceBook<>(DEFAULT_SCHEDULE_COMPARATOR); for (Schedule sampleSchedule : getSampleSchedules()) { sampleSb.addResource(sampleSchedule); } return sampleSb; } public static ReadOnlyResourceBook<Regime> getSampleRegimeBook() { ReadOnlyResourceBook<Regime> sampleRb = new ReadOnlyResourceBook<>(DEFAULT_REGIME_COMPARATOR); for (Regime sampleRegime : getSampleRegimes()) { sampleRb.addResource(sampleRegime); } return sampleRb; } }
47.906475
111
0.635531
3b627aa3ce19cef96378900754575813cded9b28
1,002
package org.jerry.transfercash.service; import org.apache.log4j.Logger; import org.jerry.transfercash.exception.CustomException; import org.jerry.transfercash.exception.ErrorResponse; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class ServiceExceptionMapper implements ExceptionMapper<CustomException> { private static Logger log = Logger.getLogger(ServiceExceptionMapper.class); public ServiceExceptionMapper() { } public Response toResponse(CustomException daoException) { if (log.isDebugEnabled()) { log.debug("Mapping exception to Response...."); } ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setErrorCode(daoException.getMessage()); // builder pattern // return internal server error for DAO exceptions return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponse).type(MediaType.APPLICATION_JSON).build(); } }
31.3125
127
0.799401
817a6d683df033c205a37873883f88a26fdad489
2,373
package com.example.demo.controllers; import com.example.demo.conceptHeader.ConceptHeader; import com.example.demo.conceptHeader.OpenTabs; import com.example.demo.user.User; import com.example.demo.user.UserComponent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @Controller public class NavMenuController { @Autowired private OpenTabs openTabs; @Autowired private UserComponent userComponent; @GetMapping("/MainPage/DeleteHeaderConcept/{name}") public void deleteHeaderConcept(Model model,@PathVariable String name) { openTabs.deleteConceptHeader(new ConceptHeader(name)); for (ConceptHeader c : openTabs.getOpenTabs()){ System.out.println(c.getName()); } } @GetMapping("/MainPage/HeaderConcept/{name}") public void addHeaderConcept(Model model,@PathVariable String name) { if (!openTabs.conceptContains(new ConceptHeader(name)) && openTabs.size()<11) { ConceptHeader conceptHeaderV = new ConceptHeader(name); openTabs.addTab(conceptHeaderV); } } @GetMapping("/MainPage/HeaderConcept") public String addHeaderConcept(Model model) { User u = userComponent.getLoggedUser(); if (u == null){ model.addAttribute("login",true); model.addAttribute("urlLog","/logIn"); model.addAttribute("inOut","in"); }else if (u.getRol().equals("ROLE_TEACHER")){ model.addAttribute("student", false); model.addAttribute("teacher", true); model.addAttribute("login", false); model.addAttribute("inOut", "out"); model.addAttribute("urlLog", "/MainPage/logOut"); } else if (u.getRol().equals("ROLE_STUDENT")) { model.addAttribute("student", true); model.addAttribute("teacher", false); model.addAttribute("login",false); model.addAttribute("inOut","out"); model.addAttribute("urlLog","/MainPage/logOut"); } model.addAttribute("conceptHeader",openTabs.getOpenTabs()); model.addAttribute("logIn",true); return "Header"; } }
40.913793
87
0.670881
c3f4779e5f4075f02552a2c162c454a5e86bb40f
563
package com.example.reservationandlivraisonapi.entity.reclamation; import com.example.reservationandlivraisonapi.entity.acteurs.User; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.Date; @Entity @NoArgsConstructor @AllArgsConstructor @Data public class Message { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String content; private Date date; @ManyToOne private Conversation conversation; @ManyToOne private User sender; }
18.766667
66
0.817052
461e503f1dc0d339714d192767ee15b310348921
134
package com.twilio.demo.minotaur; import io.dropwizard.Configuration; public class MinotaurConfiguration extends Configuration { }
16.75
58
0.828358
2f2b03065c5b012d0b1676734c00f178d5bdc81e
3,303
/* */ package org.springframework.context.support; /* */ /* */ import java.util.Locale; /* */ import org.springframework.context.HierarchicalMessageSource; /* */ import org.springframework.context.MessageSource; /* */ import org.springframework.context.MessageSourceResolvable; /* */ import org.springframework.context.NoSuchMessageException; /* */ import org.springframework.lang.Nullable; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class DelegatingMessageSource /* */ extends MessageSourceSupport /* */ implements HierarchicalMessageSource /* */ { /* */ @Nullable /* */ private MessageSource parentMessageSource; /* */ /* */ public void setParentMessageSource(@Nullable MessageSource parent) { /* 46 */ this.parentMessageSource = parent; /* */ } /* */ /* */ /* */ @Nullable /* */ public MessageSource getParentMessageSource() { /* 52 */ return this.parentMessageSource; /* */ } /* */ /* */ /* */ /* */ @Nullable /* */ public String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale) { /* 59 */ if (this.parentMessageSource != null) { /* 60 */ return this.parentMessageSource.getMessage(code, args, defaultMessage, locale); /* */ } /* 62 */ if (defaultMessage != null) { /* 63 */ return renderDefaultMessage(defaultMessage, args, locale); /* */ } /* */ /* 66 */ return null; /* */ } /* */ /* */ /* */ /* */ public String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException { /* 72 */ if (this.parentMessageSource != null) { /* 73 */ return this.parentMessageSource.getMessage(code, args, locale); /* */ } /* */ /* 76 */ throw new NoSuchMessageException(code, locale); /* */ } /* */ /* */ /* */ /* */ public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException { /* 82 */ if (this.parentMessageSource != null) { /* 83 */ return this.parentMessageSource.getMessage(resolvable, locale); /* */ } /* */ /* 86 */ if (resolvable.getDefaultMessage() != null) { /* 87 */ return renderDefaultMessage(resolvable.getDefaultMessage(), resolvable.getArguments(), locale); /* */ } /* 89 */ String[] codes = resolvable.getCodes(); /* 90 */ String code = (codes != null && codes.length > 0) ? codes[0] : ""; /* 91 */ throw new NoSuchMessageException(code, locale); /* */ } /* */ /* */ /* */ /* */ /* */ public String toString() { /* 98 */ return (this.parentMessageSource != null) ? this.parentMessageSource.toString() : "Empty MessageSource"; /* */ } /* */ } /* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/context/support/DelegatingMessageSource.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
31.160377
151
0.540721
9d626ebb7b523602b34cd0d49e5c963a9fc70ce0
627
package com.secbro2.pattern; /** * @author sec * @version 1.0 * @date 2021/6/23 **/ public class Client { public static void main(String[] args) { // 普通配置电脑的组装 ComputerBuilder builder = new CommonComputerBuilder(); Director director = new Director(builder); Computer product = director.construct(); product.show(); System.out.println("------------------"); // 高级配置电脑的组装 builder = new SupperComputerBuilder(); director = new Director(builder); product = director.construct(); product.show(); // 可拓展其他配置的构建中实现 } }
20.9
62
0.577352
a3b40ee485c1c0bc82a34ab6179f6c9fde93928d
1,817
package com.tmall.web; import com.tmall.pojo.Product; import com.tmall.service.CategoryService; import com.tmall.service.ProductService; import com.tmall.service.ProductImageService; import com.tmall.util.Page4Navigator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.Date; @RestController public class ProductController { @Autowired ProductService productService; @Autowired CategoryService categoryService; @Autowired ProductImageService productImageService; @GetMapping("/categories/{cid}/products") public Page4Navigator<Product> list(@PathVariable("cid") int cid, @RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size) throws Exception { start = start<0?0:start; Page4Navigator<Product> page =productService.list(cid, start, size,5 ); productImageService.setFirstProdutImages(page.getContent()); return page; } @GetMapping("/products/{id}") public Product get(@PathVariable("id") int id) throws Exception { Product bean=productService.get(id); return bean; } @PostMapping("/products") public Object add(@RequestBody Product bean) throws Exception { bean.setCreateDate(new Date()); productService.add(bean); return bean; } @DeleteMapping("/products/{id}") public String delete(@PathVariable("id") int id, HttpServletRequest request) throws Exception { productService.delete(id); return null; } @PutMapping("/products") public Object update(@RequestBody Product bean) throws Exception { productService.update(bean); return bean; } }
33.648148
209
0.714364
e1b887638739e96e8855e3bdbd5a5cbafadce7bf
895
package com.jn.langx.test.util.enums; import com.jn.langx.DelegateHolder; import com.jn.langx.util.enums.base.CommonEnum; import com.jn.langx.util.enums.base.EnumDelegate; public enum Period implements DelegateHolder<EnumDelegate>, CommonEnum { MINUTES(0, "minutes", "minutes"), HOURS(1, "hours", "hours"), DAY(2, "day", "day"), MONTH(3, "month", "month"); public static final long serialVersionUID = 1L; private EnumDelegate delegate; Period(int code, String name, String displayText) { this.delegate = new EnumDelegate(code, name, displayText); } public int getCode() { return delegate.getCode(); } public String getName() { return delegate.getName(); } public String getDisplayText() { return delegate.getDisplayText(); } public EnumDelegate getDelegate() { return delegate; } }
24.189189
72
0.661453
25bde18901256528b43cc99c7cb58692ebbd8f19
6,180
package com.google.javascript.clutz; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.ImmutableList; import com.google.common.io.Files; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; /** * Representation of the data contained in a depgraph file. * * <p>This JSON file is produced by Bazel javascript rules, and describes the shape of the * dependency graph for a given rule. We use it to determine which inputs to the compiler are srcs * and which come from deps. */ class Depgraph { private final Set<String> roots = new LinkedHashSet<>(); private final Set<String> nonroots = new LinkedHashSet<>(); private final Set<String> rootExterns = new LinkedHashSet<>(); private final Set<String> nonrootExterns = new LinkedHashSet<>(); /** * Closure's internal name for goog.provide and goog.module symbols is incompatible, and in a * goog.module file, it's impossible to tell which is being referenced, so information is pulled * out of the depgraph, and later passed to ImportBasedMapBuilder to resolve the ambiguity. */ private final Set<String> googProvides = new HashSet<>(); private Depgraph() {} boolean isRoot(String fileName) { // roots can only be empty if no Depgraphs were passed in, in which case we accept all files. return roots.isEmpty() || roots.contains(fileName); } Depgraph withNonrootsAsRoots() { Depgraph res = new Depgraph(); res.roots.addAll(roots); res.roots.addAll(nonroots); res.rootExterns.addAll(rootExterns); res.rootExterns.addAll(nonrootExterns); return res; } Set<String> getRoots() { return Collections.unmodifiableSet(roots); } Set<String> getNonroots() { return Collections.unmodifiableSet(nonroots); } Set<String> getRootExterns() { return Collections.unmodifiableSet(rootExterns); } Set<String> getNonrootExterns() { return Collections.unmodifiableSet(nonrootExterns); } Set<String> getGoogProvides() { return Collections.unmodifiableSet(googProvides); } static Depgraph forRoots(Set<String> roots, Set<String> nonroots) { Depgraph result = new Depgraph(); result.roots.addAll(roots); result.nonroots.addAll(nonroots); return result; } // TODO(alexeagle): consider parsing into an object graph rather than nested loops over List<?>. static Depgraph parseFrom(List<String> fileNames) { Depgraph result = new Depgraph(); if (fileNames.isEmpty()) { return result; } for (String depgraphName : fileNames) { try { String depgraph = Files.asCharSource(new File(depgraphName), UTF_8).read(); List<List<?>> list = new Gson() .fromJson( depgraph, new TypeToken<List<List<?>>>() { /* empty */ }.getType()); for (List<?> outer : list) { String key = (String) outer.get(0); @SuppressWarnings("unchecked") List<List<?>> value = (List<List<?>>) outer.get(1); result.collectFiles("roots".equals(key), value); } } catch (FileNotFoundException e) { throw new IllegalArgumentException("depgraph file not found: " + depgraphName, e); } catch (IOException e) { throw new RuntimeException("error reading depgraph file " + depgraphName, e); } catch (Exception e) { throw new RuntimeException("malformed depgraph: " + depgraphName, e); } } if (result.roots.isEmpty() && result.rootExterns.isEmpty()) { throw new IllegalStateException("No roots were found in the provided depgraphs files"); } return result; } // Strip brackets from bazel's "[blaze-out/.../]foo/bar" path prefixes. private static final Pattern GENERATED_FILE = Pattern.compile("^\\[([^]]+)\\]"); private void collectFiles(boolean isRoots, List<List<?>> fileList) { for (List<?> rootDescriptor : fileList) { String fileName = (String) rootDescriptor.get(0); // *-bootstrap.js are automatically added to every rule by Bazel if (fileName.endsWith("-bootstrap.js")) { continue; } @SuppressWarnings("unchecked") List<List<?>> fileProperties = (List<List<?>>) rootDescriptor.get(1); boolean isExterns = false; boolean isGoogProvide = true; List<String> provides = new ArrayList<>(); for (List<?> tuple : fileProperties) { String key = (String) tuple.get(0); if ("is_externs".equals(key) && Boolean.TRUE.equals(tuple.get(1))) { isExterns = true; break; } if ("load_flags".equals(key)) { // load flags is a list of lists of strings ie [["lang","es6"],["module","goog"]] @SuppressWarnings("unchecked") List<List<String>> loadFlags = (List<List<String>>) tuple.get(1); if (loadFlags.contains(ImmutableList.of("module", "goog"))) { isGoogProvide = false; } } if ("provides".equals(key)) { // provides is a list of strings, where the first element is the file name with a prefix // and all the remaining elements are the provides from that file @SuppressWarnings("unchecked") List<String> provideList = (List<String>) tuple.get(1); if (provideList.size() > 1) { provides.addAll(provideList.subList(1, provideList.size())); } } } fileName = GENERATED_FILE.matcher(fileName).replaceAll("$1"); if (isExterns && isRoots) { rootExterns.add(fileName); } else if (isExterns && !isRoots) { nonrootExterns.add(fileName); } else if (isRoots) { roots.add(fileName); } else { nonroots.add(fileName); } if (isGoogProvide) { googProvides.addAll(provides); } } } }
35.113636
98
0.646278
63dcbb46754497251692b843988b1eb1e87ec5d7
824
package me.itzg.helpers.get; import java.io.IOException; import lombok.extern.slf4j.Slf4j; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.io.HttpClientResponseHandler; import org.apache.hc.core5.http.io.entity.EntityUtils; @Slf4j class DeriveFilenameHandler implements HttpClientResponseHandler<String> { final FilenameExtractor filenameExtractor; public DeriveFilenameHandler(LatchingUrisInterceptor interceptor) { filenameExtractor = new FilenameExtractor(interceptor); } @Override public String handleResponse(ClassicHttpResponse response) throws HttpException, IOException { final String filename = filenameExtractor.extract(response); EntityUtils.consume(response.getEntity()); return filename; } }
29.428571
96
0.809466
62e23745128b7ca6c40543bf1a9a8a9133301223
398
package e; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support .ClassPathXmlApplicationContext; public class Client { public static void main(String[] args) { try (ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml")) { } } }
28.428571
73
0.665829
c589202e4ca56568f14c653d64c4eec0ee69ca84
4,559
package pohkahkong.game.rainbow.bean.animation; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; /** * * @author Poh Kah Kong * */ public class PropertySpriteAnimation extends SpriteAnimation { protected static enum State {FALSE, RESTARTING, CONTINUOUS}; protected Matrix matrix = new Matrix(); protected Paint paint = new Paint(); // rotating protected boolean rotating = false; protected float degrees = 0.0f; // fading protected boolean fading = false; protected int alpha = 255; protected float alphaDelta = -2.0f; // translating protected State translatingX = State.FALSE; protected State translatingY = State.FALSE; protected float translateDistX; protected float translateDistY; protected float translateX = 0; protected float translateY = 0; protected float translateDeltaX = 1.0f; protected float translateDeltaY = 1.0f; public PropertySpriteAnimation(Bitmap bitmap, int left, int top, int width, int height, int frames, float fps) { super(bitmap, left, top, width, height, frames, fps); } public PropertySpriteAnimation(Bitmap bitmap, int left, int top, int width, int height, float fps) { super(bitmap, left, top, width, height, fps); } @Override public boolean update(long newTime) { updateProperty(newTime); return updateSprite(newTime); } protected boolean updateSprite(long newTime) { return super.update(newTime); } protected boolean updateProperty(long newTime) { if (newTime<time+1.0/fps*50) { return false; } if (rotating || translatingX!=State.FALSE || translatingY!=State.FALSE) { matrix.reset(); rotate(); translate(); } if (fading) { paint.reset(); fading(); } return true; } private void rotate() { if (!rotating) { return; } degrees++; if (degrees>360.0f) { degrees = 0.0f; } matrix.postRotate(degrees, width/2, height/2); } private void translate() { if (translatingX == State.FALSE && translatingY == State.FALSE) { return; } if (translatingX!=State.FALSE) { translateX+=translateDeltaX; if (Math.abs(translateX)<0 || Math.abs(translateX)>translateDistX) { if (translatingX==State.RESTARTING) { translateX = 0.0f; } else { translateDeltaX = -translateDeltaX; } } } if (translatingY!=State.FALSE) { translateY+=translateDeltaY; if (Math.abs(translateY)<0 || Math.abs(translateY)>translateDistY) { if (translatingY==State.RESTARTING) { translateY = 0.0f; } else { translateDeltaY = -translateDeltaY; } } } matrix.postTranslate(translateX, translateY); } private void fading() { if (!fading) { return; } alpha+=alphaDelta; if (alpha<=100 || alpha>=255) { alphaDelta = -alphaDelta; alpha+=alphaDelta; } paint.setAlpha(alpha); } @Override public void draw(Canvas canvas, float x, float y) { canvas.save(); Rect src = new Rect(left+width*frame, top, left+width*(frame+1), top+height); Rect dst = new Rect(0, 0, width, height); canvas.translate(x,y); canvas.concat(matrix); canvas.drawBitmap(bitmap, src, dst, paint); canvas.restore(); } // getters and setters public void setTranslucent(boolean translucent) { if (translucent) { paint.setAlpha(100); fading = false; } else { paint.setAlpha(255); } } public void setRotating(boolean rotating) { this.rotating = rotating; } public void setTranslateX(boolean translating, float translateDistX, boolean up, boolean restarting) { if (!translating) { translatingX = State.FALSE; return; } this.translateDistX = translateDistX; translateDeltaX = up? -translateDeltaX:translateDeltaX; translatingX = restarting? State.RESTARTING:State.CONTINUOUS; } public void setTranslateY(boolean translating, float translateDistY, boolean left, boolean restarting) { if (!translating) { translatingY = State.FALSE; return; } this.translateDistY = translateDistY; translateDeltaY = left? -translateDeltaY:translateDeltaY; translatingY = restarting? State.RESTARTING:State.CONTINUOUS; } public void setFading(boolean fading) { this.fading = fading; } public PropertySpriteAnimation clone() { return new PropertySpriteAnimation(bitmap, left, top, width, height, frames, fps); } }
25.187845
108
0.670322
ec22876a10291d74eafa43b22525af238eae34bc
3,571
package p320f.p321a.p327d.p336f; import io.reactivex.internal.queue.MpscLinkedQueue.LinkedQueueNode; import java.util.concurrent.atomic.AtomicReference; import p320f.p321a.p327d.p330c.C13273h; /* renamed from: f.a.d.f.a */ /* compiled from: MpscLinkedQueue */ public final class C13703a<T> implements C13273h<T> { /* renamed from: a */ private final AtomicReference<C13704a<T>> f41738a = new AtomicReference<>(); /* renamed from: b */ private final AtomicReference<C13704a<T>> f41739b = new AtomicReference<>(); /* renamed from: f.a.d.f.a$a */ /* compiled from: MpscLinkedQueue */ static final class C13704a<E> extends AtomicReference<C13704a<E>> { /* renamed from: a */ private E f41740a; C13704a() { } C13704a(E val) { mo42679a(val); } /* renamed from: a */ public E mo42677a() { E temp = mo42680b(); mo42679a((E) null); return temp; } /* renamed from: b */ public E mo42680b() { return this.f41740a; } /* renamed from: a */ public void mo42679a(E newValue) { this.f41740a = newValue; } /* renamed from: a */ public void mo42678a(C13704a<E> n) { lazySet(n); } /* renamed from: c */ public C13704a<E> mo42681c() { return (C13704a) get(); } } public C13703a() { LinkedQueueNode<T> node = new C13704a<>(); mo42673a(node); mo42675b(node); } public boolean offer(T e) { if (e != null) { LinkedQueueNode<T> nextNode = new C13704a<>(e); mo42675b(nextNode).mo42678a((C13704a<E>) nextNode); return true; } throw new NullPointerException("Null is not a valid element"); } public T poll() { C13704a c; C13704a aVar; T currConsumerNode = mo42672a(); LinkedQueueNode<T> nextNode = currConsumerNode.mo42681c(); if (nextNode != null) { T nextValue = nextNode.mo42677a(); mo42673a(nextNode); return nextValue; } else if (currConsumerNode == mo42676c()) { return null; } else { do { c = currConsumerNode.mo42681c(); aVar = c; } while (c == null); T nextValue2 = aVar.mo42677a(); mo42673a(aVar); return nextValue2; } } public void clear() { while (poll() != null) { if (isEmpty()) { return; } } } /* access modifiers changed from: 0000 */ /* renamed from: c */ public C13704a<T> mo42676c() { return (C13704a) this.f41738a.get(); } /* access modifiers changed from: 0000 */ /* renamed from: b */ public C13704a<T> mo42675b(C13704a<T> node) { return (C13704a) this.f41738a.getAndSet(node); } /* access modifiers changed from: 0000 */ /* renamed from: b */ public C13704a<T> mo42674b() { return (C13704a) this.f41739b.get(); } /* access modifiers changed from: 0000 */ /* renamed from: a */ public C13704a<T> mo42672a() { return (C13704a) this.f41739b.get(); } /* access modifiers changed from: 0000 */ /* renamed from: a */ public void mo42673a(C13704a<T> node) { this.f41739b.lazySet(node); } public boolean isEmpty() { return mo42674b() == mo42676c(); } }
25.876812
80
0.536264
58fcb1dd4b91228337820875342006398550f0ae
396
package com.oldlie.exam.repository; import java.util.List; import com.oldlie.exam.entity.Student; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository<Student, Long> { List<Student> findAllByExamNumber(String examNumber); Student findOneByNameAndNumberAndExamNumber(String name, String number, String examNumber); }
26.4
95
0.815657
1e85463520c3b0d5c7236dc8c70364e1e7fc014e
1,050
package com.example.lithography.service; import com.example.lithography.adapter.PinglunBean; import com.example.lithography.bean.Dabean; import com.example.lithography.bean.ReDianBean; import com.example.lithography.bean.TanBean; import com.example.lithography.bean.XiangqingBean; import java.util.Map; import io.reactivex.Flowable; import retrofit2.http.GET; import retrofit2.http.QueryMap; /** * Created by 柴晓凯 on 2018/1/2. */ public interface ApiService { //首页 @GET("homePageApi/homePage.do") Flowable<Dabean> getNews(@QueryMap Map<String, String> map); //探探 @GET("columns/getVideoList.do") Flowable<TanBean> getTan(@QueryMap Map<String, String> map); //详情 @GET("videoDetailApi/videoDetail.do") Flowable<XiangqingBean> getXiangq(@QueryMap Map<String, String> map); //评论 @GET("Commentary/getCommentList.do") Flowable<PinglunBean> getPingl(@QueryMap Map<String, String> map); //热点 @GET("columns/getNewsList.do") Flowable<ReDianBean> getRe(@QueryMap Map<String, String> map); }
25.609756
73
0.731429
7f0e3f1fbebfe4909e8d1b79a27fe174107c3588
465
package com.effective; public enum EnumTest { /* MON, TUE, WED, THU, FRI, SAT, SUN;*/ MON(1), TUE(2), WED(3), THU(4), FRI(5), SAT(6), SUN(7); private int value; private EnumTest(int value){ this.value = value; } public int getValue() { return value; } public static void main(String[] args) { /*for(EnumTest e : EnumTest.values()){ System.out.println(e.name()+"---"+e.ordinal()); }*/ System.out.println(EnumTest.FRI.getValue()); } }
17.884615
56
0.615054
14d410146dbc7018c22c4625fece4b1653da80e0
1,331
/* * Copyright 2016-2020 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.propagation; import io.opentracing.Tracer; import java.util.Iterator; import java.util.Map; /** * A TextMap carrier for use with Tracer.extract() ONLY (it has no mutating methods). * * Note that the TextMap interface can be made to wrap around arbitrary data types (not just Map&lt;String, String&gt; * as illustrated here). * * @see Tracer#extract(Format, Object) */ public class TextMapExtractAdapter implements TextMapExtract { protected final Map<String,String> map; public TextMapExtractAdapter(final Map<String,String> map) { this.map = map; } @Override public Iterator<Map.Entry<String, String>> iterator() { return map.entrySet().iterator(); } }
32.463415
118
0.731029
2dcd3946249ed0227335e195257d1b855b1849ae
1,177
package com.td.common.bean; public class Body { private final static String SUCCESS_CODE = "200"; private final static String ERROR_CODE = "300"; private final static String CLOSE_CURRENT = "closeCurrent"; private String statusCode; private String message; public String getStatusCode() { return statusCode; } public Body setStatusCode(String statusCode) { this.statusCode = statusCode; return this; } public String getMessage() { return message; } public Body setMessage(String message) { this.message = message; return this; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append(statusCode == null ? "" : "\"statusCode\" : \"" + statusCode + "\","); sb.append(message == null ? "" : "\"message\" : \"" + message + "\","); sb = sb.toString().equals("{") ? sb.append("}") : sb.replace(sb.length() - 1, sb.length(), "}"); return sb.toString(); } /** * 设置statusCode值200 * * @return */ public Body success() { return setStatusCode(SUCCESS_CODE); } /** * 设置statusCode值300 * * @return */ public Body error() { return setStatusCode(ERROR_CODE); } }
19.295082
92
0.64486
57b92ddf357607791d8dc8fd3c29b02f054fe7c1
1,194
package sqlancer.postgres.ast; import sqlancer.Randomly; import sqlancer.postgres.PostgresSchema.PostgresDataType; public class PostgresJoin implements PostgresExpression { public enum PostgresJoinType { INNER, LEFT, RIGHT, FULL, CROSS; public static PostgresJoinType getRandom() { return Randomly.fromOptions(values()); } } private final PostgresExpression tableReference; private final PostgresExpression onClause; private final PostgresJoinType type; public PostgresJoin(PostgresExpression tableReference, PostgresExpression onClause, PostgresJoinType type) { this.tableReference = tableReference; this.onClause = onClause; this.type = type; } public PostgresExpression getTableReference() { return tableReference; } public PostgresExpression getOnClause() { return onClause; } public PostgresJoinType getType() { return type; } @Override public PostgresDataType getExpressionType() { throw new AssertionError(); } @Override public PostgresConstant getExpectedValue() { throw new AssertionError(); } }
23.88
112
0.693467
9e3449388bb39ddbfbca0faac4e86ffb3f0a6153
3,067
/** * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.runtime.classhandling; import com.examples.with.different.packagename.classhandling.MutableEnum; import org.evosuite.runtime.RuntimeSettings; import org.evosuite.runtime.instrumentation.EvoClassLoader; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.lang.reflect.Method; public class ClassResetterTest { @Test public void testResetOfEnum() throws Exception{ ClassLoader loader = new EvoClassLoader(); RuntimeSettings.resetStaticState = true; ClassResetter.getInstance().setClassLoader(loader); String cut = "com.examples.with.different.packagename.classhandling.FooEnum"; Class<?> klass = loader.loadClass(cut); Method m = klass.getDeclaredMethod("check"); boolean val = false; val = (Boolean) m.invoke(null); Assert.assertTrue(val); ClassResetter.getInstance().reset(cut); //make sure that the reset does not create new enum instance values val = (Boolean) m.invoke(null); Assert.assertTrue(val); } // TODO: We could consider providing a workaround to reset mutable enums. @Ignore @Test public void testResetOfMutableEnum() throws Exception{ ClassLoader loader = new EvoClassLoader(); RuntimeSettings.resetStaticState = true; ClassResetter.getInstance().setClassLoader(loader); String cut = MutableEnum.class.getCanonicalName(); Class<?> klass = (Class<MutableEnum>) loader.loadClass(cut); Object[] enums = klass.getEnumConstants(); Assert.assertEquals(2, enums.length); Method getter = klass.getDeclaredMethod("getLetter"); Assert.assertEquals("a", getter.invoke(enums[0])); Assert.assertEquals("b", getter.invoke(enums[1])); Method m = klass.getDeclaredMethod("changeLetter"); m.invoke(enums[0]); Assert.assertEquals("X", getter.invoke(enums[0])); Assert.assertEquals("b", getter.invoke(enums[1])); ClassResetter.getInstance().reset(cut); Assert.assertEquals("a", getter.invoke(enums[0])); Assert.assertEquals("b", getter.invoke(enums[1])); } }
34.460674
86
0.676883
2691e0d502e00c4982c06b615ef6abd2cb48e1ce
3,339
package com.thegongoliers.output.drivetrain.swerve; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveDriveKinematics; import edu.wpi.first.math.kinematics.SwerveDriveOdometry; import edu.wpi.first.wpilibj.interfaces.Gyro; public class SwerveDrivetrain { private final SwerveWheel mFrontLeft; private final SwerveWheel mFrontRight; private final SwerveWheel mBackLeft; private final SwerveWheel mBackRight; private final Gyro mGyro; private double maxDegreesPerSecond = 180; private double maxWheelSpeed = 1; private final SwerveDriveKinematics mKinematics; private final SwerveDriveOdometry mOdometry; public SwerveDrivetrain(SwerveWheel frontLeft, SwerveWheel frontRight, SwerveWheel backLeft, SwerveWheel backRight, Gyro gyro) { mFrontLeft = frontLeft; mFrontRight = frontRight; mBackLeft = backLeft; mBackRight = backRight; mGyro = gyro; mKinematics = new SwerveDriveKinematics(frontLeft.getLocation(), frontRight.getLocation(), backLeft.getLocation(), backRight.getLocation()); mOdometry = new SwerveDriveOdometry(mKinematics, mGyro.getRotation2d()); } public void setMaxDegreesPerSecond(double maxDegreesPerSecond) { this.maxDegreesPerSecond = maxDegreesPerSecond; } public void setMaxWheelSpeed(double maxWheelSpeed) { this.maxWheelSpeed = maxWheelSpeed; } /** * Drive with given speeds (percentages) * * @param x The x speed [-1, 1] * @param y The y speed [-1, 1] * @param rotation The rotation speed [-1, 1] */ public void drive(double x, double y, double rotation) { // TODO: Add modules which take in and output a ChassisSpeeds object (field relative, velocity control, voltage control, ramp, path follower, target alignment) var speed = new ChassisSpeeds(x, y, rotation * maxDegreesPerSecond); var states = mKinematics.toSwerveModuleStates(speed); SwerveDriveKinematics.desaturateWheelSpeeds(states, maxWheelSpeed); mFrontLeft.set(states[0].speedMetersPerSecond, states[0].angle.getDegrees()); mFrontRight.set(states[1].speedMetersPerSecond, states[1].angle.getDegrees()); mBackLeft.set(states[2].speedMetersPerSecond, states[2].angle.getDegrees()); mBackRight.set(states[3].speedMetersPerSecond, states[3].angle.getDegrees()); } public double getX() { return mOdometry.getPoseMeters().getX(); } public double getY() { return mOdometry.getPoseMeters().getY(); } public double getRotation() { return mGyro.getAngle(); } public void resetPosition() { mOdometry.resetPosition(new Pose2d(0, 0, Rotation2d.fromDegrees(0)), mGyro.getRotation2d()); } public void resetWheels() { mFrontLeft.reset(); mFrontRight.reset(); mBackLeft.reset(); mBackRight.reset(); } public void updatePosition() { mOdometry.update( mGyro.getRotation2d(), mFrontLeft.getState(), mFrontRight.getState(), mBackLeft.getState(), mBackRight.getState()); } }
35.521277
167
0.685834
c03cc654f31db8da1df4a3a9ed8d51ef3dc4c92e
17,408
package com.armadialogcreator.gui.main.stringtable; import com.armadialogcreator.ArmaDialogCreator; import com.armadialogcreator.HelpUrls; import com.armadialogcreator.core.stringtable.*; import com.armadialogcreator.gui.GenericResponseFooter; import com.armadialogcreator.gui.SimpleResponseDialog; import com.armadialogcreator.gui.StagePopup; import com.armadialogcreator.gui.fxcontrol.SearchTextField; import com.armadialogcreator.gui.main.BrowserUtil; import com.armadialogcreator.img.icons.ADCIcons; import com.armadialogcreator.lang.Lang; import com.armadialogcreator.util.KeyValue; import com.armadialogcreator.util.ListObserverListener; import com.armadialogcreator.util.ValueListener; import com.armadialogcreator.util.ValueObserver; import javafx.beans.property.BooleanProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.*; import javafx.scene.image.ImageView; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.util.Callback; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.*; import java.util.function.Consumer; /** @author Kayler @since 12/14/2016 */ public class StringTableEditorPopup extends StagePopup<VBox> { private final StringTableEditorTabPane tabPane; /** String to be used for when {@link StringTableKeyPath#noPackageName()} is true */ private final String noPackageName, /** String to be used for when {@link StringTableKeyPath#noContainer()} is true */ noContainerName; private StringTable table; private final LinkedList<ListObserverListener<StringTableKey>> listenersToRemoveFromTable = new LinkedList<>(); private final ResourceBundle bundle = Lang.getBundle("StringTableBundle"); public StringTableEditorPopup(@NotNull StringTable table, @NotNull StringTableWriter writer, @NotNull StringTableParser parser) { super(ArmaDialogCreator.getPrimaryStage(), new VBox(0), null); setTitle(bundle.getString("StringTableEditorPopup.popup_title")); this.table = table; noPackageName = bundle.getString("StringTable.no_package"); noContainerName = bundle.getString("StringTable.no_container"); Button btnInsert = new Button("", new ImageView(ADCIcons.ICON_PLUS)); btnInsert.setTooltip(new Tooltip(bundle.getString("StringTableEditorPopup.Tab.Edit.insert_key_tooltip"))); btnInsert.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { NewStringTableKeyDialog dialog = new NewStringTableKeyDialog(getTable()); dialog.show(); if (dialog.wasCancelled()) { return; } EditTab editTab = tabPane.getEditTab(); StringTableKeyDescriptor newKey = editTab.addNewKey(dialog.getKey()); getTable().getKeys().add(dialog.getKey()); editTab.getListView().getSelectionModel().select(newKey); editTab.getListView().scrollTo(newKey); } }); Button btnRemove = new Button("", new ImageView(ADCIcons.ICON_MINUS)); btnRemove.setTooltip(new Tooltip(bundle.getString("StringTableEditorPopup.Tab.Edit.remove_key_tooltip"))); btnRemove.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { ListView<StringTableKeyDescriptor> listView = tabPane.getEditTab().getListView(); StringTableKeyDescriptor selected = listView.getSelectionModel().getSelectedItem(); if (selected == null) { return; } SimpleResponseDialog dialog = new SimpleResponseDialog( ArmaDialogCreator.getPrimaryStage(), btnRemove.getTooltip().getText(), String.format(bundle.getString("StringTableEditorPopup.Tab.Edit.remove_key_popup_body_f"), selected.getKey().getId()), true, true, false ); dialog.show(); if (dialog.wasCancelled()) { return; } tabPane.getEditTab().removeKey(selected); } }); tabPane = new StringTableEditorTabPane(this, table, btnRemove.disableProperty(), this); btnRemove.setDisable(tabPane.getEditTab().getListView().getSelectionModel().isEmpty()); Button btnRefresh = new Button("", new ImageView(ADCIcons.ICON_REFRESH)); btnRefresh.setTooltip(new Tooltip(bundle.getString("StringTableEditorPopup.ToolBar.reload_tooltip"))); btnRefresh.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { SimpleResponseDialog dialog = new SimpleResponseDialog( ArmaDialogCreator.getPrimaryStage(), bundle.getString("StringTableEditorPopup.ToolBar.reload_popup_title"), bundle.getString("StringTableEditorPopup.ToolBar.reload_popup_body"), true, true, false ); dialog.show(); if (dialog.wasCancelled()) { return; } try { getTable().setTo(parser.createStringTableInstance()); tabPane.setToTable(getTable()); } catch (IOException e) { new SimpleResponseDialog( ArmaDialogCreator.getPrimaryStage(), bundle.getString("Error.couldnt_refresh_short"), bundle.getString("Error.couldnt_refresh") + "\n" + e.getMessage(), false, true, false ).show(); } } }); Button btnSave = new Button("", new ImageView(ADCIcons.ICON_SAVE)); btnSave.setTooltip(new Tooltip(bundle.getString("StringTableEditorPopup.ToolBar.save_tooltip"))); btnSave.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { SimpleResponseDialog dialog = new SimpleResponseDialog( myStage, bundle.getString("SaveDialog.dialog_title"), bundle.getString("SaveDialog.body"), true, true, false ); dialog.setStageSize(420, 150); dialog.setResizable(false); dialog.show(); if (dialog.wasCancelled()) { return; } try { writer.writeTable(getTable()); } catch (IOException e) { new SimpleResponseDialog( ArmaDialogCreator.getPrimaryStage(), bundle.getString("Error.couldnt_save_short"), bundle.getString("Error.couldnt_save") + "\n" + e.getMessage(), false, true, false ).show(); } } }); btnRemove.disabledProperty(); myRootElement.getChildren().add(new ToolBar(btnRefresh, btnSave, new Separator(Orientation.VERTICAL), btnInsert, btnRemove)); myRootElement.getChildren().add(tabPane); GenericResponseFooter responseFooter = getBoundResponseFooter(false, true, true); VBox.setMargin(responseFooter, new Insets(10)); myRootElement.getChildren().addAll(new Separator(Orientation.HORIZONTAL), responseFooter); VBox.setVgrow(tabPane, Priority.ALWAYS); setStageSize(720, 480); } @Override protected void help() { BrowserUtil.browse(HelpUrls.STRING_TABLE_EDITOR); } /** Get the table that is being edited */ @NotNull public StringTable getTable() { return table; } @Override protected void closing() { clearListeners(); super.closing(); } private void clearListeners() { for (ListObserverListener<StringTableKey> listener : listenersToRemoveFromTable) { table.getKeys().removeListener(listener); } listenersToRemoveFromTable.clear(); } private class StringTableEditorTabPane extends TabPane { private final ValueObserver<Language> previewLanguageObserver = new ValueObserver<>(KnownLanguage.Original); private final StringTableEditorPopup popup; private final BooleanProperty disableRemove; private final StringTableEditorPopup editorPopup; private EditTab editTab; public StringTableEditorTabPane(@NotNull StringTableEditorPopup popup, @NotNull StringTable table, @NotNull BooleanProperty disableRemove, @NotNull StringTableEditorPopup editorPopup) { this.popup = popup; this.disableRemove = disableRemove; this.editorPopup = editorPopup; setToTable(table); } public void setToTable(@NotNull StringTable table) { getTabs().clear(); popup.clearListeners(); editTab = new EditTab(table, previewLanguageObserver, editorPopup); editTab.getListView().getSelectionModel().selectedItemProperty().addListener(new ChangeListener<StringTableKeyDescriptor>() { @Override public void changed(ObservableValue<? extends StringTableKeyDescriptor> observable, StringTableKeyDescriptor oldValue, StringTableKeyDescriptor selected) { disableRemove.setValue(selected == null); } }); getTabs().add(editTab); getTabs().add(new ConfigTab(popup, table, previewLanguageObserver)); getTabs().add(new GraphsTab(popup, table)); } @NotNull public EditTab getEditTab() { return editTab; } } private class ConfigTab extends Tab { //set xml things like project name attribute (project=root tag of stringtable.xml) public ConfigTab(@NotNull StringTableEditorPopup popup, @NotNull StringTable table, @NotNull ValueObserver<Language> previewLanguageObserver) { super(bundle.getString("StringTableEditorPopup.Tab.Config.tab_title")); VBox root = new VBox(10); root.setPadding(new Insets(10)); root.setFillWidth(true); setContent(root); setGraphic(new ImageView(ADCIcons.ICON_GEAR)); setClosable(false); ComboBox<Language> comboBoxLanguage = new ComboBox<>(); comboBoxLanguage.getItems().addAll(KnownLanguage.values()); comboBoxLanguage.getSelectionModel().select(previewLanguageObserver.getValue()); comboBoxLanguage.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Language>() { @Override public void changed(ObservableValue<? extends Language> observable, Language oldValue, Language newValue) { previewLanguageObserver.updateValue(newValue); } }); Label lblPreviewLanguage = new Label(bundle.getString("StringTableEditorPopup.Tab.Config.preview_language"), comboBoxLanguage); lblPreviewLanguage.setContentDisplay(ContentDisplay.RIGHT); root.getChildren().add(lblPreviewLanguage); Label lblSize = new Label(String.format(bundle.getString("StringTableEditorPopup.Tab.Config.number_of_keys_f"), table.getKeys().size())); root.getChildren().add(lblSize); Consumer<Object> keyListener = o -> { lblSize.setText(String.format(bundle.getString("StringTableEditorPopup.Tab.Config.number_of_keys_f"), table.getKeys().size())); }; popup.listenersToRemoveFromTable.add((list, c) -> { keyListener.accept(null); }); table.getKeys().addListener((list, change) -> { keyListener.accept(null); }); } } private class EditTab extends Tab { private final Comparator<StringTableKeyDescriptor> comparator = new Comparator<>() { @Override public int compare(StringTableKeyDescriptor o1, StringTableKeyDescriptor o2) { return o1.getKey().getId().compareToIgnoreCase(o2.getKey().getId()); } }; private final ObservableList<StringTableKeyDescriptor> listViewItemList; private ValueObserver<Language> previewLanguageObserver; private StringTableEditorPopup editorPopup; private final List<StringTableKeyDescriptor> allItems = new LinkedList<>(); private final ListView<StringTableKeyDescriptor> lvMatch = new ListView<>(); private final StringTableKeyEditorPane editorPane; public EditTab(@NotNull StringTable table, @NotNull ValueObserver<Language> previewLanguageObserver, @NotNull StringTableEditorPopup editorPopup) { super(bundle.getString("StringTableEditorPopup.Tab.Edit.tab_title")); listViewItemList = FXCollections.observableList(new ArrayList<>(), new Callback<>() { public javafx.beans.Observable[] call(StringTableKeyDescriptor param) { return new javafx.beans.Observable[]{ param.getKey().getLanguageTokenMap(), param.getKey().getIdObserver(), previewLanguageObserver, param.getKey().getPath() }; } }); //for some reason, can't have a LinkedList as the underlying list implementation if we want the list view to update the displayed cell text automatically this.previewLanguageObserver = previewLanguageObserver; this.editorPopup = editorPopup; previewLanguageObserver.addListener(new ValueListener<>() { @Override public void valueUpdated(@NotNull ValueObserver<Language> observer, @Nullable Language oldValue, @Nullable Language newValue) { for (StringTableKeyDescriptor descriptor : allItems) { descriptor.setPreviewLanguage(newValue); } } }); editorPane = new StringTableKeyEditorPane(table, KnownLanguage.Original); lvMatch.setPlaceholder(new Label(bundle.getString("StringTableEditorPopup.Tab.Edit.Search.no_match"))); lvMatch.setStyle("-fx-font-family:monospace"); for (StringTableKey key : table.getKeys()) { addNewKey(key); } lvMatch.setItems(listViewItemList); lvMatch.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<>() { @Override public void changed(ObservableValue<? extends StringTableKeyDescriptor> observable, StringTableKeyDescriptor oldValue, StringTableKeyDescriptor selected) { if (selected != null) { editorPane.setKey(selected.getKey(), table.getKeys()); } else { editorPane.setKey(null, table.getKeys()); } } }); SearchTextField tfSearch = new StringTableSearchField(lvMatch, allItems); VBox vbRoot = new VBox(10, tfSearch, editorPane, lvMatch); VBox.setVgrow(lvMatch, Priority.ALWAYS); vbRoot.setFillWidth(true); vbRoot.setPadding(new Insets(10)); setContent(vbRoot); setClosable(false); } @NotNull public ListView<StringTableKeyDescriptor> getListView() { return lvMatch; } /** Use this instead of adding to {@link ListView#getItems()} with {@link #getListView()} @return the key that was added */ public StringTableKeyDescriptor addNewKey(@NotNull StringTableKey key) { StringTableKeyDescriptor descriptor = new StringTableKeyDescriptor(key, editorPopup.noPackageName, editorPopup.noContainerName); descriptor.setPreviewLanguage(previewLanguageObserver.getValue()); allItems.add(descriptor); listViewItemList.add(descriptor); listViewItemList.sort(comparator); allItems.sort(comparator); return descriptor; } /** Use this instead of removing from {@link ListView#getItems()} with {@link #getListView()} */ public void removeKey(@NotNull StringTableKey key) { StringTableKeyDescriptor match = null; for (StringTableKeyDescriptor descriptor : allItems) { if (descriptor.getKey().equals(key)) { match = descriptor; break; } } if (match == null) { return; } removeKey(match); } public void removeKey(@NotNull StringTableKeyDescriptor key) { allItems.remove(key); listViewItemList.remove(key); } } private class GraphsTab extends Tab { private final StringTable table; private final CategoryAxis xAxis = new CategoryAxis(); private final NumberAxis yAxis = new NumberAxis(0, 0, 0); private final BarChart<String, Number> chart = new BarChart<>(xAxis, yAxis); private final XYChart.Series<String, Number> series = new XYChart.Series<>(); public GraphsTab(@NotNull StringTableEditorPopup popup, @NotNull StringTable table) { this.table = table; popup.listenersToRemoveFromTable.add((list, change) -> { updateGraph(); }); table.getKeys().addListener((list, change) -> { updateGraph(); }); setText(bundle.getString("StringTableEditorPopup.Tab.Graph.tab_title")); setClosable(false); initContent(); updateGraph(); } private void initContent() { VBox root = new VBox(10); setContent(root); root.getChildren().add(chart); chart.setTitle(bundle.getString("StringTableEditorPopup.Tab.Graph.graph_label")); xAxis.setLabel(bundle.getString("StringTableEditorPopup.Tab.Graph.x_axis")); yAxis.setLabel(bundle.getString("StringTableEditorPopup.Tab.Graph.y_axis")); series.setName(bundle.getString("StringTableEditorPopup.Tab.Graph.series_label")); } private void updateGraph() { chart.getData().clear(); ArrayList<KeyValue<String, Integer>> usedLanguages = new ArrayList<>(); final int numKeys = table.getKeys().size(); for (StringTableKey key : table.getKeys()) { for (Map.Entry<Language, String> entry : key.getLanguageTokenMap().entrySet()) { String langName = entry.getKey().getName(); boolean found = false; for (KeyValue<String, Integer> usedLanguage : usedLanguages) { if (usedLanguage.getKey().equals(langName)) { found = true; usedLanguage.setValue(usedLanguage.getValue() + 1); break; } } if (!found) { usedLanguages.add(new KeyValue<>(langName, 1)); } } } ObservableList<String> languages = FXCollections.observableArrayList(); double max = 0; series.getData().clear(); for (KeyValue<String, Integer> usedLanguage : usedLanguages) { String langName = usedLanguage.getKey(); languages.add(langName); int v = usedLanguage.getValue(); max = Math.max(max, v); series.getData().add(new XYChart.Data<>(langName, v)); } xAxis.setCategories(languages); yAxis.setTickUnit(Math.floor(max / 4)); yAxis.setUpperBound(numKeys); yAxis.setLowerBound(0); chart.getData().add(series); } } }
35.096774
187
0.74213
0ad016ea9471d69550d69f705ad37bbe8a50bdd2
876
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.media.ui; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * MediaButtonReceiver is a basic BroadcastReceiver class that receives * ACTION_MEDIA_BUTTON from a MediaSessionCompat. It then forward these intents * to the service listening to them. * This is there for backward compatibility with JB_MR0 and JB_MR1. */ public abstract class MediaButtonReceiver extends BroadcastReceiver { public abstract Class<?> getServiceClass(); @Override public void onReceive(Context context, Intent intent) { intent.setClass(context, getServiceClass()); context.startService(intent); } }
33.692308
79
0.767123
2269985cd7d058abfea9a7166e93bd606efb96e0
509
package ScreenShotAndWaits; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; public class PageWait { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.manage().timeouts().pageLoadTimeout(100, TimeUnit.SECONDS); driver.get("https://www.cars.com/"); } }
20.36
69
0.70334
54eb7eb352a1bcefb7291e47f974fe8544d44eb0
890
class Solution { public String minWindow(String S, String T) { final int m = T.length(); final int n = S.length(); // dp[i][j] := start index (1-indexed) of // the minimum window of T[0..i] and S[0..j) int[][] dp = new int[m + 1][n + 1]; // fill in placeholder values for (int j = 0; j <= n; ++j) dp[0][j] = j + 1; for (int i = 1; i <= m; ++i) for (int j = 1; j <= n; ++j) if (T.charAt(i - 1) == S.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1]; else dp[i][j] = dp[i][j - 1]; int bestLeft = 0; int minLength = Integer.MAX_VALUE; for (int j = 1; j <= n; ++j) if (dp[m][j] > 0 && j - dp[m][j] + 1 < minLength) { bestLeft = dp[m][j] - 1; minLength = j - dp[m][j] + 1; } return minLength == Integer.MAX_VALUE ? "" : S.substring(bestLeft, bestLeft + minLength); } }
27.8125
93
0.469663
44d4479779cb5744d3daa9502495517f6748b390
2,483
package com.imooc.miaoshaproject.service.impl; import com.imooc.miaoshaproject.dao.PromoDOMapper; import com.imooc.miaoshaproject.dataobject.PromoDO; import com.imooc.miaoshaproject.service.ItemService; import com.imooc.miaoshaproject.service.PromoService; import com.imooc.miaoshaproject.service.model.ItemModel; import com.imooc.miaoshaproject.service.model.PromoModel; import org.joda.time.DateTime; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.math.BigDecimal; /** * Created by hzllb on 2018/11/18. */ @Service public class PromoServiceImpl implements PromoService { @Autowired private PromoDOMapper promoDOMapper; @Autowired ItemService itemService; @Autowired RedisTemplate redisTemplate; @Override public PromoModel getPromoByItemId(Integer itemId) { //获取对应商品的秒杀活动信息 PromoDO promoDO = promoDOMapper.selectByItemId(itemId); //dataobject->model PromoModel promoModel = convertFromDataObject(promoDO); if (promoModel == null) { return null; } //判断当前时间是否秒杀活动即将开始或正在进行 if (new DateTime(promoModel.getStartDate()).isAfterNow()) { promoModel.setStatus(1); } else if (new DateTime(promoModel.getEndDate()).isBeforeNow()) { promoModel.setStatus(3); } else { promoModel.setStatus(2); } return promoModel; } @Override public void publishPromo(Integer promoId) { // 通过活动id 获取多动 PromoDO promoDO = promoDOMapper.selectByItemId(promoId); if (promoDO == null || promoDO.getId() == 0) { return; } ItemModel itemModel = itemService.getItemById(promoDO.getItemId()); // 库存同步到redis内 redisTemplate.opsForValue().set("promo_item_stock_" + itemModel.getId(), itemModel.getStock()); } private PromoModel convertFromDataObject(PromoDO promoDO) { if (promoDO == null) { return null; } PromoModel promoModel = new PromoModel(); BeanUtils.copyProperties(promoDO, promoModel); promoModel.setPromoItemPrice(new BigDecimal(promoDO.getPromoItemPrice())); promoModel.setStartDate(promoDO.getStartDate()); promoModel.setEndDate(promoDO.getEndDate()); return promoModel; } }
31.833333
103
0.69271
4378426a02dccee5e02cdb95f551b3abe0f0a78a
632
/* * 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 commandPattern; /** * * @author Steve */ public class CommandGarageDoorOpen implements Command { private final GarageDoor garageDoor; public CommandGarageDoorOpen(GarageDoor garageDoor) { this.garageDoor = garageDoor; } @Override public void execute() { garageDoor.up(); } @Override public void undo() { garageDoor.down(); } }
20.387097
80
0.623418
bee78b4c0db51ae54039cbc0ecb49fa9234f6fa7
4,732
/** * Copyright (c) Microsoft Corporation * * All rights reserved. * * MIT License * * 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.microsoft.azuretools.container.handlers; import java.nio.file.Paths; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.jface.dialogs.MessageDialog; import com.microsoft.azuretools.container.ConsoleLogger; import com.microsoft.azuretools.container.Constant; import com.microsoft.azuretools.container.DockerRuntime; import com.microsoft.azuretools.container.ui.DockerRunDialog; import com.microsoft.azuretools.container.utils.WarUtil; import com.microsoft.azuretools.core.actions.MavenExecuteAction; import com.microsoft.azuretools.core.utils.AzureAbstractHandler; import com.microsoft.azuretools.core.utils.MavenUtils; import com.microsoft.azuretools.core.utils.PluginUtil; import com.microsoft.tooling.msservices.components.DefaultLoader; public class DockerRunHandler extends AzureAbstractHandler { private static final String MAVEN_GOALS = "package"; private IProject project; private String basePath; private String destinationPath; @Override public Object onExecute(ExecutionEvent event) throws ExecutionException { project = PluginUtil.getSelectedProject(); try { if (project == null) { throw new Exception(Constant.ERROR_NO_SELECTED_PROJECT); } basePath = project.getLocation().toString(); if (MavenUtils.isMavenProject(project)) { destinationPath = MavenUtils.getTargetPath(project); } else { destinationPath = Paths.get(basePath, Constant.DOCKERFILE_FOLDER, project.getName() + ".war") .normalize().toString(); } // Stop running container String runningContainerId = DockerRuntime.getInstance().getRunningContainerId(basePath); if (runningContainerId != null) { boolean stop = MessageDialog.openConfirm(PluginUtil.getParentShell(), "Confirmation", Constant.MESSAGE_CONFIRM_STOP_CONTAINER); if (stop) { DockerRuntime.getInstance().cleanRuningContainer(basePath); } else { return null; } } // Build artifact ConsoleLogger.info(String.format(Constant.MESSAGE_EXPORTING_PROJECT, destinationPath)); if (MavenUtils.isMavenProject(project)) { MavenExecuteAction action = new MavenExecuteAction(MAVEN_GOALS); IContainer container; container = MavenUtils.getPomFile(project).getParent(); action.launch(container, () -> { // TODO: callback after mvn package done. IMPORTANT buildAndRun(event); return null; }); } else { WarUtil.export(project, destinationPath); buildAndRun(event); } } catch (Exception e) { e.printStackTrace(); ConsoleLogger.error(String.format(Constant.ERROR_RUNNING_DOCKER, e.getMessage())); sendTelemetryOnException(event, e); } return null; } private void buildAndRun(ExecutionEvent event) { DefaultLoader.getIdeHelper().invokeAndWait(() -> { DockerRunDialog dialog = new DockerRunDialog(PluginUtil.getParentShell(), basePath, destinationPath); dialog.open(); }); } }
43.018182
118
0.680051
3077f8b7009a0637c64c09f35725390ba35473df
3,410
package com.jspxcms.core.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import com.google.common.base.Objects; import com.jspxcms.core.domain.NodeMemberGroup.NodeMemberGroupId; @Entity @Table(name = "cms_node_membergroup") @IdClass(NodeMemberGroupId.class) public class NodeMemberGroup implements java.io.Serializable { private static final long serialVersionUID = 1L; @Transient public void applyDefaultValue() { if (getViewPerm() == null) { setViewPerm(true); } if (getContriPerm() == null) { setContriPerm(true); } if (getCommentPerm() == null) { setCommentPerm(true); } } public NodeMemberGroup() { } public NodeMemberGroup(Node node, MemberGroup group) { this.node = node; this.group = group; } @Id @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_node_id", nullable = false) private Node node; @Id @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_membergroup_id", nullable = false) private MemberGroup group; @Column(name = "f_is_view_perm", nullable = false, length = 1) private Boolean viewPerm; @Column(name = "f_is_contri_perm", nullable = false, length = 1) private Boolean contriPerm; @Column(name = "f_is_comment_perm", nullable = false, length = 1) private Boolean commentPerm; public Node getNode() { return node; } public void setNode(Node node) { this.node = node; } public MemberGroup getGroup() { return group; } public void setGroup(MemberGroup group) { this.group = group; } public Boolean getViewPerm() { return this.viewPerm; } public void setViewPerm(Boolean viewPerm) { this.viewPerm = viewPerm; } public Boolean getContriPerm() { return this.contriPerm; } public void setContriPerm(Boolean contriPerm) { this.contriPerm = contriPerm; } public Boolean getCommentPerm() { return this.commentPerm; } public void setCommentPerm(Boolean commentPerm) { this.commentPerm = commentPerm; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof NodeMemberGroup)) { return false; } NodeMemberGroup that = (NodeMemberGroup) o; return Objects.equal(node, that.node) && Objects.equal(group, that.group); } @Override public int hashCode() { return Objects.hashCode(node, group); } public static class NodeMemberGroupId implements Serializable { private static final long serialVersionUID = 1L; Integer node; Integer group; public NodeMemberGroupId() { } public NodeMemberGroupId(Integer node, Integer group) { this.node = node; this.group = group; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof NodeMemberGroupId)) { return false; } NodeMemberGroupId that = (NodeMemberGroupId) o; return Objects.equal(node, that.node) && Objects.equal(group, that.group); } @Override public int hashCode() { return Objects.hashCode(node, group); } } }
22.142857
78
0.68651
f58233656b45ed6ed2f1e795cfe4f52c822053d6
72
/** * * Classe Macaco */ public class Macaco extends Animal { }
9
36
0.583333
ac89dc7900d01a588cf2f51a20517fea3161b69d
2,728
package com.gao.yingjian.mobiledevelopmentassignmentone.Views; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import androidx.annotation.Nullable; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import com.gao.yingjian.mobiledevelopmentassignmentone.Adapters.SurveyDetailItemsAdapter; import com.gao.yingjian.mobiledevelopmentassignmentone.Models.SurveyDetailGroup; import com.gao.yingjian.mobiledevelopmentassignmentone.R; import com.gao.yingjian.mobiledevelopmentassignmentone.ViewModels.SurveyDetailViewModel; /** * A placeholder fragment containing a simple view. */ public class SurveyDetailFragment extends Fragment { private static final String ARG_SECTION_TITLE = "section_title"; private SurveyDetailViewModel surveyDetailViewModel; private ListView ltvSurveyDetailItems; private SurveyDetailGroup group; private String surveyId; public static SurveyDetailFragment newInstance(String title) { SurveyDetailFragment fragment = new SurveyDetailFragment(); Bundle bundle = new Bundle(); bundle.putString(ARG_SECTION_TITLE, title); fragment.setArguments(bundle); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); surveyDetailViewModel = ViewModelProviders.of(this).get(SurveyDetailViewModel.class); String title = ""; if (getArguments() != null) { title = getArguments().getString(ARG_SECTION_TITLE); } surveyDetailViewModel.setTitle(title); surveyDetailViewModel.setSurveyDetailGroup(this.surveyId, this.group); } @Override public View onCreateView( @NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_survey_detail, container, false); ltvSurveyDetailItems = root.findViewById(R.id.ltvSurveyDetailItems); ltvSurveyDetailItems.setAdapter(new SurveyDetailItemsAdapter(getLayoutInflater(), getContext(), surveyDetailViewModel.getSurveyId(), surveyDetailViewModel.getSurveyDetailItems())); surveyDetailViewModel.getText().observe(this, new Observer<String>() { @Override public void onChanged(@Nullable String s) { } }); return root; } public void setSurveyDetailGroup(String surveyId, SurveyDetailGroup group){ this.surveyId = surveyId; this.group = group; } }
35.894737
188
0.743768
efc3016987ac0591d5a3d39f45d2f594f7806619
10,281
package org.stellasql.stella.gui.statement; import java.sql.Types; import java.util.Iterator; import org.dom4j.DocumentException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.stellasql.stella.ApplicationData; import org.stellasql.stella.ColumnInfo; import org.stellasql.stella.TableInfo; import org.stellasql.stella.gui.util.SyntaxHighlighter; import org.stellasql.stella.session.SessionData; public class InsertDialog extends BaseInsertUpdateDialog { private int lastCompositeHeight = 0; private int lastSashHeight = 0; public InsertDialog(Shell parent, TableInfo tableInfo, SessionData sessionData) { super(parent, tableInfo, sessionData); super.init(true, true, false); setText("Create insert statment for " + this.tableInfo.getName()); getShell().addControlListener(this); } public void addColumnValue(String columnName, Object value) { for (Iterator it = cwList.iterator(); it.hasNext();) { ColumnWidget cw = (ColumnWidget)it.next(); if (cw.getColumnInfo().getColumnName().equals(columnName)) cw.setValue(value); } } @Override public void open() { super.open(); lastCompositeHeight = sash.getParent().getSize().y; Point pt = columnsComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT); if (pt.y < columnsComposite.getSize().y) { int sashLoc = pt.y + inner.getLocation().y + 2; // 2 = top and bottom line from inner if (sc.getClientArea().width < pt.x) // add the height of the scroll bar if it will be shown sashLoc += sc.getHorizontalBar().getSize().y; moveSash(sashLoc); } lastSashHeight = lastCompositeHeight - sash.getLocation().y; } private int moveSash(int y) { int limit = 100; Rectangle sashRect = sash.getBounds(); int top = limit; int bottom = sash.getParent().getSize().y - limit; y = Math.max(Math.min(y, bottom), top); if (y != sashRect.y) { FormData fd = (FormData)sash.getLayoutData(); fd.top = new FormAttachment(0, y); sash.getParent().layout(); } lastSashHeight = sash.getParent().getSize().y - sash.getLocation().y; return y; } @Override protected void layoutControls() { FormData fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.top = new FormAttachment(0, 0); fd.bottom = new FormAttachment(sash, 0); inner.setLayoutData(fd); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.top = new FormAttachment(0, 350); fd.height = 4; sash.setLayoutData(fd); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.top = new FormAttachment(sash, 0); fd.bottom = new FormAttachment(100, 0); statementText.setLayoutData(fd); } @Override public void widgetSelected(SelectionEvent e) { if (e.widget == sash) { e.y = moveSash(e.y); } else super.widgetSelected(e); } @Override public void controlResized(ControlEvent e) { if (getShell().isVisible()) { if (sash.getParent().getSize().y < lastCompositeHeight) { moveSash(sash.getParent().getSize().y - lastSashHeight); } else if (sash.getParent().getSize().y > lastCompositeHeight) { moveSash(sash.getParent().getSize().y - lastSashHeight); } lastCompositeHeight = sash.getParent().getSize().y; } super.controlResized(e); } @Override protected void buildStatement() { StringBuffer sbuf = new StringBuffer(); sbuf.append("INSERT INTO "); // TODO add pref to copy propername (catalog + tablename) as it used to work //sbuf.append(tableInfo.getProperName()); sbuf.append(tableInfo.getName()); StringBuffer columns = new StringBuffer(); StringBuffer values = new StringBuffer(); int max = 80; StringBuffer columsLine = new StringBuffer(); StringBuffer valuesLine = new StringBuffer(); for (Iterator it = cwList.iterator(); it.hasNext();) { ColumnWidget cw = (ColumnWidget)it.next(); if (cw.getChecked()) { StringBuffer temp = new StringBuffer(); if (columns.length() > 0 || columsLine.length() > 0) columsLine.append(", "); temp.append(cw.getColumnInfo().getColumnName()); if (columsLine.length() + temp.length() > max) { columns.append(columsLine).append("\n"); columsLine.delete(0, columsLine.length()); } columsLine.append(temp); temp = new StringBuffer(); if (values.length() > 0 || valuesLine.length() > 0) valuesLine.append(", "); if (cw.getValue().length() > 0) temp.append(cw.getValue()); else temp.append("?"); if (valuesLine.length() + temp.length() > max) { values.append(valuesLine).append("\n"); valuesLine.delete(0, valuesLine.length()); } valuesLine.append(temp); } } columns.append(columsLine); values.append(valuesLine); sbuf.append("\n(").append(columns).append(")\n"); sbuf.append("VALUES"); sbuf.append("\n(").append(values).append(")"); sbuf.append(ApplicationData.getInstance().getQuerySeparator()); statementText.setText(sbuf.toString()); } public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new FillLayout()); shell.pack(); shell.open(); display.addFilter(SWT.KeyDown, new Listener(){@Override public void handleEvent(Event event) { event.doit = false; }}); display.addFilter(SWT.Traverse, new Listener(){@Override public void handleEvent(Event event) { event.doit = false; }}); try { ApplicationData.getInstance().load(); } catch (DocumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } SyntaxHighlighter.initializeColors(); TableInfo tableInfo = new TableInfo("SomeTable", "SomeCatalog", "SomeScheme", "TABLE", true, true, "."); ColumnInfo columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column1"); columnInfo.setTypeName("varchar2"); columnInfo.setDataType(Types.CHAR); columnInfo.setNullable(false); columnInfo.setDefault("asdf"); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column2"); columnInfo.setTypeName("date"); columnInfo.setNullable(true); columnInfo.setDataType(Types.DATE); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column3"); columnInfo.setTypeName("timestamp"); columnInfo.setNullable(true); columnInfo.setDataType(Types.TIMESTAMP); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("time"); columnInfo.setNullable(false); columnInfo.setDataType(Types.TIME); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); columnInfo = new ColumnInfo(); columnInfo.setColumnName("Column4"); columnInfo.setTypeName("varchar2"); columnInfo.setNullable(false); tableInfo.addColumn(columnInfo); InsertDialog id = new InsertDialog(shell, tableInfo, null); id.open(); while (!id.getShell().isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
29.458453
109
0.645171
bf848b2209b6dde4c08bf2601a2d41f4d0782756
1,695
package io.github.oldborn.atspot.spotifywebapi.nexttrack; import com.intellij.openapi.components.ServiceManager; import io.github.oldborn.atspot.spotifywebapi.SptfyGetAccessTokenService; import io.github.oldborn.atspot.spotifywebapi.SptfyRefreshAccessTokenService; import io.github.oldborn.atspot.util.UnsafeOkHttpService; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class SptfyNextTrackService { private SptfyGetAccessTokenService getAccessTokenService = SptfyGetAccessTokenService.getInstance(); private SptfyRefreshAccessTokenService refreshAccessTokenService = SptfyRefreshAccessTokenService.getInstance(); private OkHttpClient okHttpClient = UnsafeOkHttpService.getInstance().getOkHttpClient(); public static SptfyNextTrackService getInstance() { return ServiceManager.getService(SptfyNextTrackService.class); } public boolean nextTrack( boolean tryAgain) throws Exception { String access_token = getAccessTokenService.getAccessToken(); Response response = okHttpClient.newCall(new Request.Builder() .post(RequestBody.create(null, new byte[]{})) .url("https://api.spotify.com/v1/me/player/next") .header("Authorization","Bearer "+access_token) .header("Content-Type","application/json") .build()).execute(); if (response.code() == 204){ return true; }else if (tryAgain){ response.close(); access_token = refreshAccessTokenService.storeAndGetAccessToken(); return nextTrack(false); } return false; } }
39.418605
116
0.722714
2ae8036094da7d0c0a44fae6f50edeb35ea79187
3,037
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.arpablue.arpaimage.layers; import com.arpablue.arpaimage.core.IDraw; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.ArrayList; /** * It contain the layers to produce the final image. * @author AugLaptop */ public class Layers extends IDraw{ protected ArrayList<IDraw> mLayers; protected BufferedImage mImg; protected int mWidth = 400; protected int mHeight = 400; Color mTransparent = new Color(0, 0, 0, 0); public Layers(){ mLayers = new ArrayList<IDraw>(); mLayers.add(new Layer()); } public void setWidth( int width ){ mWidth = width; } public void setHeight( int height ){ mHeight = height; } public void setSize( Dimension size ){ setWidth( (int) size.getWidth() ); setHeight( (int)size.getHeight() ); } /** * It process the layers to return the image final image result. * @return It is the final image result of all layers. */ @Override public void getImage(Graphics2D g){ process(); paint(g); } /** * It process all layers to get the final image. */ public void process(){ for( IDraw l: mLayers){ l.process(); } } protected BufferedImage createImage(){ BufferedImage res = new BufferedImage(this.mWidth, this.mHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = res.createGraphics(); g2d.setBackground(Color.CYAN); return res; } protected void paint(Graphics2D g){ for( IDraw l: mLayers){ l.getImage( g ); } } public void add(IDraw layer) { if( layer == null ){ return; } mLayers.add(layer); } public void add( BufferedImage img) { if( img == null ){ return; } Layer layer = new Layer(); layer.setImage( img ); mLayers.add(layer); } public IDraw get(int index){ if( mLayers == null ){ return null; } if( index >= mLayers.size() ){ return null; } return mLayers.get(index); } @Override public void mouseClicked(int x, int y) {} @Override public void mousePressed(int x, int y) {} @Override public void mouseReleased(int x, int y) {} @Override public void mouseEntered(int x, int y) {} @Override public void mouseExited(int x, int y) {} @Override public void mouseDragged(int x, int y) {} @Override public void mouseMoved(int x, int y) {} @Override public boolean isActive() { return true; } }
25.308333
101
0.587422
c1c962fc2e164e2956b81580002858d243e9fa94
2,179
package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.model.Sbz003cRes; import io.swagger.v3.oas.annotations.media.Schema; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * Sbz003cRes2002 */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2021-03-19T21:32:11.200249+09:00[Asia/Tokyo]") public class Sbz003cRes2002 extends Sbz003cRes { @JsonProperty("resItem2002") private String resItem2002 = null; public Sbz003cRes2002 resItem2002(String resItem2002) { this.resItem2002 = resItem2002; return this; } /** * Get resItem2002 * @return resItem2002 **/ @Schema(example = "ABCDEF", required = true, description = "") @NotNull @Size(min=6,max=6) public String getResItem2002() { return resItem2002; } public void setResItem2002(String resItem2002) { this.resItem2002 = resItem2002; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Sbz003cRes2002 sbz003cRes2002 = (Sbz003cRes2002) o; return Objects.equals(this.resItem2002, sbz003cRes2002.resItem2002) && super.equals(o); } @Override public int hashCode() { return Objects.hash(resItem2002, super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Sbz003cRes2002 {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" resItem2002: ").append(toIndentedString(resItem2002)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
26.253012
145
0.682423
b8a3f808bfd2410092cb4db36fb65f77a9c71554
3,165
package com.example.graph_editor.draw; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.widget.Toast; import androidx.activity.result.ActivityResult; import com.example.graph_editor.model.graph_storage.GraphScanner; import com.example.graph_editor.model.graph_storage.GraphWriter; import com.example.graph_editor.model.graph_storage.InvalidGraphStringException; import com.example.graph_editor.model.DrawManager; import com.example.graph_editor.model.Graph; import com.example.graph_editor.model.mathematics.Rectangle; import com.example.graph_editor.model.state.State; import com.example.graph_editor.model.state.StateStack; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; public class ImportExportLaunchers { public static void importCommand(ActivityResult result, Context context, StateStack stateStack) { if( result.getResultCode() != Activity.RESULT_OK || result.getData() == null) return; Uri uri = result.getData().getData(); try { OutputStream outputStream = context.getContentResolver().openOutputStream(uri); outputStream.write(GraphWriter.toExact(stateStack.getCurrentState().getGraph()).getBytes()); outputStream.close(); } catch (Exception e) { Toast.makeText(context, "Invalid text", Toast.LENGTH_SHORT).show(); return; } Toast.makeText(context, "Export complete", Toast.LENGTH_SHORT).show(); } public static void exportCommand(ActivityResult result, Context context, StateStack stateStack) { if( result.getResultCode() != Activity.RESULT_OK || result.getData() == null) return; Uri uri = result.getData().getData(); Graph g; try { String content; try { InputStream in = context.getContentResolver().openInputStream(uri); BufferedReader r = new BufferedReader(new InputStreamReader(in)); StringBuilder total = new StringBuilder(); for (String line; (line = r.readLine()) != null; ) { total.append(line).append('\n'); } content = total.toString(); System.out.println(content); }catch (Exception e) { Toast.makeText(context, "Invalid text", Toast.LENGTH_SHORT).show(); return; } g = GraphScanner.fromExact(content); } catch (InvalidGraphStringException e) { Toast.makeText(context, "Invalid graph", Toast.LENGTH_SHORT).show(); return; } stateStack.backup(); Rectangle oldRec = stateStack.getCurrentState().getRectangle(); Rectangle optimalRec = DrawManager.getOptimalRectangle(g, 0.1, oldRec); State currentState = stateStack.getCurrentState(); currentState.setGraph(g); currentState.setRectangle(optimalRec); stateStack.invalidateView(); Toast.makeText(context, "Import complete", Toast.LENGTH_SHORT).show(); } }
42.2
104
0.666351
6bc5d29ac3023b94c0d4e1e071da215577e9fad6
260
class Book extends MediaItem { protected String author; public Book(String mediaType,String itemTitle,String itemReference,double itemPrice,String author) { super(mediaType,itemTitle,itemReference,itemPrice); this.author=author; } }
32.5
102
0.742308
c7cd291a11e81a6e007168256629c9e672c0d11d
36,344
/* * This file was automatically generated by EvoSuite * Fri Aug 24 16:08:45 GMT 2018 */ package net.sourceforge.squirrel_sql.plugins.dbcopy.util; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.shaded.org.mockito.Mockito.*; import static org.evosuite.runtime.EvoAssertions.*; import com.gargoylesoftware.base.resource.jdbc.CallableStatementWrapper; import com.gargoylesoftware.base.resource.jdbc.ConnectionWrapper; import java.sql.CallableStatement; import java.sql.Connection; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.TreeSet; import java.util.Vector; import net.sourceforge.squirrel_sql.client.IApplication; import net.sourceforge.squirrel_sql.client.gui.db.SQLAlias; import net.sourceforge.squirrel_sql.client.session.ISession; import net.sourceforge.squirrel_sql.client.session.schemainfo.SchemaInfo; import net.sourceforge.squirrel_sql.fw.id.IIdentifier; import net.sourceforge.squirrel_sql.fw.id.IntegerIdentifier; import net.sourceforge.squirrel_sql.fw.id.UidIdentifier; import net.sourceforge.squirrel_sql.fw.sql.DatabaseObjectInfo; import net.sourceforge.squirrel_sql.fw.sql.DatabaseObjectType; import net.sourceforge.squirrel_sql.fw.sql.ForeignKeyInfo; import net.sourceforge.squirrel_sql.fw.sql.IDatabaseObjectInfo; import net.sourceforge.squirrel_sql.fw.sql.ISQLConnection; import net.sourceforge.squirrel_sql.fw.sql.ISQLDatabaseMetaData; import net.sourceforge.squirrel_sql.fw.sql.ISQLDriver; import net.sourceforge.squirrel_sql.fw.sql.ITableInfo; import net.sourceforge.squirrel_sql.fw.sql.PrimaryKeyInfo; import net.sourceforge.squirrel_sql.fw.sql.SQLConnection; import net.sourceforge.squirrel_sql.fw.sql.SQLDatabaseMetaData; import net.sourceforge.squirrel_sql.fw.sql.SQLDriver; import net.sourceforge.squirrel_sql.fw.sql.SQLDriverPropertyCollection; import net.sourceforge.squirrel_sql.fw.sql.TableColumnInfo; import net.sourceforge.squirrel_sql.fw.sql.TableInfo; import net.sourceforge.squirrel_sql.fw.util.FileWrapper; import net.sourceforge.squirrel_sql.fw.util.FileWrapperFactoryImpl; import net.sourceforge.squirrel_sql.plugins.dbcopy.DBCopyPlugin; import net.sourceforge.squirrel_sql.plugins.dbcopy.SessionInfoProvider; import net.sourceforge.squirrel_sql.plugins.dbcopy.prefs.DBCopyPreferenceBean; import net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.evosuite.runtime.System; import org.evosuite.runtime.ViolatedAssumptionAnswer; import org.evosuite.runtime.testdata.EvoSuiteFile; import org.evosuite.runtime.testdata.FileSystemHandling; import org.jfree.data.time.Quarter; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class DBUtil_ESTest extends DBUtil_ESTest_scaffolding { /** //Test case number: 0 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test00() throws Throwable { String string0 = "No resource is associated with key \""; DatabaseObjectInfo databaseObjectInfo0 = new DatabaseObjectInfo("No resource is associated with key \"", "No resource is associated with key \"", "No resource is associated with key \""); DBUtil.getSchemaNameFromDbObject(databaseObjectInfo0); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getSourceSession(); // Undeclared exception! try { DBUtil.getQualifiedObjectName((ISession) null, "No resource is associated with key \"", "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", (-2)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 1 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test01() throws Throwable { DBCopyPreferenceBean dBCopyPreferenceBean0 = new DBCopyPreferenceBean(); dBCopyPreferenceBean0.setAutoCommitEnabled(true); dBCopyPreferenceBean0.setWriteScript(false); DBUtil.setPreferences(dBCopyPreferenceBean0); DBUtil.setLastStatementValues(">DOc&sb|';M7"); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getDestSession(); TableColumnInfo tableColumnInfo0 = new TableColumnInfo("NZGlT]N,8P", (String) null, "={vXwnFKgB:PN%", "XrL 8=rTle8.5E;@", 1457, ">DOc&sb|';M7", 3116, 441, 3116, 1809, (String) null, ">DOc&sb|';M7", 3116, (-122), "NZGlT]N,8P"); // Undeclared exception! try { DBUtil.getMaxColumnLengthSQL((ISession) null, tableColumnInfo0, ">DOc&sb|';M7", true); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 2 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test02() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getDestSession(); String string0 = "LVd|PU0"; String string1 = null; int int0 = 3; // Undeclared exception! try { DBUtil.getTableCount((ISession) null, "LVd|PU0", "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", (String) null, 3); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 3 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test03() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getDestSession(); String string0 = null; // Undeclared exception! try { DBUtil.getTables((ISession) null, "0T\"?~2UT?USy_TKD", "0T\"?~2UT?USy_TKD", (String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 4 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test04() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getSourceSession(); // Undeclared exception! try { DBUtil.isKeyword((ISession) null, "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy"); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 5 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test05() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getSourceSession(); // Undeclared exception! try { DBUtil.getCatSep((ISession) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 6 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test06() throws Throwable { DBUtil.getLastStatementValues(); DBUtil dBUtil0 = new DBUtil(); ConnectionWrapper connectionWrapper0 = null; try { connectionWrapper0 = new ConnectionWrapper((Connection) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.gargoylesoftware.base.resource.jdbc.ConnectionWrapper", e); } } /** //Test case number: 7 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test07() throws Throwable { DatabaseObjectInfo databaseObjectInfo0 = new DatabaseObjectInfo("clob", "", (String) null); DatabaseObjectType databaseObjectType0 = DatabaseObjectType.VIEW; databaseObjectInfo0.replaceDatabaseObjectTypeConstantObjectsByConstantObjectsOfThisVM(databaseObjectType0); DBUtil.getSchemaNameFromDbObject(databaseObjectInfo0); // Undeclared exception! try { DBUtil.getSchemaFromDbObject(databaseObjectInfo0, (SchemaInfo) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 8 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test08() throws Throwable { FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "bP"); DBUtil.setLastStatement("rxix[I|OK55|"); } /** //Test case number: 9 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test09() throws Throwable { int[] intArray0 = Quarter.FIRST_MONTH_IN_QUARTER; DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); FileWrapperFactoryImpl fileWrapperFactoryImpl0 = new FileWrapperFactoryImpl(); fileWrapperFactoryImpl0.createTempFile("net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", "SessionManager.getNextSession()-> Session "); FileWrapper fileWrapper0 = dBCopyPlugin0.getPluginUserSettingsFolder(); fileWrapperFactoryImpl0.createTempFile("#>;1V6*gKy+X@Rr?-h", "#>;1V6*gKy+X@Rr?-h", fileWrapper0); dBCopyPlugin0.getPluginJarFilePath(); dBCopyPlugin0.setFileWrapperFactory(fileWrapperFactoryImpl0); FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null); dBCopyPlugin0.getSourceSession(); // Undeclared exception! try { DBUtil.getSelectQuery(dBCopyPlugin0, "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", (ITableInfo) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 10 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test10() throws Throwable { DatabaseObjectInfo databaseObjectInfo0 = new DatabaseObjectInfo("clob", "", (String) null); DatabaseObjectType databaseObjectType0 = DatabaseObjectType.VIEW; databaseObjectInfo0.replaceDatabaseObjectTypeConstantObjectsByConstantObjectsOfThisVM(databaseObjectType0); DBUtil.getSchemaNameFromDbObject(databaseObjectInfo0); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getSourceSession(); String string0 = DBUtil.fixCase((ISession) null, ""); assertEquals("", string0); } /** //Test case number: 11 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test11() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); TableColumnInfo tableColumnInfo0 = new TableColumnInfo("net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", "Jgo^cyhDFk", "yG[fN$<-o", (-1857), " NOT NULL", (-1857), 28, 28, 273, "$m,@?", " NOT NULL", 273, 2, ""); DBCopyPlugin dBCopyPlugin1 = new DBCopyPlugin(); dBCopyPlugin1.getSourceSession(); DBUtil.replaceOtherDataType(tableColumnInfo0, (ISession) null); dBCopyPlugin0.getDestSession(); dBCopyPlugin0.getSourceSession(); // Undeclared exception! try { DBUtil.dropTable("net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", ").d`54rY0SL/p_Q=n,", "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", (ISession) null, false, 3706); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 12 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test12() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getDestSession(); String string0 = "r|.,Fk~lr`;3Ywp_"; TableColumnInfo tableColumnInfo0 = new TableColumnInfo("net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", (String) null, "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", 1111, "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", (-2105376123), (-2105376123), (-2105376123), 229, "r|.,Fk~lr`;3Ywp_", (String) null, (-2105376123), 1111, "r|.,Fk~lr`;3Ywp_"); DBUtil.replaceOtherDataType(tableColumnInfo0, (ISession) null); String string1 = "custom level class ["; String string2 = "dF|#I"; // Undeclared exception! try { DBUtil.getTableInfo((ISession) null, "custom level class [", "dF|#I"); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 13 /*Coverage entropy=0.5623351446188083 */ @Test(timeout = 4000) public void test13() throws Throwable { int int0 = 2; DBUtil.typesAreEquivalent(2, 2); TableColumnInfo[] tableColumnInfoArray0 = null; // Undeclared exception! try { DBUtil.getColumnList((TableColumnInfo[]) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 14 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test14() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getDestSession(); dBCopyPlugin0.getSourceSession(); dBCopyPlugin0.getDestSession(); dBCopyPlugin0.getApplication(); SchemaInfo schemaInfo0 = new SchemaInfo((IApplication) null); // Undeclared exception! try { DBUtil.getInsertSQL(dBCopyPlugin0, "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", (ITableInfo) null, 2); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 15 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test15() throws Throwable { DBUtil.typesAreEquivalent(0, 0); Vector<IDatabaseObjectInfo> vector0 = new Vector<IDatabaseObjectInfo>(); List<ITableInfo> list0 = DBUtil.convertObjectToTableList(vector0); List<IDatabaseObjectInfo> list1 = DBUtil.convertTableToObjectList(list0); assertTrue(list1.isEmpty()); } /** //Test case number: 16 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test16() throws Throwable { TableColumnInfo[] tableColumnInfoArray0 = new TableColumnInfo[0]; DBUtil.getColumnList(tableColumnInfoArray0); DBUtil.convertObjectArrayToTableList(tableColumnInfoArray0); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getSourceSession(); dBCopyPlugin0.getSourceSession(); // Undeclared exception! try { DBUtil.sameDatabaseType((ISession) null, (ISession) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 17 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test17() throws Throwable { TableColumnInfo[] tableColumnInfoArray0 = new TableColumnInfo[1]; TableColumnInfo tableColumnInfo0 = new TableColumnInfo("", "", "", "46IdIs=F.OaN\";'VYH", (-1132), "", (-2), (-2), (-1132), 0, "?1/6s@vQ[bx[EFEYq@L", "46IdIs=F.OaN\";'VYH", 2, 993, ""); tableColumnInfoArray0[0] = tableColumnInfo0; DBUtil.getColumnList(tableColumnInfoArray0); // Undeclared exception! try { DBUtil.convertObjectArrayToTableList(tableColumnInfoArray0); fail("Expecting exception: ClassCastException"); } catch(ClassCastException e) { // // net.sourceforge.squirrel_sql.fw.sql.TableColumnInfo cannot be cast to net.sourceforge.squirrel_sql.fw.sql.ITableInfo // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 18 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test18() throws Throwable { int[] intArray0 = Quarter.FIRST_MONTH_IN_QUARTER; DatabaseObjectInfo databaseObjectInfo0 = new DatabaseObjectInfo("TimeSeriesDataset.addSeries(): cannot add more series than specified in c'tor", "TimeSeriesDataset.addSeries(): cannot add more series than specified in c'tor", "TimeSeriesDataset.addSeries(): cannot add more series than specified in c'tor"); DatabaseObjectType databaseObjectType0 = DatabaseObjectType.COLUMN; databaseObjectInfo0.replaceDatabaseObjectTypeConstantObjectsByConstantObjectsOfThisVM(databaseObjectType0); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getApplication(); SchemaInfo schemaInfo0 = new SchemaInfo((IApplication) null); // Undeclared exception! try { DBUtil.getColumnCount((ISQLConnection) null, (ITableInfo) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 19 /*Coverage entropy=0.5004024235381879 */ @Test(timeout = 4000) public void test19() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getPluginAppSettingsFolder(); TableColumnInfo tableColumnInfo0 = new TableColumnInfo("p>>3A(", ").d`54rY0SL/p_Q=n,", ").d`54rY0SL/p_Q=n,", "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", 0, ").d`54rY0SL/p_Q=n,", (-1132), 2001, 993, (-1132), "46IdIs=F.OaN\";'VYH", "2d1# 'whDuH|,*bV", (-1132), (-1132), "@``O3S~-%zX"); TableColumnInfo[] tableColumnInfoArray0 = new TableColumnInfo[4]; tableColumnInfoArray0[0] = tableColumnInfo0; tableColumnInfoArray0[1] = tableColumnInfo0; tableColumnInfoArray0[2] = tableColumnInfo0; tableColumnInfoArray0[3] = tableColumnInfo0; DBUtil.getColumnList(tableColumnInfoArray0); // Undeclared exception! try { DBUtil.convertObjectArrayToTableList(tableColumnInfoArray0); fail("Expecting exception: ClassCastException"); } catch(ClassCastException e) { // // net.sourceforge.squirrel_sql.fw.sql.TableColumnInfo cannot be cast to net.sourceforge.squirrel_sql.fw.sql.ITableInfo // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 20 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test20() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getPluginAppSettingsFolder(); dBCopyPlugin0.getSourceSession(); TreeSet<ForeignKeyInfo> treeSet0 = new TreeSet<ForeignKeyInfo>(); ForeignKeyInfo foreignKeyInfo0 = mock(ForeignKeyInfo.class, new ViolatedAssumptionAnswer()); doReturn(0).when(foreignKeyInfo0).compareTo(any(net.sourceforge.squirrel_sql.fw.sql.IDatabaseObjectInfo.class)); treeSet0.add(foreignKeyInfo0); LinkedList<IDatabaseObjectInfo> linkedList0 = new LinkedList<IDatabaseObjectInfo>(treeSet0); // Undeclared exception! try { DBUtil.convertObjectToTableList(linkedList0); fail("Expecting exception: ClassCastException"); } catch(ClassCastException e) { // // net.sourceforge.squirrel_sql.fw.sql.ForeignKeyInfo$MockitoMock$1507657820 cannot be cast to net.sourceforge.squirrel_sql.fw.sql.ITableInfo // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 21 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test21() throws Throwable { TableColumnInfo tableColumnInfo0 = new TableColumnInfo(" from ", " from ", "sQlect count(*) from ", "Q=W&1m ]J>", (-1064), " from ", (-1064), (-1064), (-7), 4025, "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", "EB!SIT^#4:", 4025, (-7), "/CsY$-)y7-c$0e"); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); FileWrapperFactoryImpl fileWrapperFactoryImpl0 = new FileWrapperFactoryImpl(); dBCopyPlugin0.setFileWrapperFactory(fileWrapperFactoryImpl0); dBCopyPlugin0.getDestSession(); DBUtil.replaceDistinctDataType((-1064), tableColumnInfo0, (ISession) null); ITableInfo iTableInfo0 = null; DBUtil.validateColumnNames((ITableInfo) null, dBCopyPlugin0); Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); ConnectionWrapper connectionWrapper0 = new ConnectionWrapper(connection0); DatabaseObjectType databaseObjectType0 = DatabaseObjectType.TRIGGER; IIdentifier iIdentifier0 = databaseObjectType0.getIdentifier(); SQLDriver sQLDriver0 = new SQLDriver(iIdentifier0); SQLDriverPropertyCollection sQLDriverPropertyCollection0 = new SQLDriverPropertyCollection(); SQLConnection sQLConnection0 = new SQLConnection(connectionWrapper0, sQLDriverPropertyCollection0, sQLDriver0); dBCopyPlugin0.getPasteToTableInfo(sQLConnection0, "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", " from "); // Undeclared exception! try { DBUtil.getColumnType((ISQLConnection) sQLConnection0, (ITableInfo) null, (-683)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.fw.sql.SQLDatabaseMetaData", e); } } /** //Test case number: 22 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test22() throws Throwable { DatabaseObjectType databaseObjectType0 = DatabaseObjectType.COLUMN; DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getApplication(); SchemaInfo schemaInfo0 = new SchemaInfo((IApplication) null); dBCopyPlugin0.getDestSession(); DBUtil.getColumnType((ISQLConnection) null, (ITableInfo) null, "-.n]"); // Undeclared exception! try { DBUtil.getColumnNames((ISQLConnection) null, (ITableInfo) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 23 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test23() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getDestSession(); dBCopyPlugin0.getSourceSession(); dBCopyPlugin0.getDestSession(); TableColumnInfo tableColumnInfo0 = new TableColumnInfo("{MtNHf@)g", "yF*1<5B]M#", "p>>3A(", "p>>3A(", (-847), "{MtNHf@)g", 38, (-1230), (-595), (-1033), "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", "p>>3A(", (-3498), (-2595), "m}|Gge;"); DBCopyPlugin dBCopyPlugin1 = new DBCopyPlugin(); DBCopyPlugin dBCopyPlugin2 = new DBCopyPlugin(); dBCopyPlugin2.getSourceSession(); dBCopyPlugin2.getSourceDatabaseObjects(); dBCopyPlugin2.setSourceDatabaseObjects((List<IDatabaseObjectInfo>) null); // Undeclared exception! try { DBUtil.replaceDistinctDataType(2001, tableColumnInfo0, (ISession) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 24 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test24() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getSourceSession(); dBCopyPlugin0.getPluginJarFilePath(); dBCopyPlugin0.setSourceSession((ISession) null); dBCopyPlugin0.unload(); boolean boolean0 = DBUtil.typesAreEquivalent((-7), (-7)); assertTrue(boolean0); } /** //Test case number: 25 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test25() throws Throwable { LinkedList<ITableInfo> linkedList0 = new LinkedList<ITableInfo>(); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getPasteToTableInfo((ISQLConnection) null, "e3FBMjf", "e3FBMjf"); linkedList0.push((ITableInfo) null); DBUtil.convertTableToObjectList(linkedList0); DBCopyPlugin dBCopyPlugin1 = new DBCopyPlugin(); dBCopyPlugin1.getDestSession(); // Undeclared exception! try { DBUtil.sameDatabaseType((ISession) null, (ISession) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 26 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test26() throws Throwable { DBUtil.typesAreEquivalent(16, 8); DBUtil.typesAreEquivalent(1327, 274); TableColumnInfo tableColumnInfo0 = new TableColumnInfo("DBUtil.error.missingtable", "61cYS$dq%", "DBUtil.error.missingtable", (String) null, (-600), "java.util.Calendar", 16, 274, 2958465, 4, "61cYS$dq%", "W]RxbybI", 200, 64000, "(&F>}n;]%IaO%cW]I0"); TableColumnInfo tableColumnInfo1 = new TableColumnInfo("not null auto_increment", "61cYS$dq%", "-.n]", "(&F>}n;]%IaO%cW]I0", (-2), "-.n]", 200, 1327, 2048, (-2150), "(&F>}n;]%IaO%cW]I0", "61cYS$dq%", (-7), 200, "(&F>}n;]%IaO%cW]I0"); DBUtil.isBinaryType(tableColumnInfo1); DBUtil.getLastStatement(); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); ISession iSession0 = dBCopyPlugin0.getDestSession(); assertNull(iSession0); } /** //Test case number: 27 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test27() throws Throwable { DatabaseObjectInfo databaseObjectInfo0 = new DatabaseObjectInfo((String) null, (String) null, (String) null); DatabaseObjectType databaseObjectType0 = DatabaseObjectType.SCHEMA; databaseObjectInfo0.replaceDatabaseObjectTypeConstantObjectsByConstantObjectsOfThisVM(databaseObjectType0); databaseObjectInfo0.replaceDatabaseObjectTypeConstantObjectsByConstantObjectsOfThisVM(databaseObjectType0); DBUtil.getSchemaFromDbObject(databaseObjectInfo0, (SchemaInfo) null); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getDestSession(); // Undeclared exception! try { DBUtil.deleteDataInExistingTable((ISession) null, "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", "**X-lU", "c.RS`E6xG(K/AjSP"); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 28 /*Coverage entropy=1.6094379124341005 */ @Test(timeout = 4000) public void test28() throws Throwable { DBUtil.typesAreEquivalent((-24), (-24)); TableColumnInfo tableColumnInfo0 = new TableColumnInfo("61cYS$dq%", "61cYS$dq%", "un2gM33OBEqA: L;", "un2gM33OBEqA: L;", (-24), "DBUtil.error.missingtable", (-24), (-24), (-24), (-24), "DBUtil.error.missingtable", "un2gM33OBEqA: L;", (-24), (-24), "un2gM33OBEqA: L;"); DatabaseObjectType databaseObjectType0 = DatabaseObjectType.SCHEMA; tableColumnInfo0.replaceDatabaseObjectTypeConstantObjectsByConstantObjectsOfThisVM(databaseObjectType0); DBUtil.isBinaryType(tableColumnInfo0); DBUtil.getLastStatement(); DatabaseObjectType databaseObjectType1 = DatabaseObjectType.COLUMN; DBUtil.getSchemaNameFromDbObject(tableColumnInfo0); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getSourceSession(); String string0 = "<.f1FN*"; // Undeclared exception! try { DBUtil.deleteDataInExistingTable((ISession) null, "<.f1FN*", "\"", "net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy"); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 29 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test29() throws Throwable { FileWrapperFactoryImpl fileWrapperFactoryImpl0 = new FileWrapperFactoryImpl(); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.setFileWrapperFactory(fileWrapperFactoryImpl0); DBUtil.validateColumnNames((ITableInfo) null, (SessionInfoProvider) null); Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); doReturn((CallableStatement) null).when(connection0).prepareCall(anyString()); ConnectionWrapper connectionWrapper0 = new ConnectionWrapper(connection0); // Undeclared exception! try { connectionWrapper0.prepareCall("#E"); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // statement // verifyException("com.gargoylesoftware.base.resource.jdbc.StatementWrapper", e); } } /** //Test case number: 30 /*Coverage entropy=0.5004024235381879 */ @Test(timeout = 4000) public void test30() throws Throwable { boolean boolean0 = DBUtil.typesAreEquivalent(Integer.MIN_VALUE, (-3)); TableColumnInfo tableColumnInfo0 = new TableColumnInfo(" GI#m", (String) null, " NOT NULL", " GI#m", (-3), " GI#m", (-3), (-1074), (-1074), (-777), "[|d5oC?#1;ef02u1", "Unexpected exception while attempting to determine if a table (", (-3), (-1117), "AXION"); boolean boolean1 = DBUtil.isBinaryType(tableColumnInfo0); assertFalse(boolean1 == boolean0); assertTrue(boolean1); } /** //Test case number: 31 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test31() throws Throwable { FileSystemHandling.shouldAllThrowIOExceptions(); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getSourceSession(); // Undeclared exception! try { DBUtil.getTableCount((ISession) null, "OOi,9W)[$}pw/yo8B'^", "OOi,9W)[$}pw/yo8B'^", "", 1); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 32 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test32() throws Throwable { DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.setPasteMenuEnabled(true); dBCopyPlugin0.getDestSession(); dBCopyPlugin0.setDestSession((ISession) null); dBCopyPlugin0.setSourceSession((ISession) null); TableColumnInfo tableColumnInfo0 = new TableColumnInfo("net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", "\"l", "", "lboXtea)(HTi", (-21), "qo6s.RXb>c", (-21), 52, 25, (-732), "", (String) null, (-3), 52, " 1"); TableColumnInfo tableColumnInfo1 = new TableColumnInfo("net.sourceforge.squirrel_sql.plugins.dbcopy.dbcopy", "ebCtZJOMsr{.G7(", "lboXtea)(HTi", "O}IY?", (-732), " 1", 25, 25, (-732), (-3320), " kh/W%auoHC", "\"l", (-1994091956), 50, "g"); DBUtil.isBinaryType(tableColumnInfo1); ISQLConnection iSQLConnection0 = null; // Undeclared exception! try { DBUtil.getColumnName((ISQLConnection) null, (ITableInfo) null, (-5)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil", e); } } /** //Test case number: 33 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test33() throws Throwable { boolean boolean0 = DBUtil.typesAreEquivalent(3, 2); DBUtil.typesAreEquivalent(3, 3); boolean boolean1 = DBUtil.typesAreEquivalent(3, 3); assertTrue(boolean1); System.setCurrentTimeMillis(3); boolean boolean2 = DBUtil.typesAreEquivalent((-1596), 3); assertFalse(boolean2 == boolean0); assertFalse(boolean2); } /** //Test case number: 34 /*Coverage entropy=0.45056120886630463 */ @Test(timeout = 4000) public void test34() throws Throwable { byte[] byteArray0 = new byte[8]; byteArray0[0] = (byte)79; byteArray0[1] = (byte)4; byteArray0[2] = (byte) (-64); byteArray0[3] = (byte) (-112); byteArray0[4] = (byte)50; byteArray0[5] = (byte) (-87); byteArray0[6] = (byte)125; byteArray0[7] = (byte) (-7); FileSystemHandling.appendDataToFile((EvoSuiteFile) null, byteArray0); DBUtil.typesAreEquivalent((-8), (-7)); DBUtil.typesAreEquivalent(2, 3); DBCopyPlugin dBCopyPlugin0 = new DBCopyPlugin(); dBCopyPlugin0.getSourceSession(); String string0 = DBUtil.fixCase((ISession) null, (String) null); assertNull(string0); } }
41.583524
426
0.684405
eceae56639b1e4b1fe998d93951133a3cfa1ce08
497
/* https://leetcode.com/problems/boats-to-save-people/ 881. Boats to Save People */ class Solution { public int numRescueBoats(int[] people, int limit) { Arrays.sort(people); int i =0; int j = people.length-1; int result = 0; while(i<=j){ if(people[i]+people[j] <= limit){ i++; j--; }else{ j--; } result++; } return result; } }
20.708333
56
0.432596
92e89deefbe6785ca8e583c3365448fdae8af000
3,108
// automatically generated by the FlatBuffers compiler, do not modify package Neodroid.FBS.Reaction; import java.nio.*; import java.lang.*; import java.util.*; import com.google.flatbuffers.*; @SuppressWarnings("unused") public final class FConfiguration extends Table { public static FConfiguration getRootAsFConfiguration(ByteBuffer _bb) { return getRootAsFConfiguration(_bb, new FConfiguration()); } public static FConfiguration getRootAsFConfiguration(ByteBuffer _bb, FConfiguration obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public void __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; vtable_start = bb_pos - bb.getInt(bb_pos); vtable_size = bb.getShort(vtable_start); } public FConfiguration __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } public String configurableName() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } public ByteBuffer configurableNameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } public ByteBuffer configurableNameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } public double configurableValue() { int o = __offset(6); return o != 0 ? bb.getDouble(o + bb_pos) : 0.0; } public static int createFConfiguration(FlatBufferBuilder builder, int configurable_nameOffset, double configurable_value) { builder.startObject(2); FConfiguration.addConfigurableValue(builder, configurable_value); FConfiguration.addConfigurableName(builder, configurable_nameOffset); return FConfiguration.endFConfiguration(builder); } public static void startFConfiguration(FlatBufferBuilder builder) { builder.startObject(2); } public static void addConfigurableName(FlatBufferBuilder builder, int configurableNameOffset) { builder.addOffset(0, configurableNameOffset, 0); } public static void addConfigurableValue(FlatBufferBuilder builder, double configurableValue) { builder.addDouble(1, configurableValue, 0.0); } public static int endFConfiguration(FlatBufferBuilder builder) { int o = builder.endObject(); builder.required(o, 4); // configurable_name return o; } @Override protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); } public static FConfiguration __lookup_by_key(FConfiguration obj, int vectorLocation, String key, ByteBuffer bb) { byte[] byteKey = key.getBytes(Table.UTF8_CHARSET.get()); int span = bb.getInt(vectorLocation - 4); int start = 0; while (span != 0) { int middle = span / 2; int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb); if (comp > 0) { span = middle; } else if (comp < 0) { middle++; start += middle; span -= middle; } else { return (obj == null ? new FConfiguration() : obj).__assign(tableOffset, bb); } } return null; } }
47.815385
203
0.723616
5214be12df67907570b5123c218c203c586c716e
16,091
/* * Copyright © 2015 - 2021 ReSys ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dialob.session.engine.session.model; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.protobuf.CodedInputStream; import com.google.protobuf.CodedOutputStream; import io.dialob.api.proto.Action; import io.dialob.rule.parser.api.PrimitiveValueType; import io.dialob.rule.parser.api.ValueType; import io.dialob.session.engine.Utils; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.*; import static io.dialob.session.engine.Utils.readNullableString; import static io.dialob.session.engine.Utils.writeNullableString; @EqualsAndHashCode @ToString public class ItemState implements SessionObject { private static final long serialVersionUID = -3974128908954128671L; public enum Status { /** * Item state instance is just created, but have not been evaluated */ NEW, /** * Normal state */ OK, /** * Update failed */ ERROR, /** * expecting value from asyncronous evaluation */ PENDING } private static final int DISPLAY_ITEM_BIT = 1 << 0; private static final int ACTIVE_BIT = 1 << 1; private static final int DISABLED_BIT = 1 << 2; private static final int REQUIRED_BIT = 1 << 3; private static final int ROWS_CAN_BE_ADDED_BIT = 1 << 4; private static final int ROWS_CAN_BE_REMOVED_BIT = 1 << 5; private static final int INVALID_ANSWERS_BIT = 1 << 6; private static final int HAS_CUSTOM_PROPS_BIT = 1 << 7; private final ItemId id; private final ItemId prototypeId; private final String type; private final String view; private final String valueSetId; private Status status = Status.NEW; private Object answer; private Object value; private Object defaultValue; private int bits = (ACTIVE_BIT | ROWS_CAN_BE_ADDED_BIT | ROWS_CAN_BE_REMOVED_BIT); private String label; private String description; // indicates whethet questionnaire is completed private List<String> classNames = ImmutableList.of(); private List<ItemId> items = ImmutableList.of(); private List<ItemId> availableItems = ImmutableList.of(); private Map<String, Object> props = new HashMap<>(); private Set<Action.Type> allowedActions = ImmutableSet.of(); private ItemId activePage; protected void setBits(boolean toValue, int bit) { if (toValue) { setBits(bit); } else { resetBits(bit); } } protected void setBits(int bit) { bits = bits | bit; } protected void resetBits(int bit) { bits = bits & (~bit); } protected boolean isBit(int bit) { return (bits & bit) != 0; } public static ItemState readFrom(CodedInputStream input) throws IOException { final ItemId id = IdUtils.readIdFrom(input); final ItemId prototypeId = IdUtils.readIdFrom(input); final String type = input.readString(); final String view = readNullableString(input); final String valueSetId = readNullableString(input); ItemState state = new ItemState(id, prototypeId, type, view, valueSetId); state.activePage = IdUtils.readIdFrom(input); state.status = Status.values()[input.readRawByte()]; state.bits = input.readInt32(); state.label = readNullableString(input); state.description = readNullableString(input); state.answer = Utils.readObjectValue(input); state.value = readValue(input); state.defaultValue = readValue(input); state.classNames = readStringList(input); state.items = readIdList(input); state.availableItems = readIdList(input); int count = input.readInt32(); if ( count > 0) { Action.Type[] types = new Action.Type[count]; for (int i = 0; i < count; i++ ){ types[i] = Action.Type.values()[input.readInt32()]; } state.allowedActions = ImmutableSet.copyOf(types); } else { state.allowedActions = ImmutableSet.of(); } return state; } public void writeTo(CodedOutputStream output) throws IOException { IdUtils.writeIdTo(id, output); IdUtils.writeIdTo(prototypeId, output); output.writeStringNoTag(type); writeNullableString(output, view); writeNullableString(output, valueSetId); IdUtils.writeIdTo(activePage, output); output.writeRawByte(status.ordinal()); output.writeInt32NoTag(bits); writeNullableString(output, label); writeNullableString(output, description); Utils.writeObjectValue(output, answer); writeValue(output, Utils.mapQuestionTypeToValueType(type).orElse(null), value); writeValue(output, Utils.mapQuestionTypeToValueType(type).orElse(null), defaultValue); writeStringList(output, classNames); writeIdList(output, items); writeIdList(output, availableItems); output.writeInt32NoTag(allowedActions.size()); for (Action.Type actionType: allowedActions) { output.writeInt32NoTag(actionType.ordinal()); } } private void writeValue(CodedOutputStream output, ValueType type, Object value) throws IOException { final boolean present = value != null && type != null; output.writeBoolNoTag(present); if (present) { output.writeRawByte(type.getTypeCode()); type.writeTo(output, value); } } private static Object readValue(CodedInputStream input) throws IOException { if (input.readBool()) { byte typeCode = input.readRawByte(); ValueType valueType; if ((0x80 & typeCode) != 0) { typeCode = (byte) (typeCode & 0x7f); valueType = ValueType.arrayOf(PrimitiveValueType.values()[typeCode]); } else { valueType = PrimitiveValueType.values()[typeCode]; } return valueType.readFrom(input); } return null; } private void writeIdList(CodedOutputStream output, List<ItemId> itemIds) throws IOException { output.writeInt32NoTag(itemIds.size()); for (ItemId s : itemIds) { IdUtils.writeIdTo(s, output); } } private void writeStringList(CodedOutputStream output, List<String> stringList) throws IOException { output.writeInt32NoTag(stringList.size()); for (String s : stringList) { output.writeStringNoTag(s); } } private static List<ItemId> readIdList(CodedInputStream input) throws IOException { int count = input.readInt32(); if (count > 0) { ItemId[] ids = new ItemId[count]; for (int i = 0; i < count; i++) { ids[i] = IdUtils.readIdFrom(input); } return ImmutableList.copyOf(ids); } return ImmutableList.of(); } private static List<String> readStringList(CodedInputStream input) throws IOException { int count = input.readInt32(); if (count > 0) { String[] ids = new String[count]; for (int i = 0; i < count; i++) { ids[i] = input.readString(); } return ImmutableList.copyOf(ids); } return ImmutableList.of(); } public ItemState(@Nonnull ItemId id, ItemId prototypeId, @Nonnull String type, String view, String valueSetId) { this.id = id; this.prototypeId = prototypeId; this.type = type; this.view = view; this.valueSetId = valueSetId; resetBits(DISPLAY_ITEM_BIT); } public ItemState(@Nonnull ItemId id, ItemId prototypeId, @Nonnull String type, String view, boolean displayItem, String valueSetId, Object answer, Object value, Object defaultValue, ItemId activePage) { this.valueSetId = valueSetId; this.id = id; this.prototypeId = prototypeId; this.type = type; this.view = view; this.setBits(displayItem, DISPLAY_ITEM_BIT); this.answer = answer; this.value = value; this.defaultValue = defaultValue; this.activePage = activePage; } ItemState(@Nonnull ItemState itemState) { this(itemState.getId(), itemState); } ItemState(@Nonnull ItemId id, @Nonnull ItemState itemState) { this.id = id; this.prototypeId = itemState.prototypeId; this.type = itemState.type; this.view = itemState.view; this.valueSetId = itemState.valueSetId; this.status = itemState.status; this.answer = itemState.answer; this.value = itemState.value; this.defaultValue = itemState.defaultValue; this.bits = itemState.bits; this.label = itemState.label; this.description = itemState.description; this.classNames = itemState.classNames; this.items = itemState.items; this.availableItems = itemState.availableItems; this.props = itemState.props; this.allowedActions = itemState.allowedActions; this.activePage = itemState.activePage; } @Nonnull public ItemId getId() { return id; } @Nullable public ItemId getPrototypeId() { return prototypeId; } @Nonnull public String getType() { return type; } @Nullable public String getView() { return view; } @Override public boolean isDisplayItem() { return (bits & DISPLAY_ITEM_BIT) != 0; } public Optional<String> getValueSetId() { return Optional.ofNullable(valueSetId); } public Status getStatus() { return status; } public Object getAnswer() { return answer; } public Object getValue() { return isActive() && value != null ? value : defaultValue; } @Override public boolean isActive() { return isBit(ACTIVE_BIT); } public boolean isAnswered() { return !isNull() && !isBlank(); } public boolean isBlank() { return isNull() || value instanceof CharSequence && StringUtils.isBlank((CharSequence)value); } public boolean isNull() { return value == null; } public boolean isInvalidAnswers() { return isBit(INVALID_ANSWERS_BIT); } public boolean isInvalid() { if (answer instanceof String) { return value == null && StringUtils.isNotEmpty((CharSequence) answer); } return value == null && answer != null; } @Override public boolean isDisabled() { return (bits & DISABLED_BIT) != 0; } public boolean isRequired() { return (bits & REQUIRED_BIT) != 0; } public boolean isRowsCanBeAdded() { return (bits & ROWS_CAN_BE_ADDED_BIT) != 0; } public boolean isRowsCanBeRemoved() { return (bits & ROWS_CAN_BE_REMOVED_BIT) != 0; } public boolean hasCustomProps() { return (bits & HAS_CUSTOM_PROPS_BIT) != 0; } public String getLabel() { return label; } public String getDescription() { return description; } public List<String> getClassNames() { return classNames; } @Nonnull public List<ItemId> getItems() { return items; } public List<ItemId> getAvailableItems() { return availableItems; } public Optional<ItemId> getActivePage() { return Optional.ofNullable(activePage); } public Set<Action.Type> getAllowedActions() { return allowedActions; } @Nonnull public ItemState withId(@Nonnull ItemId newId) { return new ItemState(newId, this); } public class UpdateBuilder { private ItemState itemState; UpdateBuilder() { } private ItemState state() { if (itemState == null) { this.itemState = new ItemState(ItemState.this); } return itemState; } private boolean hasNewState() { return this.itemState != null; } public UpdateBuilder setStatus(Status newStatus) { if (status != newStatus) { state().status = newStatus; } return this; } public UpdateBuilder setAnswer(Object newAnswer) { if (!Objects.equals(answer, newAnswer)) { state().answer = newAnswer; } return this; } public UpdateBuilder setValue(Object newValue) { if (!Objects.equals(value, newValue)) { state().value = newValue; } return this; } public UpdateBuilder setActive(boolean newActive) { if (isBit(ACTIVE_BIT) != newActive) { state().setBits(newActive, ACTIVE_BIT); } return this; } public UpdateBuilder setDisabled(Boolean newDisabled) { if (newDisabled == null) { return this; } if (isBit(DISABLED_BIT) != newDisabled) { state().setBits(newDisabled, DISABLED_BIT); } return this; } public UpdateBuilder setRequired(boolean newRequired) { if (isBit(REQUIRED_BIT) != newRequired) { state().setBits(newRequired, REQUIRED_BIT); } return this; } public UpdateBuilder setRowsCanBeAdded(boolean newRowsCanBeAdded) { if (isBit(ROWS_CAN_BE_ADDED_BIT) != newRowsCanBeAdded) { state().setBits(newRowsCanBeAdded, ROWS_CAN_BE_ADDED_BIT); } return this; } public UpdateBuilder setRowsCanBeRemoved(boolean newRowsCanBeRemoved) { if (isBit(ROWS_CAN_BE_REMOVED_BIT) != newRowsCanBeRemoved) { state().setBits(newRowsCanBeRemoved, ROWS_CAN_BE_REMOVED_BIT); } return this; } public UpdateBuilder setHasCustomProps(boolean newHasCustomProps) { if (isBit(HAS_CUSTOM_PROPS_BIT) != newHasCustomProps) { state().setBits(newHasCustomProps, HAS_CUSTOM_PROPS_BIT); } return this; } public UpdateBuilder setLabel(String newLabel) { if (!Objects.equals(label, newLabel)) { state().label = newLabel; } return this; } public UpdateBuilder setDescription(String newDescription) { if (!Objects.equals(description, newDescription)) { state().description = newDescription; } return this; } public UpdateBuilder setProp(String propName, Object newValue) { Object previous = props.get(propName); if (!Objects.equals(previous, newValue)) { state().props.put(propName, newValue); } return this; } public UpdateBuilder setClassNames(List<String> newClassNames) { if (!Objects.equals(classNames, newClassNames)) { state().classNames = ImmutableList.copyOf(newClassNames); } return this; } public UpdateBuilder setItems(List<ItemId> newItems) { if (!Objects.equals(items, newItems)) { state().items = ImmutableList.copyOf(newItems); } return this; } public UpdateBuilder setAvailableItems(List<ItemId> newAvailableItems) { if (!Objects.equals(availableItems, newAvailableItems)) { state().availableItems = ImmutableList.copyOf(newAvailableItems); } return this; } public UpdateBuilder setAllowedActions(Set<Action.Type> newAllowedActions) { if (!Objects.equals(allowedActions, newAllowedActions)) { state().allowedActions = ImmutableSet.copyOf(newAllowedActions); } return this; } public UpdateBuilder setActivePage(ItemId newActivePage) { if ((hasNewState() && state().items.contains(newActivePage) || items.contains(newActivePage)) && !Objects.equals(activePage, newActivePage)) { // TODO matches is active item "available" state().activePage = newActivePage; } return this; } public UpdateBuilder setInvalidAnswers(boolean newIsInvalidAnswers) { if (isBit(INVALID_ANSWERS_BIT) != newIsInvalidAnswers) { state().setBits(newIsInvalidAnswers, INVALID_ANSWERS_BIT); } return this; } public ItemState get() { if (itemState == null) { return ItemState.this; } return itemState; } } public UpdateBuilder update() { return new UpdateBuilder(); } }
26.818333
204
0.677087
a32a8df08ec3e2ef23e5a4505679d91e37d187b9
1,717
package org.softuni.residentevil.utils; import org.softuni.residentevil.domain.entities.Role; import org.softuni.residentevil.repositories.RoleRepository; import org.softuni.residentevil.repositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashSet; import java.util.Set; @Component public class AuthSeeder { private final RoleRepository roleRepository; private final UserRepository userRepository; @Autowired public AuthSeeder(RoleRepository roleRepository, UserRepository userRepository) { this.roleRepository = roleRepository; this.userRepository = userRepository; } public void initialDbRolesSeed() { if(this.roleRepository.count() == 0) { Role admin = new Role(); admin.setAuthority("ROLE_ROOT"); Role moderator = new Role(); moderator.setAuthority("ROLE_ADMIN"); Role user = new Role(); user.setAuthority("ROLE_USER"); this.roleRepository.saveAndFlush(admin); this.roleRepository.saveAndFlush(moderator); this.roleRepository.saveAndFlush(user); } } public Set<Role> seedUserRoles() { Set<Role> roles = new HashSet<>(); if(this.userRepository.count() == 0) { roles.add(this.roleRepository.findByAuthority("ROLE_ROOT")); roles.add(this.roleRepository.findByAuthority("ROLE_ADMIN")); roles.add(this.roleRepository.findByAuthority("ROLE_USER")); } else { roles.add(this.roleRepository.findByAuthority("ROLE_USER")); } return roles; } }
31.796296
85
0.677927
0c9f9d55f0fdfb09d19c68166c9f2d43f4b0933d
416
package org.linuxlsx.algo.rete; /** * @author linuxlsx * @date 2019-04-26 */ public class EqualEvalNode implements EvalNode{ public String attr; public String value; public EqualEvalNode() { } public EqualEvalNode(String attr, String value) { this.attr = attr; this.value = value; } @Override public boolean eval(Factor factor) { return false; } }
16.64
53
0.625
eda42dcd495a15bfaf7c7dbd5ccff06a3444fe78
1,022
package com.github.wautsns.project.per1024.auth.business.service; import java.math.BigInteger; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.springframework.stereotype.Service; import com.github.wautsns.project.per1024.auth.business.repository.mapper.UserMn2nRoleMapper; import com.github.wautsns.project.per1024.auth.model.po.UserMn2nRolePO; import lombok.RequiredArgsConstructor; /** * * @author wautsns * @version 0.1.0 Oct 11, 2019 */ @Service @RequiredArgsConstructor public class RoleService { private static final List<Long> VISITOR = Collections.singletonList(1L); private final UserMn2nRoleMapper userMn2nRoleMapper; public List<Long> listIdsByUid(BigInteger uid) { if (uid == null) { return VISITOR; } List<UserMn2nRolePO> roles = userMn2nRoleMapper.select(new UserMn2nRolePO().setUid(uid)); return roles.stream() .map(UserMn2nRolePO::getRoleId) .collect(Collectors.toList()); } }
27.621622
97
0.746575
63f66c338e7348d7d8cbe3e6a2c565860c63582f
10,793
package me.dinnerbeef.compressium; import net.minecraft.block.*; import net.minecraft.util.ResourceLocation; import net.minecraftforge.registries.ForgeRegistries; import java.util.ArrayList; import java.util.List; import java.util.function.Function; /** * @author LatvianModder / DinnerBeef (Just Coped And Pasted Some Of This) */ public enum CompressiumType { TERRACOTTA("terracotta", new ResourceLocation("minecraft", "terracotta"), new ResourceLocation("minecraft", "block/terracotta"), new ResourceLocation("minecraft","block/terracotta"), Block::new), COBBLESTONE("cobblestone", new ResourceLocation("minecraft", "cobblestone"), new ResourceLocation("minecraft", "block/cobblestone"), new ResourceLocation("minecraft","block/cobblestone"), Block::new), STONE("stone", new ResourceLocation("minecraft", "stone"), new ResourceLocation("minecraft", "block/stone"), new ResourceLocation("minecraft","block/stone"), Block::new), SAND("sand", new ResourceLocation("minecraft", "sand"), new ResourceLocation("minecraft", "block/sand"), new ResourceLocation("minecraft","block/sand"), FallingDamageBlock::new), GRAVEL("gravel", new ResourceLocation("minecraft", "gravel"), new ResourceLocation("minecraft", "block/gravel"), new ResourceLocation("minecraft","block/gravel"), FallingDamageBlock::new), NETHERRACK("netherrack", new ResourceLocation("minecraft", "netherrack"), new ResourceLocation("minecraft", "block/netherrack"), new ResourceLocation("minecraft","block/netherrack"), NetherrackBlock::new), SNOW("snow", new ResourceLocation("minecraft", "snow"), new ResourceLocation("minecraft", "block/snow"), new ResourceLocation("minecraft","block/snow_block"), Block::new), SOULSAND("soulsand", new ResourceLocation("minecraft", "soul_sand"), new ResourceLocation("minecraft", "block/soul_sand"), new ResourceLocation("minecraft","block/soul_sand"), SoulSandBlock::new), IRON("iron", new ResourceLocation("minecraft", "iron_block"), new ResourceLocation("minecraft", "block/iron_block"), new ResourceLocation("minecraft","block/iron_block"), Block::new), GOLD("gold", new ResourceLocation("minecraft", "gold_block"), new ResourceLocation("minecraft", "block/gold_block"), new ResourceLocation("minecraft","block/gold_block"), Block::new), DIAMOND("diamond", new ResourceLocation("minecraft", "diamond_block"), new ResourceLocation("minecraft", "block/diamond_block"), new ResourceLocation("minecraft","block/diamond_block"), Block::new), EMERALD("emerald", new ResourceLocation("minecraft", "emerald_block"), new ResourceLocation("minecraft", "block/emerald_block"), new ResourceLocation("minecraft","block/emerald_block"), Block::new), CLAY("clay", new ResourceLocation("minecraft", "clay"), new ResourceLocation("minecraft", "block/clay"), new ResourceLocation("minecraft","block/clay"), Block::new), NETHERITE("netherite", new ResourceLocation("minecraft", "netherite_block"), new ResourceLocation("minecraft", "block/netherite_block"), new ResourceLocation("minecraft","block/netherite_block"), Block::new), DIRT("dirt", new ResourceLocation("minecraft", "dirt"), new ResourceLocation("minecraft", "block/dirt"), new ResourceLocation("minecraft","block/dirt"), Block::new), COAL("coal", new ResourceLocation("minecraft", "coal_block"), new ResourceLocation("minecraft", "block/coal_block"), new ResourceLocation("minecraft","block/coal_block"), Block::new), REDSAND("redsand", new ResourceLocation("minecraft", "red_sand"), new ResourceLocation("minecraft", "block/red_sand"), new ResourceLocation("minecraft","block/red_sand"), FallingDamageBlock::new), ENDSTONE("endstone", new ResourceLocation("minecraft", "end_stone"), new ResourceLocation("minecraft", "block/end_stone"), new ResourceLocation("minecraft","block/end_stone"), Block::new), OBSIDIAN("obsidian", new ResourceLocation("minecraft", "obsidian"), new ResourceLocation("minecraft", "block/obsidian"), new ResourceLocation("minecraft","block/obsidian"), Block::new), LAPIS("lapis", new ResourceLocation("minecraft", "lapis_block"), new ResourceLocation("minecraft", "block/lapis_block"), new ResourceLocation("minecraft","block/lapis_block"), Block::new), QUARTZ("quartz", new ResourceLocation("minecraft", "quartz_block"), new ResourceLocation("minecraft", "block/quartz_block_side"), new ResourceLocation("minecraft","block/quartz_block"), Block::new), HONEY("honey", new ResourceLocation("minecraft", "honey_block"), new ResourceLocation("minecraft", "block/honey_block_side"), new ResourceLocation("minecraft","block/honey_block"), HoneyBlock::new), REDSTONE("redstone", new ResourceLocation("minecraft", "redstone_block"), new ResourceLocation("minecraft", "block/redstone_block"), new ResourceLocation("minecraft","block/redstone_block"), RedstoneBlock::new), ANDESITE("andesite", new ResourceLocation("minecraft", "andesite"), new ResourceLocation("minecraft", "block/andesite"), new ResourceLocation("minecraft","block/andesite"), Block::new), DIORITE("diorite", new ResourceLocation("minecraft", "diorite"), new ResourceLocation("minecraft", "block/diorite"), new ResourceLocation("minecraft","block/diorite"), Block::new), GRANITE("granite", new ResourceLocation("minecraft", "granite"), new ResourceLocation("minecraft", "block/granite"), new ResourceLocation("minecraft","block/granite"), Block::new), BASALT("basalt", new ResourceLocation("minecraft", "basalt"), new ResourceLocation("minecraft", "block/basalt_side"), new ResourceLocation("minecraft","block/basalt"), Block::new), BLACKSTONE("blackstone", new ResourceLocation("minecraft", "blackstone"), new ResourceLocation("minecraft", "block/blackstone"), new ResourceLocation("minecraft","block/blackstone"), Block::new), MAGMABLOCK("magmablock", new ResourceLocation("minecraft", "magma_block"), new ResourceLocation("minecraft", "block/magma"), new ResourceLocation("minecraft","block/magma_block"), MagmaBlock::new), NETHERBRICKS("netherbricks", new ResourceLocation("minecraft", "nether_bricks"), new ResourceLocation("minecraft", "block/nether_bricks"), new ResourceLocation("minecraft","block/nether_bricks"), Block::new), SOULSOIL("soulsoil", new ResourceLocation("minecraft", "soul_soil"), new ResourceLocation("minecraft", "block/soul_soil"), new ResourceLocation("minecraft","block/soul_soil"), Block::new), BONEBLOCK("boneblock", new ResourceLocation("minecraft", "bone_block"), new ResourceLocation("minecraft", "block/bone_block_side"), new ResourceLocation("minecraft","block/bone_block"), Block::new), CRYINGOBSIDIAN("cryingobsidian", new ResourceLocation("minecraft", "crying_obsidian"), new ResourceLocation("minecraft", "block/crying_obsidian"), new ResourceLocation("minecraft","block/crying_obsidian"), Block::new), KELPBLOCK("kelpblock", new ResourceLocation("minecraft", "dried_kelp_block"), new ResourceLocation("minecraft", "block/dried_kelp_side"), new ResourceLocation("minecraft","block/dried_kelp_block"), Block::new), GLASS("glass", new ResourceLocation("minecraft", "glass"), new ResourceLocation("minecraft", "block/glass"), new ResourceLocation("minecraft","block/glass"), Block::new), PRISMARINE("prismarine", new ResourceLocation("minecraft", "prismarine"), new ResourceLocation("minecraft", "block/prismarine"), new ResourceLocation("minecraft","block/prismarine"), Block::new), PRISMARINEBRICKS("prismarinebricks", new ResourceLocation("minecraft", "prismarine_bricks"), new ResourceLocation("minecraft", "block/prismarine_bricks"), new ResourceLocation("minecraft","block/prismarine_bricks"), Block::new), DARKPRISMARINE("darkprismarine", new ResourceLocation("minecraft", "dark_prismarine"), new ResourceLocation("minecraft", "block/dark_prismarine"), new ResourceLocation("minecraft","block/dark_prismarine"), Block::new); public static final CompressiumType[] VALUES = values(); public final String name; public final ResourceLocation baseResourceLocation; public final List<Block> blocks; public final ResourceLocation particlePath; public final ResourceLocation baseBlockModel; private final Function<AbstractBlock.Properties, Block> constructor; CompressiumType(String n, ResourceLocation baseResourceLocation, ResourceLocation particlePath, ResourceLocation baseBlockModel, Function<AbstractBlock.Properties, Block> constructor) { this.name = n; this.blocks = new ArrayList<>(); this.particlePath = particlePath; this.baseBlockModel = baseBlockModel; this.baseResourceLocation = baseResourceLocation; this.constructor = constructor; } public Block getBaseBlock() { return ForgeRegistries.BLOCKS.getValue(baseResourceLocation); } public Block getBlock() { return constructor.apply(AbstractBlock.Properties.copy(ForgeRegistries.BLOCKS.getValue(baseResourceLocation))); } }
46.321888
119
0.625776
6569e88dca87cea8a2a2cf1fd4c51218901f24a7
3,190
/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * 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.sweble.wikitext.parser; import de.fau.cs.osr.ptk.common.Warning; import de.fau.cs.osr.ptk.common.ast.Span; public abstract class WikitextWarning extends Warning { private static final long serialVersionUID = 1L; protected final WarningSeverity severity; // ========================================================================= public WikitextWarning( Span span, WarningSeverity severity, String origin, String message) { super(span, origin, message); this.severity = severity; } public WikitextWarning( Span span, WarningSeverity severity, Class<?> origin, String message) { super(span, origin, message); this.severity = severity; } // ========================================================================= public WarningSeverity getSeverity() { return severity; } // ========================================================================= @Override public String toString() { String span = spanToString(); String message = messageToString(); String severity = severityToString(); return "Warning (" + severity + "): " + span + " : " + message; } protected String severityToString() { String severity = "-"; if (getSeverity() != null) severity = getSeverity().toString().toLowerCase(); return severity; } // ========================================================================= @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((severity == null) ? 0 : severity.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; WikitextWarning other = (WikitextWarning) obj; if (severity != other.severity) return false; return true; } // ========================================================================= public static enum WarningSeverity { /** Really not a problem. */ NONE { @Override public int getLevel() { return 0; } }, /** Might be worth looking into. */ INFORMATIVE { @Override public int getLevel() { return 5; } }, /** Should be taken care of. */ NORMAL { @Override public int getLevel() { return 10; } }, /** That's really bad. */ FATAL { @Override public int getLevel() { return 100; } }; public abstract int getLevel(); } }
20.986842
77
0.577116
ede279590a5fa68c6052d2f3f2d55dc2cbb9e948
4,312
/* * #%L * Hootsuite Integration * %% * Copyright 2020 Adobe. All rights reserved. * %% * This file is licensed 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. * #L% */ package com.adobe.core.hootsuite.integration.external.services.beans; 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; /** * * A simple POJO for marshalling/unmarshalling Access/Refresh Token Response<br/> * from Hootsuite. * * @version 1.0 * @since 2020.04.15 * * ****************************************************************************** * Version History * ****************************************************************************** * * 1.0 Initial Version * * ******************************************************************************* */ @JsonInclude(JsonInclude.Include.NON_NULL) public class AuthTokenResponse { /** The access token. */ @JsonProperty("access_token") private String accessToken; /** The expires in. */ @JsonProperty("expires_in") private Integer expiresIn; /** The refresh token. */ @JsonProperty("refresh_token") private String refreshToken; /** The scope. */ @JsonProperty("scope") private String scope; /** The token type. */ @JsonProperty("token_type") private String tokenType; /** The additional properties. */ @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * Gets the access token. * * @return the access token */ @JsonProperty("access_token") public String getAccessToken() { return accessToken; } /** * Sets the access token. * * @param accessToken the new access token */ @JsonProperty("access_token") public void setAccessToken(String accessToken) { this.accessToken = accessToken; } /** * Gets the expires in. * * @return the expires in */ @JsonProperty("expires_in") public Integer getExpiresIn() { return expiresIn; } /** * Sets the expires in. * * @param expiresIn the new expires in */ @JsonProperty("expires_in") public void setExpiresIn(Integer expiresIn) { this.expiresIn = expiresIn; } /** * Gets the refresh token. * * @return the refresh token */ @JsonProperty("refresh_token") public String getRefreshToken() { return refreshToken; } /** * Sets the refresh token. * * @param refreshToken the new refresh token */ @JsonProperty("refresh_token") public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } /** * Gets the scope. * * @return the scope */ @JsonProperty("scope") public String getScope() { return scope; } /** * Sets the scope. * * @param scope the new scope */ @JsonProperty("scope") public void setScope(String scope) { this.scope = scope; } /** * Gets the token type. * * @return the token type */ @JsonProperty("token_type") public String getTokenType() { return tokenType; } /** * Sets the token type. * * @param tokenType the new token type */ @JsonProperty("token_type") public void setTokenType(String tokenType) { this.tokenType = tokenType; } /** * Gets the additional properties. * * @return the additional properties */ @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } /** * Sets the additional property. * * @param name the name * @param value the value */ @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
22.112821
89
0.653293
a8eff415a1413175a7ed51261ade226eec939ba4
3,476
package nyla.solutions.core.patterns.observer; import nyla.solutions.core.exception.RequiredException; import nyla.solutions.core.security.user.data.UserProfile; import nyla.solutions.core.util.Text; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; class TopicTest { private String topicName = "topicName"; private Topic<UserProfile> subject; private SubjectObserver observer; private UserProfile userProfile; private String id; @BeforeEach void setUp() { id = Text.generateId(); userProfile = new UserProfile(); userProfile.setId(id); subject = new Topic(topicName); observer = mock(SubjectTimerObserver.class); when(observer.getId()).thenReturn(id); } @Test void add() { subject.add(observer); subject.notify(userProfile); verify(observer).update(topicName,userProfile); } @Test void add_when_observer_null_Then_ThrowsRequiredException() { assertThrows(RequiredException.class, ()-> subject.add(null)); } @Test void add_when_observer_id_isEmpty_Then_ThrowsRequiredException() { when(observer.getId()).thenReturn(null); assertThrows(IllegalArgumentException.class, ()-> subject.add(observer)); when(observer.getId()).thenReturn(""); assertThrows(IllegalArgumentException.class, ()-> subject.add(observer)); when(observer.getId()).thenReturn(id); subject.add(observer); } @Test void remove_null_does_Not() { subject.add(observer); subject.remove(null); assertEquals(1,subject.getObserverMap().size()); } @Test void remove() { subject.add(observer); subject.notify(userProfile); verify(observer,atMostOnce()).update(topicName,userProfile); subject.remove(observer); subject.notify(userProfile); verify(observer,atMostOnce()).update(topicName,userProfile); } @Test void getName() { assertEquals(topicName,subject.getName()); } @Test void compareTo() { assertTrue(new Topic("A").compareTo(new Topic("B")) < 0); assertTrue(new Topic("B").compareTo(new Topic("A")) > 0); assertTrue(new Topic("C").compareTo(new Topic("C")) == 0); } @Test void copy() { Topic<UserProfile> copy = new Topic<UserProfile>(topicName); copy.copy(subject); assertEquals(subject.getName(),copy.getName()); assertEquals(subject.getObserverMap(),copy.getObserverMap()); } @Test void testHashCode() { Topic other = new Topic(subject.getName()); assertEquals(subject.hashCode(),other.hashCode()); subject.add(observer); assertNotEquals(subject.hashCode(),other.hashCode()); other.add(observer); assertEquals(subject.hashCode(),other.hashCode()); } @Test void testEquals() { Topic other = new Topic(subject.getName()); assertTrue(subject.equals(other)); subject.add(observer); assertFalse(subject.equals(other)); other.add(observer); assertTrue(subject.equals(other)); } @Test void testToString() { String text = subject.toString(); assertTrue(text.contains(topicName)); } }
24.307692
82
0.634638
1e314cde30698eb9851b31d9f63368664fd04aa2
120,161
package com.lilithsthrone.game.sex.sexActions.baseActions; import com.lilithsthrone.game.character.GameCharacter; import com.lilithsthrone.game.character.attributes.CorruptionLevel; import com.lilithsthrone.game.character.body.valueEnums.BreastShape; import com.lilithsthrone.game.character.body.valueEnums.CupSize; import com.lilithsthrone.game.dialogue.utils.UtilText; import com.lilithsthrone.game.sex.ArousalIncrease; import com.lilithsthrone.game.sex.SexAreaOrifice; import com.lilithsthrone.game.sex.SexAreaPenetration; import com.lilithsthrone.game.sex.SexPace; import com.lilithsthrone.game.sex.SexParticipantType; import com.lilithsthrone.game.sex.sexActions.SexAction; import com.lilithsthrone.game.sex.sexActions.SexActionType; import com.lilithsthrone.main.Main; import com.lilithsthrone.utils.Util; import com.lilithsthrone.utils.Util.Value; /** * @since 0.3.1 * @version 0.3.1 * @author Innoxia */ public class PenisBreastsCrotch { private static String getPaizuriTitle(GameCharacter character) { if(character.isBreastCrotchFuckablePaizuri()) { if(character.getBreastCrotchShape()==BreastShape.UDDERS) { return "udder-paizuri"; } else { return "crotch-boob-paizuri"; } } else { if(character.getBreastCrotchShape()==BreastShape.UDDERS) { return "udder-naizuri"; } else { return "crotch-boob-naizuri"; } } } public static final SexAction FUCKING_START = new SexAction( SexActionType.START_ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.ONE_VANILLA, Util.newHashMapOfValues(new Value<>(SexAreaPenetration.PENIS, SexAreaOrifice.BREAST_CROTCH)), SexParticipantType.NORMAL) { @Override public boolean isBaseRequirementsMet() { return Main.sex.getCharacterTargetedForSexAction(this).hasBreastsCrotch(); } @Override public String getActionTitle() { return "Start "+getPaizuriTitle(Main.sex.getCharacterTargetedForSexAction(this)); } @Override public String getActionDescription() { if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { return "Slide your [npc.cock+] between [npc2.namePos] [npc2.crotchBoobs+] and start fucking them."; } else { return "Start grinding your [npc.cock+] over [npc2.namePos] stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to take hold of [npc2.namePos] [npc2.crotchBoobs+], [npc.name] gently [npc.verb(push)] them together," + " lining [npc.her] [npc.cock] up to [npc2.her] cleavage before sliding forwards and starting to fuck [npc2.her] [npc2.crotchBoobs].")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to greedily [npc.verb(sink)] [npc.her] [npc.fingers] into [npc2.namePos] [npc2.crotchBoobs+], [npc.name] eagerly [npc.verb(push)] them together," + " lining [npc.her] [npc.cock] up to [npc2.her] cleavage before sliding forwards and starting to enthusiastically fuck [npc2.her] [npc2.crotchBoobs].")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to roughly [npc.verb(sink)] [npc.her] [npc.fingers] into [npc2.namePos] [npc2.crotchBoobs+], [npc.name] forcefully [npc.verb(push)] them together," + " lining [npc.her] [npc.cock] up to [npc2.her] cleavage before slamming forwards and starting to rapidly fuck [npc2.her] [npc2.crotchBoobs].")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to take hold of [npc2.namePos] [npc2.crotchBoobs+], [npc.name] then [npc.verb(push)] them together," + " lining [npc.her] [npc.cock] up to [npc2.her] cleavage before sliding forwards and starting to fuck [npc2.her] [npc2.crotchBoobs].")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to greedily [npc.verb(sink)] [npc.her] [npc.fingers] into [npc2.namePos] [npc2.crotchBoobs+], [npc.name] eagerly [npc.verb(push)] them together," + " lining [npc.her] [npc.cock] up to [npc2.her] cleavage before sliding forwards and starting to enthusiastically fuck [npc2.her] [npc2.crotchBoobs].")); break; default: break; } switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out a happy little [npc2.moan] in response," + " reaching up to help push [npc2.her] [npc2.crotchBoobs] together as [npc2.she] [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response," + " quickly reaching up to help push [npc2.her] [npc2.crotchBoobs] together as [npc2.she] happily [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response," + " reaching up to forcefully press [npc2.her] [npc2.crotchBoobs] together as [npc2.she] dominantly [npc2.verb(order)] [npc.herHim] to keep going.")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response," + " quickly reaching up to help push [npc2.her] [npc2.crotchBoobs] together as [npc2.she] happily [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out a little [npc2.moan] in response," + " before reaching up to help push [npc2.her] [npc2.crotchBoobs] together as [npc2.she] [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response," + " reaching up to weakly try and push [npc.herHim] away from [npc2.her] [npc2.crotchBoobs] as [npc2.she] [npc2.verb(beg)] for [npc.herHim] to stop.")); break; default: break; } } else if(Main.sex.getCharacterTargetedForSexAction(this).getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to take hold of [npc2.namePos] [npc2.crotchBoobs+], [npc.name] gently [npc.verb(try)] to push them together," + " lining [npc.her] [npc.cock] up to what little cleavage [npc2.she] [npc2.has] before sliding forwards and starting to grind down over [npc2.her] lower abdomen.")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to squeeze and grope [npc2.namePos] [npc2.crotchBoobs+], [npc.name] [npc.do] [npc.her] best to try to push them together," + " lining [npc.her] [npc.cock] up to what little cleavage [npc2.she] [npc2.has] before sliding forwards and starting to eagerly grind down over [npc2.her] lower abdomen.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to roughly squeeze and grope [npc2.namePos] [npc2.crotchBoobs+], [npc.name] [npc.do] [npc.her] best to try to push them together," + " lining [npc.her] [npc.cock] up to what little cleavage [npc2.she] [npc2.has] before sliding forwards and starting to forcefully grind down over [npc2.her] lower abdomen.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to squeeze and grope [npc2.namePos] [npc2.crotchBoobs+], [npc.name] [npc.do] [npc.her] best to try to push them together," + " lining [npc.her] [npc.cock] up to what little cleavage [npc2.she] [npc2.has] before sliding forwards and starting to grind down over [npc2.her] lower abdomen.")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to squeeze and grope [npc2.namePos] [npc2.crotchBoobs+], [npc.name] [npc.do] [npc.her] best to try to push them together," + " lining [npc.her] [npc.cock] up to what little cleavage [npc2.she] [npc2.has] before sliding forwards and starting to eagerly grind down over [npc2.her] lower abdomen.")); break; default: break; } switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out a happy little [npc2.moan] in response, reaching up to try and help push [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together" + " as [npc2.she] [npc2.verb(encourage)] [npc.name] to fuck [npc2.her] breasts.")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, quickly reaching up to try and help push [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together" + " as [npc2.she] happily [npc2.verb(encourage)] [npc.herHim] to fuck [npc2.her] breasts.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, reaching up to forcefully try and [npc.verb(press)] [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together" + " as [npc2.she] dominantly [npc2.verb(order)] [npc.herHim] to fuck [npc2.her] breasts.")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, quickly reaching up to try and help push [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together" + " as [npc2.she] happily [npc2.verb(encourage)] [npc.herHim] to fuck [npc2.her] breasts.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out a little [npc2.moan] in response, before reaching up to try and help push [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together" + " as [npc2.she] [npc2.verb(encourage)] [npc.herHim] to fuck [npc2.her] breasts.")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response," + " reaching up to weakly try and push [npc.herHim] away from [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] as [npc2.she] [npc2.verb(beg)] for [npc.herHim] to stop.")); break; default: break; } } else { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to press [npc.her] [npc.hands] against [npc2.namePos] torso, [npc.name] repositions [npc.herself] to line [npc.her] [npc.cock] up over [npc2.her] lower abdomen," + " before sliding forwards and starting to grind down against [npc2.her] body.")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to press [npc.her] [npc.hands] against [npc2.namePos] torso, [npc.name] repositions [npc.herself] to line [npc.her] [npc.cock] up over [npc2.her] lower abdomen," + " before sliding forwards and starting to eagerly grind down against [npc2.her] body.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to roughly [npc.verb(press)] [npc.her] [npc.hands] against [npc2.namePos] torso, [npc.name] repositions [npc.herself] to line [npc.her] [npc.cock] up over [npc2.her] lower abdomen," + " before sliding forwards and starting to forcefully grind down against [npc2.her] body.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to press [npc.her] [npc.hands] against [npc2.namePos] torso, [npc.name] repositions [npc.herself] to line [npc.her] [npc.cock] up over [npc2.her] lower abdomen," + " before sliding forwards and starting to grind down against [npc2.her] body.")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching down to press [npc.her] [npc.hands] against [npc2.namePos] torso, [npc.name] repositions [npc.herself] to line [npc.her] [npc.cock] up over [npc2.her] lower abdomen," + " before sliding forwards and starting to eagerly grind down against [npc2.her] body.")); break; default: break; } switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out a happy little [npc2.moan] in response, pushing [npc2.her] stomach out as [npc2.she] [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, quickly pushing [npc2.her] stomach out as [npc2.she] happily [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, forcefully pushing [npc2.her] stomach out as [npc2.she] dominantly [npc2.verb(order)] [npc.herHim] to keep going.")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, pushing [npc2.her] stomach out as [npc2.she] happily [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out a little [npc2.moan] in response, pushing [npc2.her] stomach out as [npc2.she] [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response," + " reaching up to weakly try and [npc2.verb(push)] [npc.name] away from [npc2.herHim] as [npc2.she] [npc2.verb(beg)] to be left alone.")); break; default: break; } } return UtilText.nodeContentSB.toString(); } }; private static String getTargetedCharacterResponse(SexAction action) { if(Main.sex.getCharacterTargetedForSexAction(action).isBreastCrotchFuckablePaizuri()) { switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(action))) { case SUB_EAGER: case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] eagerly [npc2.verb(push)] [npc2.her] [npc2.crotchBoobs+] together in response," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(encourage)] [npc.name] to continue fucking [npc2.her] cleavage.", " [npc2.A_moan+] bursts out from between [npc2.namePos] [npc2.lips+]," + " and, eagerly pushing [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together," + " [npc2.she] [npc2.verb(encourage)] [npc.name] to continue sliding [npc.her] [npc.cock+] up and down between [npc2.her] cleavage.", " [npc2.Moaning] in delight, [npc2.name] eagerly [npc2.verb(wrap)] [npc2.her] [npc2.crotchBoobs+] around [npc.namePos] [npc.cock+]," + " before begging for [npc.herHim] to continue fucking [npc2.her] pillowy mounds.")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " Desperately trying, and failing, to pull away from [npc.namePos] [npc.cock]," + " [npc2.name] [npc2.verb(let)] out [npc2.a_sob+], tears streaming down [npc2.her] [npc2.face] as [npc2.she] weakly [npc2.verb(beg)] for [npc.name] to leave [npc2.her] [npc2.crotchBoobs] alone.", " [npc2.A_sob+] bursts out from between [npc2.namePos] [npc2.lips] as [npc2.she] weakly [npc2.verb(try)] to push [npc.name] away," + " tears streaming down [npc2.her] [npc2.face] as [npc2.she] [npc2.verb(plead)] for [npc.herHim] to leave [npc2.her] [npc2.crotchBoobs] alone.", " [npc2.Sobbing] in distress, and with tears running down [npc2.her] [npc2.face]," + " [npc2.name] weakly [npc2.verb(struggle)] against [npc.name], pleading and crying for [npc.herHim] to get away from [npc2.her] [npc2.crotchBoobs].")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(push)] [npc2.her] [npc2.crotchBoobs+] together in response," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(encourage)] [npc.name] to continue fucking [npc2.her] cleavage.", " [npc2.A_moan+] bursts out from between [npc2.namePos] [npc2.lips+]," + " and, pushing [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together," + " [npc2.she] [npc2.verb(encourage)] [npc.name] to continue sliding [npc.her] [npc.cock+] up and down between [npc2.her] cleavage.", " [npc2.Moaning] in delight, [npc2.name] [npc2.verb(wrap)] [npc2.her] [npc2.crotchBoobs+] around [npc.namePos] [npc.cock+]," + " before begging for [npc.herHim] to continue fucking [npc2.her] pillowy mounds.")); break; case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] gently [npc2.verb(push)] [npc2.her] [npc2.crotchBoobs+] together in response," + " letting out a soft [npc2.moan] as [npc2.she] [npc2.verb(encourage)] [npc.name] to continue fucking [npc2.her] cleavage.", " A soft [npc2.moan] drifts out from between [npc2.namePos] [npc2.lips+]," + " and, gently pushing [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together," + " [npc2.she] [npc2.verb(encourage)] [npc.name] to continue sliding [npc.her] [npc.cock+] up and down between [npc2.her] cleavage.", " [npc2.Moaning] in delight, [npc2.name] gently [npc2.verb(wrap)] [npc2.her] [npc2.crotchBoobs+] around [npc.namePos] [npc.cock+]," + " before begging for [npc.herHim] to continue fucking [npc2.her] pillowy mounds.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] roughly [npc2.verb(press)] [npc2.her] [npc2.crotchBoobs+] together in response," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(order)] [npc.name] to continue fucking [npc2.her] cleavage.", " [npc2.A_moan+] bursts out from between [npc2.namePos] [npc2.lips+]," + " and, forcefully pressing [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together," + " [npc2.she] [npc2.verb(order)] [npc.name] to continue thrusting [npc.her] [npc.cock+] up and down between [npc2.her] cleavage.", " [npc2.Moaning] in delight, [npc2.name] dominantly [npc2.verb(wrap)] [npc2.her] [npc2.crotchBoobs+] around [npc.namePos] [npc.cock+]," + " before ordering [npc.herHim] to continue fucking [npc2.her] pillowy mounds.")); break; } } else if(Main.sex.getCharacterTargetedForSexAction(action).getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(action))) { case SUB_EAGER: case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] eagerly [npc2.verb(attempt)] to push [npc2.her] tiny [npc2.crotchBoobs] together in response," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(encourage)] [npc.name] to continue fucking what little cleavage [npc2.she] [npc2.has].", " [npc2.A_moan+] bursts out from between [npc2.namePos] [npc2.lips+]," + " and, eagerly attempting to push [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together," + " [npc2.she] [npc2.verb(encourage)] [npc.name] to continue sliding [npc.her] [npc.cock+] up and down between [npc2.her] tiny cleavage.", " [npc2.Moaning] in delight, [npc2.name] eagerly [npc2.verb(push)] [npc2.her] [npc2.crotchBoobs+] against the sides of [npc.namePos] [npc.cock+]," + " before begging for [npc.herHim] to continue fucking [npc2.her] diminutive cleavage.")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " Desperately trying, and failing, to pull away from [npc.namePos] [npc.cock]," + " [npc2.name] [npc2.verb(let)] out [npc2.a_sob+], tears streaming down [npc2.her] [npc2.face] as [npc2.she] weakly [npc2.verb(beg)] for [npc.name] to leave [npc2.her] [npc2.crotchBoobs] alone.", " [npc2.A_sob+] bursts out from between [npc2.namePos] [npc2.lips] as [npc2.she] weakly [npc2.verb(try)] to push [npc.name] away," + " tears streaming down [npc2.her] [npc2.face] as [npc2.she] [npc2.verb(plead)] for [npc.herHim] to leave [npc2.her] [npc2.crotchBoobs] alone.", " [npc2.Sobbing] in distress, and with tears running down [npc2.her] [npc2.face]," + " [npc2.name] weakly [npc2.verb(struggle)] against [npc.name], pleading and crying for [npc.herHim] to get away from [npc2.her] [npc2.crotchBoobs].")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(attempt)] to push [npc2.her] [npc2.crotchBoobs+] together in response," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(encourage)] [npc.name] to continue fucking what little cleavage [npc2.she] [npc2.has].", " [npc2.A_moan+] bursts out from between [npc2.namePos] [npc2.lips+]," + " and, pushing [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together," + " [npc2.she] [npc2.verb(encourage)] [npc.name] to continue sliding [npc.her] [npc.cock+] up and down between [npc2.her] tiny cleavage.", " [npc2.Moaning] in delight, [npc2.name] [npc2.verb(push)] [npc2.her] [npc2.crotchBoobs+] against the sides of [npc.namePos] [npc.cock+]," + " before begging for [npc.herHim] to continue fucking [npc2.her] diminutive cleavage.")); break; case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(attempt)] to gently push [npc2.her] [npc2.crotchBoobs+] together in response," + " letting out a soft [npc2.moan] as [npc2.she] [npc2.verb(encourage)] [npc.name] to continue fucking what little cleavage [npc2.she] [npc2.has].", " A soft [npc2.moan] drifts out from between [npc2.namePos] [npc2.lips+]," + " and, gently pushing [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together," + " [npc2.she] [npc2.verb(encourage)] [npc.name] to continue sliding [npc.her] [npc.cock+] up and down between [npc2.her] tiny cleavage.", " [npc2.Moaning] in delight, [npc2.name] gently [npc2.verb(push)] [npc2.her] [npc2.crotchBoobs+] against the sides of [npc.namePos] [npc.cock+]," + " before begging for [npc.herHim] to continue fucking [npc2.her] diminutive cleavage.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(attempt)] to roughly push [npc2.verb(press)] [npc2.her] [npc2.crotchBoobs+] together in response," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(order)] [npc.name] to continue fucking what little cleavage [npc2.she] [npc2.has].", " [npc2.A_moan+] bursts out from between [npc2.namePos] [npc2.lips+]," + " and, forcefully pressing [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs] together," + " [npc2.she] [npc2.verb(order)] [npc.name] to continue thrusting [npc.her] [npc.cock+] up and down between [npc2.her] tiny cleavage.", " [npc2.Moaning] in delight, [npc2.name] dominantly [npc2.verb(press)] [npc2.her] [npc2.crotchBoobs+] against the sides of [npc.namePos] [npc.cock+]," + " before ordering [npc.herHim] to continue fucking [npc2.her] diminutive cleavage.")); break; } } else { switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(action))) { case SUB_EAGER: case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] eagerly [npc2.verb(push)] [npc2.her] flat stomach out in response," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(encourage)] [npc.name] to continue humping [npc2.her] torso.", " [npc2.A_moan+] bursts out from between [npc2.namePos] [npc2.lips+]," + " and, eagerly pushing [npc2.her] flat stomach out," + " [npc2.she] [npc2.verb(encourage)] [npc.name] to continue sliding [npc.her] [npc.cock+] up and down over [npc2.her] torso.", " [npc2.Moaning] in delight, [npc2.name] eagerly [npc2.does] [npc2.her] best to try and [npc2.verb(wrap)] [npc2.her] flat stomach around [npc.namePos] [npc.cock+]," + " before giving up and begging for [npc.herHim] to continue humping [npc2.her] torso.")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " Desperately trying, and failing, to pull away from [npc.namePos] [npc.cock]," + " [npc2.name] [npc2.verb(let)] out [npc2.a_sob+], tears streaming down [npc2.her] [npc2.face] as [npc2.she] weakly [npc2.verb(beg)] for [npc.name] to leave [npc2.her] [npc2.crotchBoobs] alone.", " [npc2.A_sob+] bursts out from between [npc2.namePos] [npc2.lips] as [npc2.she] weakly [npc2.verb(try)] to push [npc.name] away," + " tears streaming down [npc2.her] [npc2.face] as [npc2.she] [npc2.verb(plead)] for [npc.herHim] to leave [npc2.her] [npc2.crotchBoobs] alone.", " [npc2.Sobbing] in distress, and with tears running down [npc2.her] [npc2.face]," + " [npc2.name] weakly [npc2.verb(struggle)] against [npc.name], pleading and crying for [npc.herHim] to get away from [npc2.her] [npc2.crotchBoobs].")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(push)] [npc2.her] flat stomach out in response," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(encourage)] [npc.name] to continue humping [npc2.her] torso.", " [npc2.A_moan+] bursts out from between [npc2.namePos] [npc2.lips+]," + " and, pushing [npc2.her] flat stomach out," + " [npc2.she] [npc2.verb(encourage)] [npc.name] to continue sliding [npc.her] [npc.cock+] up and down over [npc2.her] torso.", " [npc2.Moaning] in delight, [npc2.name] [npc2.does] [npc2.her] best to try and [npc2.verb(wrap)] [npc2.her] flat stomach around [npc.namePos] [npc.cock+]," + " before giving up and begging for [npc.herHim] to continue humping [npc2.her] torso.")); break; case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] gently [npc2.verb(push)] [npc2.her] flat stomach out in response," + " letting out a soft [npc2.moan] as [npc2.she] [npc2.verb(encourage)] [npc.name] to continue humping [npc2.her] torso.", " A soft [npc2.moan] drifts out from between [npc2.namePos] [npc2.lips+]," + " and, gently pushing [npc2.her] flat stomach out," + " [npc2.she] [npc2.verb(encourage)] [npc.name] to continue sliding [npc.her] [npc.cock+] up and down over [npc2.her] torso.", " [npc2.Moaning] in delight, [npc2.name] [npc2.does] [npc2.her] best to try and gently [npc2.verb(wrap)] [npc2.her] flat stomach around [npc.namePos] [npc.cock+]," + " before giving up and begging for [npc.herHim] to just continue humping [npc2.her] torso.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] roughly [npc2.verb(thrust)] [npc2.her] flat stomach out in response," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(order)] [npc.name] to continue humping [npc2.her] torso.", " [npc2.A_moan+] bursts out from between [npc2.namePos] [npc2.lips+]," + " and, forcefully pushing [npc2.her] flat stomach out," + " [npc2.she] [npc2.verb(order)] [npc.name] to continue thrusting [npc.her] [npc.cock+] up and down over [npc2.her] torso.", " [npc2.Moaning] in delight, [npc2.name] [npc2.does] [npc2.her] best to try and roughly [npc2.verb(wrap)] [npc2.her] flat stomach around [npc.namePos] [npc.cock+]," + " before giving up and ordering [npc.herHim] to just continue humping [npc2.her] torso.")); break; } } return ""; } public static final SexAction FUCKING_DOM_GENTLE = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.ONE_VANILLA, Util.newHashMapOfValues(new Value<>(SexAreaPenetration.PENIS, SexAreaOrifice.BREAST_CROTCH)), SexParticipantType.NORMAL, SexPace.DOM_GENTLE) { @Override public String getActionTitle() { return "Gentle "+getPaizuriTitle(Main.sex.getCharacterTargetedForSexAction(this)); } @Override public String getActionDescription() { if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { return "Gently fuck [npc2.namePos] [npc2.crotchBoobs+]."; } else { return "Gently grind your [npc.cock+] against [npc2.namePos] flat stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Gently sliding [npc.her] [npc.cock+] between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] steadily bucking [npc.her] [npc.hips] back and forth, letting out a little [npc.moan] with every thrust as [npc.she] slowly [npc.verb(fuck)] [npc2.her] cleavage.", "Gently pushing [npc.her] [npc.cock+] between the cleavage formed between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] softly thrusting [npc.her] [npc.hips] forwards, letting out a little [npc.moan] as [npc.she] gently [npc.verb(fuck)] [npc2.her] [npc2.crotchBoobs].", "Softly pushing [npc2.namePos] [npc2.crotchBoobs+] together, [npc.name] [npc.verb(let)] out a little [npc.moan] as [npc.she] [npc.verb(start)] to gently pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] slowly [npc.verb(fuck)] [npc2.her] cleavage.")); } else if(Main.sex.getCharacterTargetedForSexAction(this).getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Gently sliding [npc.her] [npc.cock+] between [npc2.namePos] tiny [npc2.crotchBoobs]," + " [npc.name] [npc.verb(start)] steadily bucking [npc.her] [npc.hips] back and forth, letting out a little [npc.moan] with every thrust as [npc.she] slowly [npc.verb(fuck)] [npc2.her] diminutive cleavage.", "Gently pushing [npc.her] [npc.cock+] between the tiny amount of cleavage formed between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] softly thrusting [npc.her] [npc.hips] forwards, letting out a little [npc.moan] as [npc.she] gently [npc.verb(grind)] up and down over [npc2.her] lower abdomen.", "Softly trying to push [npc2.namePos] [npc2.crotchBoobSize] [npc2.crotchBoobs] together, [npc.name] [npc.verb(let)] out a little [npc.moan] as [npc.she] [npc.verb(start)] to gently pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] slowly [npc.verb(grind)] [npc.her] [npc.cock+] over [npc2.her] lower abdomen.")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Gently sliding [npc.her] [npc.cock+] over [npc2.namePos] flat lower abdomen," + " [npc.name] [npc.verb(start)] steadily bucking [npc.her] [npc.hips] back and forth, letting out a little [npc.moan] with every thrust as [npc.she] slowly [npc.verb(grind)] against [npc2.her] torso.", "Gently pushing [npc.her] [npc.cock+] down against [npc2.namePos] flat [npc2.crotchBoobs]," + " [npc.name] [npc.verb(start)] softly thrusting [npc.her] [npc.hips] forwards, letting out a little [npc.moan] as [npc.she] gently [npc.verb(grind)] up and down over [npc2.her] lower abdomen.", "Softly groping [npc2.namePos] flat lower abdomen, [npc.name] [npc.verb(let)] out a little [npc.moan] as [npc.she] [npc.verb(start)] to gently pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] slowly [npc.verb(grind)] [npc.her] [npc.cock+] over [npc2.her] torso.")); } UtilText.nodeContentSB.append(getTargetedCharacterResponse(this)); return UtilText.nodeContentSB.toString(); } }; public static final SexAction FUCKING_DOM_NORMAL = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.ONE_VANILLA, Util.newHashMapOfValues(new Value<>(SexAreaPenetration.PENIS, SexAreaOrifice.BREAST_CROTCH)), SexParticipantType.NORMAL, SexPace.DOM_NORMAL) { @Override public String getActionTitle() { return Util.capitaliseSentence(getPaizuriTitle(Main.sex.getCharacterTargetedForSexAction(this))); } @Override public String getActionDescription() { if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { return "Continue fucking [npc2.namePos] [npc2.crotchBoobs+]."; } else { return "Continue grinding against [npc2.namePos] stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly sliding [npc.her] [npc.cock+] between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] frantically bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] greedily [npc.verb(fuck)] [npc2.her] cleavage.", "Desperately pushing [npc.her] [npc.cock+] between the cleavage formed between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] energetically thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] happily [npc.verb(fuck)] [npc2.her] [npc2.crotchBoobs].", "Greedily pushing [npc2.namePos] [npc2.crotchBoobs+] together, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to frantically pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] eagerly [npc.verb(fuck)] [npc2.her] cleavage.")); } else if(Main.sex.getCharacterTargetedForSexAction(this).getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly sliding [npc.her] [npc.cock+] between [npc2.namePos] tiny [npc2.crotchBoobs]," + " [npc.name] [npc.verb(start)] frantically bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] greedily [npc.verb(fuck)] [npc2.her] diminutive cleavage.", "Desperately pushing [npc.her] [npc.cock+] between the tiny amount of cleavage formed between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] energetically thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] happily [npc.verb(grind)] up and down over [npc2.her] lower abdomen.", "Greedily trying to push [npc2.namePos] [npc2.crotchBoobSize] [npc2.crotchBoobs] together, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to frantically pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] eagerly [npc.verb(grind)] [npc.her] [npc.cock+] over [npc2.her] lower abdomen.")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly sliding [npc.her] [npc.cock+] over [npc2.namePos] flat lower abdomen," + " [npc.name] [npc.verb(start)] frantically bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] greedily [npc.verb(grind)] against [npc2.her] torso.", "Desperately pushing [npc.her] [npc.cock+] down against [npc2.namePos] flat [npc2.crotchBoobs]," + " [npc.name] [npc.verb(start)] energetically thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] happily [npc.verb(grind)] up and down over [npc2.her] lower abdomen.", "Greedily groping [npc2.namePos] flat lower abdomen, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to frantically pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] eagerly [npc.verb(grind)] [npc.her] [npc.cock+] over [npc2.her] torso.")); } UtilText.nodeContentSB.append(getTargetedCharacterResponse(this)); return UtilText.nodeContentSB.toString(); } }; public static final SexAction FUCKING_DOM_ROUGH = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.TWO_HORNY, Util.newHashMapOfValues(new Value<>(SexAreaPenetration.PENIS, SexAreaOrifice.BREAST_CROTCH)), SexParticipantType.NORMAL, SexPace.DOM_ROUGH) { @Override public String getActionTitle() { return "Rough "+getPaizuriTitle(Main.sex.getCharacterTargetedForSexAction(this)); } @Override public String getActionDescription() { if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { return "Roughly fuck [npc2.namePos] [npc2.crotchBoobs+]."; } else { return "Roughly grind your [npc.cock+] against [npc2.namePos] flat stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Roughly slamming [npc.her] [npc.cock+] between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] violently bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] forcefully [npc.verb(fuck)] [npc2.her] cleavage.", "Violently pushing [npc.her] [npc.cock+] between the cleavage formed between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] roughly thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] dominantly [npc.verb(fuck)] [npc2.her] [npc2.crotchBoobs].", "Greedily pushing [npc2.namePos] [npc2.crotchBoobs+] together, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to dominantly pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] roughly [npc.verb(fuck)] [npc2.her] cleavage.")); } else if(Main.sex.getCharacterTargetedForSexAction(this).getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Roughly slamming [npc.her] [npc.cock+] between [npc2.namePos] tiny [npc2.crotchBoobs]," + " [npc.name] [npc.verb(start)] violently bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] forcefully [npc.verb(fuck)] [npc2.her] diminutive cleavage.", "Violently pushing [npc.her] [npc.cock+] between the tiny amount of cleavage formed between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] roughly thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] dominantly [npc.verb(grind)] up and down over [npc2.her] lower abdomen.", "Greedily trying to push [npc2.namePos] [npc2.crotchBoobSize] [npc2.crotchBoobs] together, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to dominantly pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] roughly [npc.verb(grind)] [npc.her] [npc.cock+] over [npc2.her] lower abdomen.")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Roughly pushing [npc.her] [npc.cock+] over [npc2.namePos] flat lower abdomen," + " [npc.name] [npc.verb(start)] violently bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] forcefully [npc.verb(grind)] against [npc2.her] torso.", "Violently pushing [npc.her] [npc.cock+] down against [npc2.namePos] flat [npc2.crotchBoobs]," + " [npc.name] [npc.verb(start)] roughly thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] dominantly [npc.verb(grind)] up and down over [npc2.her] lower abdomen.", "Greedily groping [npc2.namePos] flat lower abdomen, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to dominantly pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] roughly [npc.verb(grind)] [npc.her] [npc.cock+] over [npc2.her] torso.")); } UtilText.nodeContentSB.append(getTargetedCharacterResponse(this)); return UtilText.nodeContentSB.toString(); } }; public static final SexAction FUCKING_SUB_NORMAL = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.ONE_VANILLA, Util.newHashMapOfValues(new Value<>(SexAreaPenetration.PENIS, SexAreaOrifice.BREAST_CROTCH)), SexParticipantType.NORMAL, SexPace.SUB_NORMAL) { @Override public String getActionTitle() { return Util.capitaliseSentence(getPaizuriTitle(Main.sex.getCharacterTargetedForSexAction(this))); } @Override public String getActionDescription() { if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { return "Continue fucking [npc2.namePos] [npc2.crotchBoobs+]."; } else { return "Continue grinding against [npc2.namePos] flat stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Sliding [npc.her] [npc.cock+] between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] [npc.verb(fuck)] [npc2.her] cleavage.", "Pushing [npc.her] [npc.cock+] between the cleavage formed between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] happily [npc.verb(fuck)] [npc2.her] [npc2.crotchBoobs].", "Pushing [npc2.namePos] [npc2.crotchBoobs+] together, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] [npc.verb(fuck)] [npc2.her] cleavage.")); } else if(Main.sex.getCharacterTargetedForSexAction(this).getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Sliding [npc.her] [npc.cock+] between [npc2.namePos] tiny [npc2.crotchBoobs]," + " [npc.name] [npc.verb(start)] bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] [npc.verb(fuck)] [npc2.her] diminutive cleavage.", "Pushing [npc.her] [npc.cock+] between the tiny amount of cleavage formed between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] happily [npc.verb(grind)] up and down over [npc2.her] lower abdomen.", "Trying to push [npc2.namePos] [npc2.crotchBoobSize] [npc2.crotchBoobs] together, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] [npc.verb(grind)] [npc.her] [npc.cock+] over [npc2.her] lower abdomen.")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Sliding [npc.her] [npc.cock+] over [npc2.namePos] flat lower abdomen," + " [npc.name] [npc.verb(start)] bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] [npc.verb(grind)] against [npc2.her] torso.", "Pushing [npc.her] [npc.cock+] down against [npc2.namePos] flat [npc2.crotchBoobs]," + " [npc.name] [npc.verb(start)] thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] happily [npc.verb(grind)] up and down over [npc2.her] lower abdomen.", "Groping [npc2.namePos] flat lower abdomen, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] [npc.verb(grind)] [npc.her] [npc.cock+] over [npc2.her] torso.")); } UtilText.nodeContentSB.append(getTargetedCharacterResponse(this)); return UtilText.nodeContentSB.toString(); } }; public static final SexAction FUCKING_SUB_EAGER = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.ONE_VANILLA, Util.newHashMapOfValues(new Value<>(SexAreaPenetration.PENIS, SexAreaOrifice.BREAST_CROTCH)), SexParticipantType.NORMAL, SexPace.SUB_EAGER) { @Override public String getActionTitle() { return "Eager "+getPaizuriTitle(Main.sex.getCharacterTargetedForSexAction(this)); } @Override public String getActionDescription() { if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { return "Eagerly fuck [npc2.namePos] [npc2.crotchBoobs+]."; } else { return "Eagerly grind against [npc2.namePos] flat stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly sliding [npc.her] [npc.cock+] between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] frantically bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] greedily [npc.verb(fuck)] [npc2.her] cleavage.", "Desperately pushing [npc.her] [npc.cock+] between the cleavage formed between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] energetically thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] happily [npc.verb(fuck)] [npc2.her] [npc2.crotchBoobs].", "Greedily pushing [npc2.namePos] [npc2.crotchBoobs+] together, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to frantically pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] eagerly [npc.verb(fuck)] [npc2.her] cleavage.")); } else if(Main.sex.getCharacterTargetedForSexAction(this).getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly sliding [npc.her] [npc.cock+] between [npc2.namePos] tiny [npc2.crotchBoobs]," + " [npc.name] [npc.verb(start)] frantically bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] greedily [npc.verb(fuck)] [npc2.her] diminutive cleavage.", "Desperately pushing [npc.her] [npc.cock+] between the tiny amount of cleavage formed between [npc2.namePos] [npc2.crotchBoobs+]," + " [npc.name] [npc.verb(start)] energetically thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] happily [npc.verb(grind)] up and down over [npc2.her] lower abdomen.", "Greedily trying to push [npc2.namePos] [npc2.crotchBoobSize] [npc2.crotchBoobs] together, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to frantically pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] eagerly [npc.verb(grind)] [npc.her] [npc.cock+] over [npc2.her] lower abdomen.")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly sliding [npc.her] [npc.cock+] over [npc2.namePos] flat lower abdomen," + " [npc.name] [npc.verb(start)] frantically bucking [npc.her] [npc.hips] back and forth, letting out [npc.a_moan+] with every thrust as [npc.she] greedily [npc.verb(grind)] against [npc2.her] torso.", "Desperately pushing [npc.her] [npc.cock+] down against [npc2.namePos] flat [npc2.crotchBoobs]," + " [npc.name] [npc.verb(start)] energetically thrusting [npc.her] [npc.hips] forwards, letting out [npc.moans+] as [npc.she] happily [npc.verb(grind)] up and down over [npc2.her] lower abdomen.", "Greedily groping [npc2.namePos] flat lower abdomen, [npc.name] [npc.verb(let)] out [npc.a_moan+] as [npc.she] [npc.verb(start)] to frantically pump [npc.her] [npc.hips] back and forth," + " breathing in [npc2.her] [npc2.scent] as [npc.she] eagerly [npc.verb(grind)] [npc.her] [npc.cock+] over [npc2.her] torso.")); } UtilText.nodeContentSB.append(getTargetedCharacterResponse(this)); return UtilText.nodeContentSB.toString(); } }; public static final SexAction FUCKING_SUB_RESIST = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.TWO_LOW, CorruptionLevel.ZERO_PURE, Util.newHashMapOfValues(new Value<>(SexAreaPenetration.PENIS, SexAreaOrifice.BREAST_CROTCH)), SexParticipantType.NORMAL, SexPace.SUB_RESISTING) { @Override public String getActionTitle() { return "Resist giving "+getPaizuriTitle(Main.sex.getCharacterTargetedForSexAction(this)); } @Override public String getActionDescription() { if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { return "Try to pull your [npc.cock] away from [npc2.namePos] [npc2.crotchBoobs+]."; } else { return "Try to pull your [npc.cock] away from [npc2.namePos] stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] desperately [npc.verb(try)] to pull [npc.her] [npc.cock+] out of [npc2.namePos] cleavage, but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " pressing [npc2.her] [npc2.crotchBoobs+] together while gently reminding [npc.herHim] that [npc2.she]'ll do whatever [npc2.she] [npc2.verb(want)].", "[npc.Name] frantically [npc.verb(try)] to pull away from [npc2.namePos] [npc2.crotchBoobs+], but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " softly [npc2.moaning] as [npc2.she] [npc2.verb(ignore)] [npc.her] desperate protests.", "Tears start to well up in [npc.namePos] [npc.eyes] as [npc.she] [npc.verb(try)] to pull out of [npc2.namePos] cleavage, but [npc2.her] grip is too strong," + " and [npc2.she] [npc2.verb(continue)] softly [npc2.moaning] as [npc2.she] firmly [npc2.verb(force)] [npc.her] [npc.cock+] between [npc2.her] [npc2.crotchBoobs+].")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] desperately [npc.verb(try)] to pull [npc.her] [npc.cock+] out of [npc2.namePos] cleavage, but [npc2.she] roughly [npc2.verb(hold)] [npc.herHim] in place," + " pressing [npc2.her] [npc2.crotchBoobs+] together while growling that [npc2.she]'ll use [npc.herHim] however [npc2.she] [npc2.verb(want)].", "[npc.Name] frantically [npc.verb(try)] to pull away from [npc2.namePos] [npc2.crotchBoobs+], but [npc2.she] roughly [npc2.verb(hold)] [npc.herHim] in place," + " [npc.moaning+] as [npc2.she] [npc2.verb(ignore)] [npc.her] futile protests.", "Tears start to well up in [npc.namePos] [npc.eyes] as [npc.she] [npc.verb(try)] to pull out of [npc2.namePos] cleavage, but [npc2.her] grip is too strong," + " and [npc2.she] [npc2.verb(continue)] [npc2.moaning+] as [npc2.she] roughly [npc2.verb(force)] [npc.her] [npc.cock+] between [npc2.her] [npc2.crotchBoobs+].")); break; default: // DOM_NORMAL and in case anything goes wrong: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] desperately [npc.verb(try)] to pull [npc.her] [npc.cock+] out of [npc2.namePos] cleavage, but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " pressing [npc2.her] [npc2.crotchBoobs+] together while [npc2.moaning] that [npc2.she]'ll do whatever [npc2.she] [npc2.verb(want)].", "[npc.Name] frantically [npc.verb(try)] to pull away from [npc2.namePos] [npc2.crotchBoobs+], but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " [npc2.moaning+] as [npc2.she] [npc2.verb(ignore)] [npc.her] futile protests.", "Tears start to well up in [npc.namePos] [npc.eyes] as [npc.she] [npc.verb(try)] to pull out of [npc2.namePos] cleavage, but [npc2.her] grip is too strong," + " and [npc2.she] [npc2.verb(continue)] [npc2.moaning+] as [npc2.she] eagerly [npc2.verb(force)] [npc.her] [npc.cock+] between [npc2.her] [npc2.crotchBoobs+].")); break; } } else if(Main.sex.getCharacterTargetedForSexAction(this).getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] desperately [npc.verb(try)] to pull [npc.her] [npc.cock+] out of the small amount of cleavage that [npc2.name] [npc2.has], but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " trying to press [npc2.her] [npc2.crotchBoobs+] together while gently reminding [npc.herHim] that [npc2.she]'ll do whatever [npc2.she] [npc2.verb(want)].", "[npc.Name] frantically [npc.verb(try)] to pull away from [npc2.namePos] [npc2.crotchBoobSize] [npc2.crotchBoobs], but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " softly [npc2.moaning] as [npc2.she] [npc2.verb(ignore)] [npc.her] desperate protests.", "Tears start to well up in [npc.namePos] [npc.eyes] as [npc.she] [npc.verb(try)] to pull out of the tiny amount of cleavage that [npc2.name] have on offer, but [npc2.her] grip is too strong," + " and [npc2.she] [npc2.verb(continue)] softly [npc2.moaning] as [npc2.she] firmly [npc2.verb(force)] [npc.her] [npc.cock+] between [npc2.her] [npc2.crotchBoobs+].")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] desperately [npc.verb(try)] to pull [npc.her] [npc.cock+] out of the small amount of cleavage that [npc2.name] [npc2.has], but [npc2.she] roughly [npc2.verb(hold)] [npc.herHim] in place," + " trying to press [npc2.her] [npc2.crotchBoobs+] together while growling that [npc2.she]'ll use [npc.herHim] however [npc2.she] [npc2.verb(want)].", "[npc.Name] frantically [npc.verb(try)] to pull away from [npc2.namePos] [npc2.crotchBoobSize] [npc2.crotchBoobs], but [npc2.she] roughly [npc2.verb(hold)] [npc.herHim] in place," + " [npc.moaning+] as [npc2.she] [npc2.verb(ignore)] [npc.her] futile protests.", "Tears start to well up in [npc.namePos] [npc.eyes] as [npc.she] [npc.verb(try)] to pull out of the tiny amount of cleavage that [npc2.name] have on offer, but [npc2.her] grip is too strong," + " and [npc2.she] [npc2.verb(continue)] [npc2.moaning+] as [npc2.she] roughly [npc2.verb(force)] [npc.her] [npc.cock+] between [npc2.her] [npc2.crotchBoobs+].")); break; default: // DOM_NORMAL and in case anything goes wrong: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] desperately [npc.verb(try)] to pull [npc.her] [npc.cock+] out of the small amount of cleavage that [npc2.name] [npc2.has], but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " trying to press [npc2.her] [npc2.crotchBoobs+] together while [npc2.moaning] that [npc2.she]'ll do whatever [npc2.she] [npc2.verb(want)].", "[npc.Name] frantically [npc.verb(try)] to pull away from [npc2.namePos] [npc2.crotchBoobSize] [npc2.crotchBoobs], but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " [npc.moaning+] as [npc2.she] [npc2.verb(ignore)] [npc.her] futile protests.", "Tears start to well up in [npc.namePos] [npc.eyes] as [npc.she] [npc.verb(try)] to pull out of the tiny amount of cleavage that [npc2.name] have on offer, but [npc2.her] grip is too strong," + " and [npc2.she] [npc2.verb(continue)] [npc2.moaning+] as [npc2.she] eagerly [npc2.verb(force)] [npc.her] [npc.cock+] between [npc2.her] [npc2.crotchBoobs+].")); break; } } else { switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] desperately [npc.verb(try)] to pull [npc.her] [npc.cock+] away from [npc2.namePos] flat lower abdomen, but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " grinding against [npc.herHim] as [npc2.she] gently [npc2.moanVerb] that [npc2.she]'ll do whatever [npc2.she] [npc2.verb(want)].", "[npc.Name] frantically [npc.verb(try)] to pull away from [npc2.namePos] lower abdomen, but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " softly [npc2.moaning] as [npc2.she] [npc2.verb(ignore)] [npc.her] desperate protests.", "Tears start to well up in [npc.namePos] [npc.eyes] as [npc.she] [npc.verb(try)] to pull away from [npc2.name], but [npc2.her] grip is too strong," + " and [npc2.she] [npc2.verb(continue)] softly [npc2.moaning] as [npc2.she] firmly [npc2.verb(force)] [npc.her] [npc.cock+] against [npc2.her] lower abdomen.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] desperately [npc.verb(try)] to pull [npc.her] [npc.cock+] away from [npc2.namePos] lower abdomen, but [npc2.she] roughly [npc2.verb(hold)] [npc.herHim] in place," + " forcefully grinding against [npc.herHim] as [npc2.she] [npc2.verb(growl)] that [npc2.she]'ll do whatever [npc2.she] [npc2.verb(want)].", "[npc.Name] frantically [npc.verb(try)] to pull away from [npc2.namePos] lower abdomen, but [npc2.she] roughly [npc2.verb(hold)] [npc.herHim] in place," + " [npc2.moaning+] as [npc2.she] [npc2.verb(ignore)] [npc.her] futile protests.", "Tears start to well up in [npc.namePos] [npc.eyes] as [npc.she] [npc.verb(try)] to pull away from [npc2.name], but [npc2.her] grip is too strong," + " and [npc2.she] [npc2.verb(continue)] [npc2.moaning+] as [npc2.she] roughly [npc2.verb(force)] [npc.namePos] [npc.cock+] against [npc2.her] lower abdomen.")); break; default: // DOM_NORMAL and in case anything goes wrong: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] desperately [npc.verb(try)] to pull [npc.her] [npc.cock+] away from [npc2.namePos] lower abdomen, but [npc2.name] firmly [npc2.verb(hold)] [npc.herHim] in place," + " grinding against [npc.herHim] as [npc2.she] [npc2.moanVerb] that [npc2.she]'ll do whatever [npc2.she] [npc2.verb(want)].", "[npc.Name] frantically [npc.verb(try)] to pull away from [npc2.namePos] lower abdomen, but [npc2.she] firmly [npc2.verb(hold)] [npc.herHim] in place," + " [npc2.moaning+] as [npc2.she] [npc2.verb(ignore)] [npc.her] futile protests.", "Tears start to well up in [npc.namePos] [npc.eyes] as [npc.she] [npc.verb(try)] to pull away from [npc2.name], but [npc2.her] grip is too strong," + " and [npc2.she] [npc2.verb(continue)] [npc2.moaning+] as [npc2.she] eagerly [npc2.verb(force)] [npc.her] [npc.cock+] against [npc2.her] lower abdomen.")); break; } } return UtilText.nodeContentSB.toString(); } }; public static final SexAction FUCKING_STOP = new SexAction( SexActionType.STOP_ONGOING, ArousalIncrease.TWO_LOW, ArousalIncrease.TWO_LOW, CorruptionLevel.ZERO_PURE, Util.newHashMapOfValues(new Value<>(SexAreaPenetration.PENIS, SexAreaOrifice.BREAST_CROTCH)), SexParticipantType.NORMAL) { @Override public String getActionTitle() { return "Stop receiving "+getPaizuriTitle(Main.sex.getCharacterTargetedForSexAction(this)); } @Override public String getActionDescription() { if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { return "Pull your [npc.cock+] away from [npc2.namePos] [npc2.crotchBoobs+] and stop fucking them."; } else { return "Pull your [npc.cock+] away from [npc2.namePos] lower abdomen and stop grinding against [npc2.herHim]."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterTargetedForSexAction(this).isBreastCrotchFuckablePaizuri()) { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Roughly pushing [npc2.name] away," + " [npc.name] [npc.verb(pull)] [npc.her] [npc.cock+] out from [npc2.her] cleavage and [npc.verb(tell)] [npc2.herHim] that [npc.sheHas] had enough of fucking [npc2.her] [npc2.crotchBoobs+].", "Roughly pulling [npc.her] [npc.cock+] out from [npc2.namePos] cleavage, [npc.name] [npc.verb(tell)] [npc2.herHim] that [npc.sheHas] had enough of fucking [npc2.her] [npc2.crotchBoobs+].")); break; default: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.name] [npc.verb(pull)] [npc.her] [npc.cock+] out from [npc2.namePos] cleavage and [npc.verb(tell)] [npc2.name] that [npc.sheHas] had enough of fucking [npc2.her] [npc2.crotchBoobs+].", "Pulling [npc.her] [npc.cock+] out from [npc2.namePos] cleavage, [npc.name] [npc.verb(tell)] [npc2.name] that [npc.sheHas] had enough of fucking [npc2.her] [npc2.crotchBoobs+].")); break; } } else if(Main.sex.getCharacterTargetedForSexAction(this).getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Roughly pushing [npc2.name] away, [npc.name] [npc.verb(pull)] [npc.her] [npc.cock+] out from [npc2.her] tiny amount of cleavage" + " and [npc.verb(tell)] [npc2.herHim] that [npc.sheHas] had enough of fucking [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs].", "Roughly pulling [npc.her] [npc.cock+] out from [npc2.namePos] tiny amount of cleavage," + " [npc.name] [npc.verb(tell)] [npc2.herHim] that [npc.sheHas] had enough of fucking [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs].")); break; default: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.name] [npc.verb(pull)] [npc.her] [npc.cock+] out from [npc2.namePos] tiny amount of cleavage" + " and [npc.verb(tell)] [npc2.herHim] that [npc.sheHas] had enough of fucking [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs].", "Pulling [npc.her] [npc.cock+] out from [npc2.namePos] tiny amount of cleavage," + " [npc.name] [npc.verb(tell)] [npc2.name] that [npc.sheHas] had enough of fucking [npc2.her] [npc2.crotchBoobSize] [npc2.crotchBoobs].")); break; } } else { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Roughly pushing [npc2.name] away, [npc.name] takes [npc.her] [npc.cock+] away from [npc2.her] lower abdomen and [npc.verb(tell)] [npc2.herHim] that [npc.sheHas] had enough of grinding against [npc2.herHim].", "Roughly pulling [npc.her] [npc.cock+] away from [npc2.namePos] lower abdomen, [npc.name] [npc.verb(tell)] [npc2.herHim] that [npc.sheHas] had enough of grinding against [npc2.herHim].")); break; default: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] takes [npc.her] [npc.cock+] away from [npc2.namePos] lower abdomen and [npc.verb(tell)] [npc2.herHim] that [npc.sheHas] had enough of grinding against [npc2.herHim].", "Pulling [npc.her] [npc.cock+] away from [npc2.namePos] lower abdomen, [npc.name] [npc.verb(tell)] [npc2.herHim] that [npc.sheHas] had enough of grinding against [npc2.herHim].")); break; } } switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(continue)] struggling against [npc.herHim], [npc2.moaning+] as [npc2.she] [npc2.verb(beg)] [npc.herHim] to leave [npc2.herHim] alone.", " With [npc2.a_moan+], [npc2.name] [npc2.verb(beg)] [npc.herHim] to leave [npc2.herHim] alone, tears welling up in [npc2.her] [npc2.eyes] as [npc2.she] weakly [npc2.verb(try)] to push [npc.herHim] away.")); break; default: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+], betraying [npc2.her] desire for [npc.herHim] to continue.", " With [npc2.a_moan+], [npc2.name] [npc2.verb(beg)] for [npc.herHim] to keep on using [npc2.herHim].")); break; } return UtilText.nodeContentSB.toString(); } }; // Partner actions: public static final SexAction USING_COCK_START = new SexAction( SexActionType.START_ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.ONE_VANILLA, Util.newHashMapOfValues(new Value<>(SexAreaOrifice.BREAST_CROTCH, SexAreaPenetration.PENIS)), SexParticipantType.NORMAL) { @Override public boolean isBaseRequirementsMet() { return Main.sex.getCharacterPerformingAction().hasBreastsCrotch() && Main.sex.getCharacterPerformingAction().getLegConfiguration().isBipedalPositionedCrotchBoobs(); } @Override public String getActionTitle() { return "Perform "+getPaizuriTitle(Main.sex.getCharacterPerformingAction()); } @Override public String getActionDescription() { if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { return "Use [npc2.namePos] [npc2.cock+] to fuck your [npc.crotchBoobs+]."; } else { return "Use [npc2.namePos] [npc2.cock+] to grind against your lower abdomen."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Gently taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to [npc.her] cleavage, and, sliding forwards," + " [npc.she] [npc.verb(press)] [npc.her] [npc.crotchBoobs+] together and [npc.verb(start)] giving [npc2.herHim] a titfuck.")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to [npc.her] cleavage, and, sliding forwards," + " [npc.she] [npc.verb(press)] [npc.her] [npc.crotchBoobs+] together and [npc.verb(start)] giving [npc2.herHim] an enthusiastic titfuck.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Roughly grabbing hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(pull)] it up to [npc.her] cleavage, and, sliding forwards," + " [npc.she] [npc.verb(press)] [npc.her] [npc.crotchBoobs+] together and [npc.verb(start)] giving [npc2.herHim] a forceful titfuck.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to [npc.her] cleavage, and, sliding forwards," + " [npc.she] [npc.verb(press)] [npc.her] [npc.crotchBoobs+] together and [npc.verb(start)] giving [npc2.herHim] a titfuck.")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to [npc.her] cleavage, and, sliding forwards," + " [npc.she] [npc.verb(press)] [npc.her] [npc.crotchBoobs+] together and [npc.verb(start)] giving [npc2.herHim] an enthusiastic titfuck.")); break; default: break; } switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out a happy little [npc2.moan] in response," + " helping to push [npc.namePos] [npc.crotchBoobs] together as [npc2.she] [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response," + " eagerly helping to push [npc.namePos] [npc.crotchBoobs] together as [npc2.she] enthusiastically [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response," + " roughly pushing [npc.namePos] [npc.crotchBoobs] together as [npc2.she] [npc2.verb(demand)] that [npc.she] keep on going.")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response," + " eagerly helping to push [npc.namePos] [npc.crotchBoobs] together as [npc2.she] enthusiastically [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan] in response," + " helping to push [npc.namePos] [npc.crotchBoobs] together as [npc2.she] meekly [npc2.verb(ask)] [npc.herHim] to keep going.")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+]," + " weakly trying to push [npc.name] away as [npc2.she] [npc2.verb(beg)] for [npc.herHim] to stop.")); break; default: break; } } else if(Main.sex.getCharacterPerformingAction().getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Gently taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to what little cleavage [npc.she] [npc.has], and, sliding forwards," + " [npc.she] [npc.verb(try)] [npc.her] best to press [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] together in order to give [npc2.herHim] a titfuck.")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to what little cleavage [npc.she] [npc.has], and, sliding forwards," + " [npc.she] [npc.verb(try)] [npc.her] best to press [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] together in order to give [npc2.herHim] an enthusiastic titfuck.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Roughly grabbing hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to what little cleavage [npc.she] [npc.has], and, sliding forwards," + " [npc.she] [npc.verb(try)] [npc.her] best to press [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] together in order to give [npc2.herHim] a forceful titfuck.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to what little cleavage [npc.she] [npc.has], and, sliding forwards," + " [npc.she] [npc.verb(try)] [npc.her] best to press [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] together in order to give [npc2.herHim] a titfuck.")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to what little cleavage [npc.she] [npc.has], and, sliding forwards," + " [npc.she] [npc.verb(try)] [npc.her] best to press [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] together in order to give [npc2.herHim] an enthusiastic titfuck.")); break; default: break; } switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out a happy little [npc2.moan] in response, gently thrusting into [npc.namePos] lower abdomen as [npc2.she] [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, desperately thrusting into [npc.namePos] lower abdomen as [npc2.she] enthusiastically [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, roughly thrusting into [npc.namePos] lower abdomen as [npc2.she] [npc2.verb(demand)] that [npc.herHim] keep on going.")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, eagerly thrusting into [npc.namePos] lower abdomen as [npc2.she] enthusiastically [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan] in response, thrusting into [npc.namePos] lower abdomen as [npc2.she] meekly [npc2.verb(ask)] [npc.herHim] to keep going.")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, weakly trying to push [npc.name] away as [npc2.she] [npc2.verb(beg)] for [npc.herHim] to stop.")); break; default: break; } } else { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Gently taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to [npc.her] flat lower abdomen, and, sliding forwards," + " [npc.she] [npc.verb(grind)] [npc.her] torso against [npc2.her] [npc2.cock+].")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to [npc.her] flat lower abdomen, and, sliding forwards," + " [npc.she] enthusiastically [npc.verb(grind)] [npc.her] torso against [npc2.her] [npc2.cock+].")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Roughly grabbing hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to [npc.her] flat lower abdomen, and, sliding forwards," + " [npc.she] forcefully [npc.verb(grind)] [npc.her] torso against [npc2.her] [npc2.cock+].")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to [npc.her] flat lower abdomen, and, sliding forwards," + " [npc.she] [npc.verb(grind)] [npc.her] torso against [npc2.her] [npc2.cock+].")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Eagerly taking hold of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(guide)] it up to [npc.her] flat lower abdomen, and, sliding forwards," + " [npc.she] enthusiastically [npc.verb(grind)] [npc.her] torso against [npc2.her] [npc2.cock+].")); break; default: break; } switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out a happy little [npc2.moan] in response, gently thrusting into [npc.namePos] lower abdomen as [npc2.she] [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, desperately thrusting into [npc.namePos] lower abdomen as [npc2.she] enthusiastically [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, roughly thrusting into [npc.namePos] lower abdomen as [npc2.she] [npc2.verb(demand)] that [npc.herHim] keep on going.")); break; case SUB_EAGER: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, eagerly thrusting into [npc.namePos] lower abdomen as [npc2.she] enthusiastically [npc2.verb(encourage)] [npc.herHim] to keep going.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan] in response, thrusting into [npc.namePos] lower abdomen as [npc2.she] meekly [npc2.verb(ask)] [npc.herHim] to keep going.")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(let)] out [npc2.a_moan+] in response, weakly trying to push [npc.name] away as [npc2.she] [npc2.verb(beg)] for [npc.herHim] to stop.")); break; default: break; } } return UtilText.nodeContentSB.toString(); } }; private static String getTargetedCharacterReceivingResponse(SexAction action) { if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(action))) { case SUB_EAGER: case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] greedily [npc2.verb(thrust)] [npc2.her] [npc2.cock+] deep between [npc.namePos] [npc.crotchBoobs+]," + " letting out [npc2.a_moan+] as [npc2.she] enthusiastically [npc2.verb(fuck)] [npc.her] cleavage.", " [npc2.A_moan+] bursts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] thrusting [npc2.her] [npc2.cock+] deep between [npc.namePos] [npc.crotchBoobs+].", " [npc2.Moaning] in delight, [npc2.name] eagerly [npc2.verb(drive)] [npc2.her] [npc2.cock+] in and out between [npc.namePos] [npc.crotchBoobs+].")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " Failing to pull [npc2.her] [npc2.cock] away from [npc.namePos] [npc.crotchBoobs+]," + " [npc2.name] [npc2.verb(let)] out [npc2.a_sob+] as [npc2.she] weakly [npc2.verb(try)] to struggle free.", " [npc2.A_sob+] bursts out from between [npc2.namePos] [npc2.lips] as [npc2.she] weakly [npc2.verb(try)] to push [npc.name] away," + " squirming and protesting as [npc.name] [npc.verb(continue)] to force [npc2.her] [npc2.cock+] back and forth between [npc.her] [npc.crotchBoobs+].", " [npc2.Sobbing] in distress, [npc2.name] [npc2.verb(try)], in vain, to pull [npc2.her] [npc2.cock] away from [npc.namePos] [npc.crotchBoobs+].")); break; case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] gently [npc2.verb(thrust)] [npc2.her] [npc2.cock+] between [npc.namePos] [npc.crotchBoobs+]," + " letting out a soft [npc2.moan] as [npc2.she] [npc2.verb(fuck)] [npc.her] cleavage.", " A soft [npc2.moan] drifts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] gently thrusting [npc2.her] [npc2.cock+] between [npc.namePos] [npc.crotchBoobs+].", " [npc2.Moaning] in delight, [npc2.name] gently [npc2.verb(thrust)] [npc2.her] [npc2.cock+] back and forth between [npc.namePos] [npc.crotchBoobs+].")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] violently [npc2.verb(thrust)] [npc2.her] [npc2.cock+] deep between [npc.namePos] [npc.crotchBoobs+]," + " letting out [npc2.a_moan+] as [npc2.she] roughly [npc2.verb(fuck)] [npc.her] cleavage.", " [npc2.A_moan+] bursts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] roughly slamming [npc2.her] [npc2.cock+] deep between [npc.namePos] [npc.crotchBoobs+].", " [npc2.Moaning] in delight, [npc2.name] roughly [npc2.verb(slam)] [npc2.her] [npc2.cock+] back and forth between [npc.namePos] [npc.crotchBoobs+].")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(thrust)] [npc2.her] [npc2.cock+] deep between [npc.namePos] [npc.crotchBoobs+]," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(fuck)] [npc.her] cleavage.", " [npc2.A_moan+] bursts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] thrusting [npc2.her] [npc2.cock+] deep between [npc.namePos] [npc.crotchBoobs+].", " [npc2.Moaning] in delight, [npc2.name] [npc2.verb(drive)] [npc2.her] [npc2.cock+] back and forth between [npc.namePos] [npc.crotchBoobs+].")); break; } } else if(Main.sex.getCharacterPerformingAction().getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(action))) { case SUB_EAGER: case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] greedily [npc2.verb(thrust)] [npc2.her] [npc2.cock+] into what little cleavage [npc.name] [npc.has] to offer," + " letting out [npc2.a_moan+] as [npc2.she] enthusiastically [npc2.verb(fuck)] [npc.her] [npc.crotchBoobs+].", " [npc2.A_moan+] bursts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] thrusting [npc2.her] [npc2.cock+] between [npc.namePos] [npc.crotchBoobSize] [npc.crotchBoobs].", " [npc2.Moaning] in delight, [npc2.name] eagerly [npc2.verb(drive)] [npc2.her] [npc2.cock+] in and out of the diminutive cleavage formed between [npc.namePos] [npc.crotchBoobs+].")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " Failing to pull [npc2.her] [npc2.cock] away from [npc.namePos] [npc.crotchBoobs+]," + " [npc2.name] [npc2.verb(let)] out [npc2.a_sob+] as [npc2.she] weakly [npc2.verb(try)] to struggle free.", " [npc2.A_sob+] bursts out from between [npc2.namePos] [npc2.lips] as [npc2.she] weakly [npc2.verb(try)] to push [npc.name] away," + " squirming and protesting as [npc.name] [npc.verb(continue)] to force [npc2.her] [npc2.cock+] back and forth between [npc.her] [npc.crotchBoobs+].", " [npc2.Sobbing] in distress, [npc2.name] [npc2.verb(try)], in vain, to pull [npc2.her] [npc2.cock] away from [npc.namePos] [npc.crotchBoobs+].")); break; case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] gently [npc2.verb(thrust)] [npc2.her] [npc2.cock+] into what little cleavage [npc.name] [npc.has] to offer," + " letting out a soft [npc2.moan] as [npc2.she] [npc2.verb(fuck)] [npc.her] [npc.crotchBoobs+].", " A soft [npc2.moan] drifts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] gently thrusting [npc2.her] [npc2.cock+] between [npc.namePos] [npc.crotchBoobSize] [npc.crotchBoobs].", " [npc2.Moaning] in delight, [npc2.name] gently [npc2.verb(thrust)] [npc2.her] [npc2.cock+] in and out of the diminutive cleavage formed between [npc.namePos] [npc.crotchBoobs+].")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] violently [npc2.verb(thrust)] [npc2.her] [npc2.cock+] into what little cleavage [npc.name] [npc.has] to offer," + " letting out [npc2.a_moan+] as [npc2.she] roughly [npc2.verb(fuck)] [npc.her] [npc.crotchBoobs+].", " [npc2.A_moan+] bursts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] roughly slamming [npc2.her] [npc2.cock+] between [npc.crotchBoobSize] [npc.crotchBoobs].", " [npc2.Moaning] in delight, [npc2.name] roughly [npc2.verb(slam)] [npc2.her] [npc2.cock+] in and out of the diminutive cleavage formed between [npc.namePos] [npc.crotchBoobs+].")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(thrust)] [npc2.her] [npc2.cock+] into what little cleavage [npc.name] [npc.has] to offer," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(fuck)] [npc.her] [npc.crotchBoobs+].", " [npc2.A_moan+] bursts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] thrusting [npc2.her] [npc2.cock+] between [npc.crotchBoobSize] [npc.crotchBoobs].", " [npc2.Moaning] in delight, [npc2.name] [npc2.verb(drive)] [npc2.her] [npc2.cock+] in and out of the diminutive cleavage formed between [npc.namePos] [npc.crotchBoobs+].")); break; } } else { switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(action))) { case SUB_EAGER: case DOM_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] greedily [npc2.verb(thrust)] [npc2.her] [npc2.cock+] over [npc.namePos] flat stomach," + " letting out [npc2.a_moan+] as [npc2.she] enthusiastically [npc2.verb(grind)] against [npc.her] torso.", " [npc2.A_moan+] bursts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] thrusting [npc2.her] [npc2.cock+] up and down against [npc.namePos] flat stomach.", " [npc2.Moaning] in delight, [npc2.name] eagerly [npc2.verb(grind)] [npc2.her] [npc2.cock+] over [npc.namePos] flat stomach.")); break; case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " Failing to pull [npc2.her] [npc2.cock] away from [npc.namePos] flat stomach," + " [npc2.name] [npc2.verb(let)] out [npc2.a_sob+] as [npc2.she] weakly [npc2.verb(try)] to struggle free.", " [npc2.A_sob+] bursts out from between [npc2.namePos] [npc2.lips] as [npc2.she] weakly [npc2.verb(try)] to push [npc.name] away," + " squirming and protesting as [npc.name] [npc.verb(continue)] to force [npc2.her] [npc2.cock+] back and forth over [npc.her] flat stomach.", " [npc2.Sobbing] in distress, [npc2.name] [npc2.verb(try)], in vain, to pull [npc2.her] [npc2.cock] away from [npc.namePos] flat stomach.")); break; case DOM_GENTLE: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] gently [npc2.verb(thrust)] [npc2.her] [npc2.cock+] over [npc.namePos] flat stomach," + " letting out a soft [npc2.moan] as [npc2.she] [npc2.verb(grind)] against [npc.her] torso.", " A soft [npc2.moan] drifts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] gently thrusting [npc2.her] [npc2.cock+] up and down against [npc.namePos] flat stomach.", " [npc2.Moaning] in delight, [npc2.name] gently [npc2.verb(grind)] [npc2.her] [npc2.cock+] over [npc.namePos] flat stomach.")); break; case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] violently [npc2.verb(thrust)] [npc2.her] [npc2.cock+] over [npc.namePos] flat stomach," + " letting out [npc2.a_moan+] as [npc2.she] roughly [npc2.verb(grind)] against [npc.her] torso.", " [npc2.A_moan+] bursts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] roughly slamming [npc2.her] [npc2.cock+] up and down against [npc.namePos] flat stomach.", " [npc2.Moaning] in delight, [npc2.name] roughly [npc2.verb(grind)] [npc2.her] [npc2.cock+] over [npc.namePos] flat stomach.")); break; case SUB_NORMAL: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(thrust)] [npc2.her] [npc2.cock+] over [npc.namePos] flat stomach," + " letting out [npc2.a_moan+] as [npc2.she] [npc2.verb(grind)] against [npc.her] torso.", " [npc2.A_moan+] bursts out from [npc2.namePos] mouth, before [npc2.she] [npc2.verb(start)] thrusting [npc2.her] [npc2.cock+] up and down against [npc.namePos] flat stomach.", " [npc2.Moaning] in delight, [npc2.name] [npc2.verb(grind)] [npc2.her] [npc2.cock+] over [npc.namePos] flat stomach.")); break; } } return ""; } public static final SexAction PERFORMING_COCK_DOM_GENTLE = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.ONE_VANILLA, Util.newHashMapOfValues(new Value<>(SexAreaOrifice.BREAST_CROTCH, SexAreaPenetration.PENIS)), SexParticipantType.NORMAL, SexPace.DOM_GENTLE) { @Override public String getActionTitle() { return "Gently perform "+getPaizuriTitle(Main.sex.getCharacterPerformingAction()); } @Override public String getActionDescription() { if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { return "Gently pleasure [npc2.namePos] [npc2.cock+] with your [npc.crotchBoobs+]."; } else { return "Gently pleasure [npc2.namePos] [npc2.cock+] with your stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to push [npc.her] [npc.crotchBoobs+] together around [npc2.namePos] [npc2.cock+]," + " [npc.name] gently [npc.verb(raise)] and [npc.verb(lower)] [npc.her] torso, softly [npc.moaning] as [npc.she] [npc.verb(use)] [npc.her] cleavage.", "Gently wrapping [npc.her] [npc.crotchBoobs+] around [npc2.namePos] [npc2.cock+], [npc.name] slowly [npc.verb(lift)] them up and down," + " letting out a soft [npc.moan] as [npc.she] lovingly [npc.verb(give)] [npc2.herHim] a titfuck.", "Letting out a soft [npc.moan], [npc.name] [npc.verb(push)] [npc.her] [npc.crotchBoobs+] together," + " enveloping [npc2.namePos] [npc2.cock+] in [npc.her] pillowy mounds as [npc.she] [npc.verb(give)] [npc2.herHim] a loving titfuck.")); } else { if(Main.sex.getCharacterPerformingAction().getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to push [npc.her] [npc.crotchBoobs+] against the sides of [npc2.namePos] [npc2.cock+]," + " [npc.name] gently [npc.verb(raise)] and [npc.verb(lower)] [npc.her] torso, softly [npc.moaning] as [npc.she] [npc.verb(try)] [npc.her] best to use what little cleavage [npc.she] [npc.has].", "Gently pressing [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] against the sides of [npc2.namePos] [npc2.cock+], [npc.name] slowly [npc.verb(lift)] them up and down," + " letting out a soft [npc.moan] as [npc.she] lovingly [npc.verb(attempt)] to give [npc2.herHim] a titfuck.", "Letting out a soft [npc.moan], [npc.name] [npc.verb(push)] [npc.her] [npc.crotchBoobs+] together," + " trying [npc.her] best to pleasure [npc2.namePos] [npc2.cock+] with the tiny amount of cleavage [npc.she] [npc.has].")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to wrap [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+], [npc.name] gently [npc.verb(raise)] and [npc.verb(lower)] [npc.namePos] torso," + " softly [npc.moaning] as [npc.she] [npc.verb(thrust)] out [npc.her] flat lower abdomen and [npc.verb(grind)] against [npc2.herHim].", "Gently wrapping [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(lift)] [npc.her] torso up and down," + " grinding [npc.her] flat lower abdomen against [npc2.herHim] as [npc.she] [npc.verb(try)] to imitate giving [npc2.herHim] a titfuck.", "Letting out a soft [npc.moan], [npc.name] [npc.verb(wrap)] [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+]," + " before thrusting [npc.her] flat lower abdomen out and giving [npc2.herHim] an imitation titfuck")); } } UtilText.nodeContentSB.append(getTargetedCharacterReceivingResponse(this)); return UtilText.nodeContentSB.toString(); } }; public static final SexAction PERFORMING_COCK_DOM_NORMAL = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.ONE_VANILLA, Util.newHashMapOfValues(new Value<>(SexAreaOrifice.BREAST_CROTCH, SexAreaPenetration.PENIS)), SexParticipantType.NORMAL, SexPace.DOM_NORMAL) { @Override public String getActionTitle() { return "Perform "+getPaizuriTitle(Main.sex.getCharacterPerformingAction()); } @Override public String getActionDescription() { if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { return "Pleasure [npc2.namePos] [npc2.cock+] with your [npc.crotchBoobs+]."; } else { return "Pleasure [npc2.namePos] [npc2.cock+] with your flat stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to happily push [npc.her] [npc.crotchBoobs+] together around [npc2.namePos] [npc2.cock+]," + " [npc.name] enthusiastically [npc.verb(raise)] and [npc.verb(lower)] [npc.her] torso, [npc.moaning+] as [npc.she] [npc.verb(use)] [npc.her] cleavage to give [npc2.herHim] an eager titfuck.", "Eagerly wrapping [npc.her] [npc.crotchBoobs+] around [npc2.namePos] [npc2.cock+], [npc.name] energetically [npc.verb(lift)] them up and down," + " letting out [npc.a_moan+] as [npc.she] [npc.verb(give)] [npc2.herHim] an enthusiastic titfuck.", "Letting out [npc.a_moan+], [npc.name] happily [npc2.verb(push)] [npc.her] [npc.crotchBoobs+] together," + " enveloping [npc2.namePos] [npc2.cock+] in [npc.her] pillowy mounds as [npc.she] [npc.verb(give)] [npc2.herHim] an eager titfuck.")); } else { if(Main.sex.getCharacterPerformingAction().getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to happily push [npc.her] [npc.crotchBoobs+] against the sides of [npc2.namePos] [npc2.cock+]," + " [npc.name] enthusiastically [npc.verb(raise)] and [npc.verb(lower)] [npc.her] torso, [npc.moaning+] as [npc.she] [npc.verb(try)] [npc.her] best to use what little cleavage [npc.she] [npc.has].", "Eagerly pressing [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] against the sides of [npc2.namePos] [npc2.cock+], [npc.name] energetically [npc.verb(lift)] them up and down," + " letting out [npc.a_moan+] as [npc.she] enthusiastically [npc.verb(attempt)] to give [npc2.herHim] a titfuck.", "Letting out [npc.a_moan+], [npc.name] happily [npc2.verb(push)] [npc.her] [npc.crotchBoobs+] together," + " trying [npc.her] best to pleasure [npc2.namePos] [npc2.cock+] with the tiny amount of cleavage [npc.she] [npc.has].")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to happily wrap [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+], [npc.name] enthusiastically [npc.verb(raise)] and [npc.verb(lower)] [npc.namePos] torso," + " [npc.moaning+] as [npc.she] [npc.verb(thrust)] out [npc.her] flat lower abdomen to desperately grind against [npc2.herHim].", "Eagerly wrapping [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+], [npc.name] energetically [npc.verb(lift)] [npc.her] torso up and down," + " grinding [npc.her] flat lower abdomen against [npc2.herHim] as [npc.she] [npc.verb(try)] to imitate giving [npc2.herHim] a titfuck.", "Letting out [npc.a_moan+], [npc.name] happily [npc.verb(wrap)] [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+]," + " before thrusting [npc.her] flat lower abdomen out and eagerly giving [npc2.herHim] an imitation titfuck")); } } UtilText.nodeContentSB.append(getTargetedCharacterReceivingResponse(this)); return UtilText.nodeContentSB.toString(); } }; public static final SexAction PERFORMING_COCK_DOM_ROUGH = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.TWO_HORNY, Util.newHashMapOfValues(new Value<>(SexAreaOrifice.BREAST_CROTCH, SexAreaPenetration.PENIS)), SexParticipantType.NORMAL, SexPace.DOM_ROUGH) { @Override public String getActionTitle() { return "Roughly perform "+getPaizuriTitle(Main.sex.getCharacterPerformingAction()); } @Override public String getActionDescription() { if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { return "Roughly pleasure [npc2.namePos] [npc2.cock+] with your [npc.crotchBoobs+]."; } else { return "Roughly pleasure [npc2.namePos] [npc2.cock+] with your flat stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to roughly force [npc.her] [npc.crotchBoobs+] together around [npc2.namePos] [npc2.cock+]," + " [npc.name] rapidly [npc.verb(raise)] and [npc.verb(lower)] [npc.her] torso, [npc.moaning+] as [npc.she] [npc.verb(use)] [npc.her] cleavage to give [npc2.herHim] a dominant titfuck.", "Dominantly wrapping [npc.her] [npc.crotchBoobs+] around [npc2.namePos] [npc2.cock+], [npc.name] roughly [npc.verb(bounce)] them up and down," + " letting out [npc.a_moan+] as [npc.she] [npc.verb(give)] [npc2.herHim] a forceful titfuck.", "Letting out [npc.a_moan+], [npc.name] forcefully [npc2.verb(push)] [npc.her] [npc.crotchBoobs+] together," + " enveloping [npc2.namePos] [npc2.cock+] in [npc.her] pillowy mounds as [npc.she] [npc.verb(give)] [npc2.herHim] a dominant titfuck.")); } else { if(Main.sex.getCharacterPerformingAction().getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to roughly force [npc.her] [npc.crotchBoobs+] against the sides of [npc2.namePos] [npc2.cock+]," + " [npc.name] rapidly [npc.verb(raise)] and [npc.verb(lower)] [npc.her] torso, [npc.moaning+] as [npc.she] [npc.verb(try)] [npc.her] best to use what little cleavage [npc.she] [npc.has].", "Dominantly pressing [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] against the sides of [npc2.namePos] [npc2.cock+], [npc.name] roughly [npc.verb(lift)] them up and down," + " letting out [npc.a_moan+] as [npc.she] [npc.verb(attempt)] to give [npc2.herHim] a forceful titfuck.", "Letting out [npc.a_moan+], [npc.name] forcefully [npc2.verb(push)] [npc.her] [npc.crotchBoobs+] together," + " trying [npc.her] best to pleasure [npc2.namePos] [npc2.cock+] with the tiny amount of cleavage [npc.she] [npc.has].")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to roughly wrap [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+], [npc.name] violently [npc.verb(raise)] and [npc.verb(lower)] [npc.namePos] torso," + " [npc.moaning+] as [npc.she] [npc.verb(thrust)] out [npc.her] flat lower abdomen to dominantly grind against [npc2.herHim].", "Dominantly wrapping [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+], [npc.name] roughly [npc.verb(lift)] [npc.her] torso up and down," + " grinding [npc.her] flat lower abdomen against [npc2.herHim] as [npc.she] [npc.verb(try)] to imitate giving [npc2.herHim] a titfuck.", "Letting out [npc.a_moan+], [npc.name] forcefully [npc.verb(wrap)] [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+]," + " before thrusting [npc.her] flat lower abdomen out and roughly giving [npc2.herHim] an imitation titfuck")); } } UtilText.nodeContentSB.append(getTargetedCharacterReceivingResponse(this)); return UtilText.nodeContentSB.toString(); } }; public static final SexAction PERFORMING_COCK_SUB_NORMAL = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.ONE_VANILLA, Util.newHashMapOfValues(new Value<>(SexAreaOrifice.BREAST_CROTCH, SexAreaPenetration.PENIS)), SexParticipantType.NORMAL, SexPace.SUB_NORMAL) { @Override public String getActionTitle() { return "Perform "+getPaizuriTitle(Main.sex.getCharacterPerformingAction()); } @Override public String getActionDescription() { if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { return "Pleasure [npc2.namePos] [npc2.cock+] with your [npc.crotchBoobs+]."; } else { return "Pleasure [npc2.namePos] [npc2.cock+] with your flat stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to push [npc.her] [npc.crotchBoobs+] together around [npc2.namePos] [npc2.cock+]," + " [npc.name] [npc.verb(raise)] and [npc.verb(lower)] [npc.her] torso, [npc.moaning+] as [npc.she] [npc.verb(use)] [npc.her] cleavage to give [npc2.herHim] a titfuck.", "Wrapping [npc.her] [npc.crotchBoobs+] around [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(lift)] them up and down," + " letting out [npc.a_moan+] as [npc.she] [npc.verb(give)] [npc2.herHim] a titfuck.", "Letting out [npc.a_moan+], [npc.name] [npc.verb(push)] [npc.her] [npc.crotchBoobs+] together," + " enveloping [npc2.namePos] [npc2.cock+] in [npc.her] pillowy mounds as [npc.she] [npc.verb(give)] [npc2.herHim] a titfuck.")); } else { if(Main.sex.getCharacterPerformingAction().getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to happily push [npc.her] [npc.crotchBoobs+] against the sides of [npc2.namePos] [npc2.cock+]," + " [npc.name] [npc.verb(raise)] and [npc.verb(lower)] [npc.her] torso, [npc.moaning+] as [npc.she] [npc.verb(try)] [npc.her] best to use what little cleavage [npc.she] [npc.has].", "Pressing [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] against the sides of [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(lift)] them up and down," + " letting out [npc.a_moan+] as [npc.she] [npc.verb(attempt)] to give [npc2.herHim] a titfuck.", "Letting out [npc.a_moan+], [npc.name] [npc.verb(push)] [npc.her] [npc.crotchBoobs+] together," + " trying [npc.her] best to pleasure [npc2.namePos] [npc2.cock+] with the tiny amount of cleavage [npc.she] [npc.has].")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to happily wrap [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(raise)] and [npc.verb(lower)] [npc.namePos] torso," + " [npc.moaning+] as [npc.she] [npc.verb(thrust)] out [npc.her] flat lower abdomen to grind against [npc2.herHim].", "Wrapping [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+], [npc.name] [npc.verb(lift)] [npc.her] torso up and down," + " grinding [npc.her] flat lower abdomen against [npc2.herHim] as [npc.she] [npc.verb(try)] to imitate giving [npc2.herHim] a titfuck.", "Letting out [npc.a_moan+], [npc.name] [npc.verb(wrap)] [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+]," + " before thrusting [npc.her] flat lower abdomen out and giving [npc2.herHim] an imitation titfuck")); } } UtilText.nodeContentSB.append(getTargetedCharacterReceivingResponse(this)); return UtilText.nodeContentSB.toString(); } }; public static final SexAction PERFORMING_COCK_SUB_EAGER = new SexAction( SexActionType.ONGOING, ArousalIncrease.FOUR_HIGH, ArousalIncrease.FOUR_HIGH, CorruptionLevel.ONE_VANILLA, Util.newHashMapOfValues(new Value<>(SexAreaOrifice.BREAST_CROTCH, SexAreaPenetration.PENIS)), SexParticipantType.NORMAL, SexPace.SUB_EAGER) { @Override public String getActionTitle() { return "Eagerly perform "+getPaizuriTitle(Main.sex.getCharacterPerformingAction()); } @Override public String getActionDescription() { if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { return "Eagerly pleasure [npc2.namePos] [npc2.cock+] with your [npc.crotchBoobs+]."; } else { return "Eagerly pleasure [npc2.namePos] [npc2.cock+] with your flat stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to happily push [npc.her] [npc.crotchBoobs+] together around [npc2.namePos] [npc2.cock+]," + " [npc.name] enthusiastically [npc.verb(raise)] and [npc.verb(lower)] [npc.her] torso, [npc.moaning+] as [npc.she] [npc.verb(use)] [npc.her] cleavage to give [npc2.herHim] an eager titfuck.", "Eagerly wrapping [npc.her] [npc.crotchBoobs+] around [npc2.namePos] [npc2.cock+], [npc.name] energetically [npc.verb(lift)] them up and down," + " letting out [npc.a_moan+] as [npc.she] [npc.verb(give)] [npc2.herHim] an enthusiastic titfuck.", "Letting out [npc.a_moan+], [npc.name] happily [npc2.verb(push)] [npc.her] [npc.crotchBoobs+] together," + " enveloping [npc2.namePos] [npc2.cock+] in [npc.her] pillowy mounds as [npc.she] [npc.verb(give)] [npc2.herHim] an eager titfuck.")); } else { if(Main.sex.getCharacterPerformingAction().getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to happily push [npc.her] [npc.crotchBoobs+] against the sides of [npc2.namePos] [npc2.cock+]," + " [npc.name] enthusiastically [npc.verb(raise)] and [npc.verb(lower)] [npc.her] torso, [npc.moaning+] as [npc.she] [npc.verb(try)] [npc.her] best to use what little cleavage [npc.she] [npc.has].", "Eagerly pressing [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] against the sides of [npc2.namePos] [npc2.cock+], [npc.name] energetically [npc.verb(lift)] them up and down," + " letting out [npc.a_moan+] as [npc.she] enthusiastically [npc.verb(attempt)] to give [npc2.herHim] a titfuck.", "Letting out [npc.a_moan+], [npc.name] happily [npc2.verb(push)] [npc.her] [npc.crotchBoobs+] together," + " trying [npc.her] best to pleasure [npc2.namePos] [npc2.cock+] with the tiny amount of cleavage [npc.she] [npc.has].")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "Reaching up to happily wrap [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+], [npc.name] enthusiastically [npc.verb(raise)] and [npc.verb(lower)] [npc.namePos] torso," + " [npc.moaning+] as [npc.she] [npc.verb(thrust)] out [npc.her] flat lower abdomen to desperately grind against [npc2.herHim].", "Eagerly wrapping [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+], [npc.name] energetically [npc.verb(lift)] [npc.her] torso up and down," + " grinding [npc.her] flat lower abdomen against [npc2.herHim] as [npc.she] [npc.verb(try)] to imitate giving [npc2.herHim] a titfuck.", "Letting out [npc.a_moan+], [npc.name] happily [npc.verb(wrap)] [npc.her] [npc.fingers+] around [npc2.namePos] [npc2.cock+]," + " before thrusting [npc.her] flat lower abdomen out and eagerly giving [npc2.herHim] an imitation titfuck")); } } UtilText.nodeContentSB.append(getTargetedCharacterReceivingResponse(this)); return UtilText.nodeContentSB.toString(); } }; public static final SexAction FUCKED_SUB_RESIST = new SexAction( SexActionType.ONGOING, ArousalIncrease.ZERO_NONE, ArousalIncrease.TWO_LOW, CorruptionLevel.ZERO_PURE, Util.newHashMapOfValues(new Value<>(SexAreaOrifice.BREAST_CROTCH, SexAreaPenetration.PENIS)), SexParticipantType.NORMAL, SexPace.SUB_RESISTING) { @Override public String getActionTitle() { return "Resist performing "+getPaizuriTitle(Main.sex.getCharacterPerformingAction()); } @Override public String getActionDescription() { if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { return "Try and pull your [npc.crotchBoobs+] away from [npc2.namePos] [npc2.cock+]."; } else { return "Try and pull your flat stomach away from [npc2.namePos] [npc2.cock+]."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] [npc.verb(let)] out [npc.moan+] as [npc.she] [npc.verb(try)] to pull [npc.her] [npc.crotchBoobs+] away from [npc2.namePos] [npc2.cock+]," + " before begging for [npc2.herHim] to leave [npc.herHim] alone.", "With [npc.a_moan+], [npc.name] weakly [npc.verb(try)] to pull away from [npc2.name]," + " sobbing in distress as [npc2.her] [npc2.cock+] continues to thrust up between [npc.her] [npc.crotchBoobs+].", "Letting out [npc.a_moan+], [npc.name] [npc.verb(try)] to push [npc2.name] away from [npc.herHim]," + " tears running down [npc.her] cheeks as [npc2.she] [npc2.verb(continue)] thrusting [npc2.her] [npc2.cock+] into [npc.her] cleavage.")); } else if(Main.sex.getCharacterPerformingAction().getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] [npc.verb(let)] out [npc.moan+] as [npc.she] [npc.verb(try)] to pull [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs] away from [npc2.namePos] [npc2.cock+]," + " before begging for [npc.herHim] to leave [npc2.herHim] alone.", "With [npc.a_moan+], [npc.name] weakly [npc.verb(try)] to pull away from [npc2.name]," + " sobbing in distress as [npc2.her] [npc2.cock+] continue to thrust up between [npc.her] [npc.crotchBoobSize] [npc.crotchBoobs+].", "Letting out [npc.a_moan+], [npc.name] [npc.verb(try)] to push [npc2.name] away from [npc.herHim]," + " tears running down [npc.her] cheeks as [npc2.she] [npc2.verb(continue)] thrusting [npc2.her] [npc2.cock+] into [npc.her] small cleavage.")); } else { UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] [npc.verb(let)] out [npc.moan+] as [npc.she] [npc.verb(try)] to pull [npc.her] flat lower abdomen away from [npc2.namePos] [npc2.cock+]," + " before begging for [npc.herHim] to leave [npc2.herHim] alone.", "With [npc.a_moan+], [npc.name] weakly [npc.verb(try)] to pull away from [npc2.name]," + " sobbing in distress as [npc2.her] [npc2.cock+] continues to grind up against [npc.her] flat lower abdomen.", "Letting out [npc.a_moan+], [npc.name] [npc.verb(try)] to push [npc2.name] away from [npc.herHim]," + " tears running down [npc.her] cheeks as [npc2.she] [npc2.verb(continue)] thrusting [npc2.her] [npc2.cock+] against [npc.her] torso.")); } return UtilText.nodeContentSB.toString(); } }; public static final SexAction FUCKED_STOP = new SexAction( SexActionType.STOP_ONGOING, ArousalIncrease.TWO_LOW, ArousalIncrease.TWO_LOW, CorruptionLevel.ZERO_PURE, Util.newHashMapOfValues(new Value<>(SexAreaOrifice.BREAST_CROTCH, SexAreaPenetration.PENIS)), SexParticipantType.NORMAL) { @Override public String getActionTitle() { return "Stop performing "+getPaizuriTitle(Main.sex.getCharacterPerformingAction()); } @Override public String getActionDescription() { if(Main.sex.getCharacterPerformingAction().isBreastCrotchFuckablePaizuri()) { return "Push [npc2.namePos] [npc2.cock] away from your [npc.crotchBoobs+]."; } else { return "Push [npc2.namePos] [npc2.cock] away from your flat stomach."; } } @Override public String getDescription() { UtilText.nodeContentSB.setLength(0); if(Main.sex.getCharacterPerformingAction().getBreastCrotchSize().getMeasurement()>=CupSize.AA.getMeasurement()) { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] roughly [npc.verb(push)] [npc2.name] away from [npc.herHim], and, in a menacing tone, [npc.verb(order)] [npc2.herHim] to stop fucking [npc.her] [npc.crotchBoobs+].", "With a menacing growl, [npc.name] roughly [npc.verb(push)] [npc2.name] away, and [npc.verb(order)] [npc2.herHim] to stop fucking [npc.her] [npc.crotchBoobs+].")); break; default: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] [npc.verb(push)] [npc2.name] away from [npc.herHim], and [npc.verb(tell)] [npc2.herHim] to stop fucking [npc.her] [npc.crotchBoobs+].", "With one last [npc.moan], [npc.name] [npc.verb(push)] [npc2.name] away, and [npc.verb(tell)] [npc2.herHim] to stop fucking [npc.her] [npc.crotchBoobs+].")); break; } } else { switch(Main.sex.getSexPace(Main.sex.getCharacterPerformingAction())) { case DOM_ROUGH: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] roughly [npc.verb(push)] [npc2.name] away from [npc.herHim], and, in a menacing tone, [npc.verb(order)] [npc2.herHim] to stop grinding against [npc.her] lower abdomen.", "With a menacing growl, [npc.name] roughly [npc.verb(push)] [npc2.name] away, and [npc.verb(order)] [npc2.herHim] to stop grinding against [npc.her] lower abdomen.")); break; default: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( "[npc.Name] [npc.verb(push)] [npc2.name] away from [npc.herHim], and [npc.verb(tell)] [npc2.herHim] to stop grinding against [npc.her] lower abdomen.", "With one last [npc.moan], [npc.name] [npc.verb(push)] [npc2.name] away, and [npc.verb(tell)] [npc2.herHim] to stop grinding against [npc.her] lower abdomen.")); break; } } switch(Main.sex.getSexPace(Main.sex.getCharacterTargetedForSexAction(this))) { case SUB_RESISTING: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] [npc2.verb(continue)] struggling against [npc.herHim], [npc2.moaning+] as [npc2.she] [npc2.verb(beg)] [npc.name] to leave [npc2.herHim] alone.", " With [npc2.a_moan+], [npc2.name] [npc2.verb(beg)] [npc.name] to leave [npc2.herHim] alone, tears welling up in [npc2.her] [npc2.eyes] as [npc2.she] weakly [npc2.verb(try)] to push [npc.herHim] away.")); break; default: UtilText.nodeContentSB.append(UtilText.returnStringAtRandom( " [npc2.Name] can't [npc2.verb(help)] but let out [npc2.a_moan+], betraying [npc2.her] desire for more of [npc.namePos] attention.", " With [npc2.a_moan+], [npc2.she] [npc2.verb(beg)] for [npc.name] to keep on using [npc2.herHim].")); break; } return UtilText.nodeContentSB.toString(); } }; }
62.162959
230
0.684041
66234893ded76978eb8689cb1860685f877a5559
2,499
package com.github.draylar.beebetter.block; import com.github.draylar.beebetter.entity.ApiaryBlockEntity; import com.github.draylar.beebetter.entity.ModdedBeehiveBlockEntity; import com.github.draylar.beebetter.registry.BeeEntities; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.ShapeContext; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.BlockEntityTicker; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.state.StateManager; import net.minecraft.state.property.IntProperty; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.shape.VoxelShape; import net.minecraft.world.BlockView; import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; public class ApiaryBlock extends ModdedBeehiveBlock { public static final int MAX_HONEY = 10; public static final IntProperty HONEY_LEVEL = IntProperty.of("honey_level", 0, MAX_HONEY); public static final VoxelShape SHAPE = Block.createCuboidShape(1, 0, 1, 15, 16, 15); public ApiaryBlock(Block.Settings settings) { super(settings); setDefaultState(getStateManager().getDefaultState().with(HONEY_LEVEL, 0).with(FACING, Direction.NORTH)); } @Nullable @Override public BlockEntity createBlockEntity(BlockPos pos, BlockState state) { return new ApiaryBlockEntity(pos, state); } @Override public IntProperty getHoneyProperty() { return HONEY_LEVEL; } @Override public int getMaxHoneyLevel() { return 10; } @Override public int getHoneyLevel(BlockState state) { return state.get(HONEY_LEVEL); } @Override public VoxelShape getOutlineShape(BlockState state, BlockView view, BlockPos pos, ShapeContext ePos) { return SHAPE; } @Override public VoxelShape getCollisionShape(BlockState state, BlockView view, BlockPos pos, ShapeContext ePos) { return SHAPE; } @Override public void appendProperties(StateManager.Builder<Block, BlockState> builder) { builder.add(HONEY_LEVEL, FACING); } @Nullable @Override public <T extends BlockEntity> BlockEntityTicker<T> getTicker(World world, BlockState blockState, BlockEntityType<T> blockEntityType) { return world.isClient ? null : checkType(blockEntityType, BeeEntities.APIARY, ModdedBeehiveBlockEntity::serverTick); } }
33.77027
139
0.751501
b2567f0ff67c19f6f5957d12660efcd9f03e3f1d
3,520
package org.sorus.oneseventen.util.input; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import org.sorus.client.version.input.Button; import org.sorus.client.version.input.Key; public class InputMap { private static final BiMap<Integer, Key> KEY_MAP = HashBiMap.create(); static { KEY_MAP.put(1, Key.ESCAPE); KEY_MAP.put(59, Key.F1); KEY_MAP.put(60, Key.F2); KEY_MAP.put(61, Key.F3); KEY_MAP.put(62, Key.F4); KEY_MAP.put(63, Key.F5); KEY_MAP.put(64, Key.F6); KEY_MAP.put(65, Key.F7); KEY_MAP.put(66, Key.F8); KEY_MAP.put(67, Key.F9); KEY_MAP.put(68, Key.F10); KEY_MAP.put(87, Key.F11); KEY_MAP.put(88, Key.F12); KEY_MAP.put(41, Key.GRAVE); KEY_MAP.put(2, Key.ONE); KEY_MAP.put(3, Key.TWO); KEY_MAP.put(4, Key.THREE); KEY_MAP.put(5, Key.FOUR); KEY_MAP.put(6, Key.FIVE); KEY_MAP.put(7, Key.SIX); KEY_MAP.put(8, Key.SEVEN); KEY_MAP.put(9, Key.EIGHT); KEY_MAP.put(10, Key.NINE); KEY_MAP.put(11, Key.ZERO); KEY_MAP.put(12, Key.MINUS); KEY_MAP.put(13, Key.EQUALS); KEY_MAP.put(14, Key.BACKSPACE); KEY_MAP.put(15, Key.TAB); KEY_MAP.put(16, Key.Q); KEY_MAP.put(17, Key.W); KEY_MAP.put(18, Key.E); KEY_MAP.put(19, Key.R); KEY_MAP.put(20, Key.T); KEY_MAP.put(21, Key.Y); KEY_MAP.put(22, Key.U); KEY_MAP.put(23, Key.I); KEY_MAP.put(24, Key.O); KEY_MAP.put(25, Key.P); KEY_MAP.put(26, Key.BRACKET_OPEN); KEY_MAP.put(27, Key.BRACKET_CLOSE); KEY_MAP.put(43, Key.SLASH_BACK); KEY_MAP.put(58, Key.CAPSLOCK); KEY_MAP.put(30, Key.A); KEY_MAP.put(31, Key.S); KEY_MAP.put(32, Key.D); KEY_MAP.put(33, Key.F); KEY_MAP.put(34, Key.G); KEY_MAP.put(35, Key.H); KEY_MAP.put(36, Key.J); KEY_MAP.put(37, Key.K); KEY_MAP.put(38, Key.L); KEY_MAP.put(39, Key.SEMICOLON); KEY_MAP.put(40, Key.APOSTROPHE); KEY_MAP.put(28, Key.ENTER); KEY_MAP.put(42, Key.SHIFT_LEFT); KEY_MAP.put(44, Key.Z); KEY_MAP.put(45, Key.X); KEY_MAP.put(46, Key.C); KEY_MAP.put(47, Key.V); KEY_MAP.put(48, Key.B); KEY_MAP.put(49, Key.N); KEY_MAP.put(50, Key.M); KEY_MAP.put(51, Key.COMMA); KEY_MAP.put(52, Key.PERIOD); KEY_MAP.put(53, Key.SLASH_FORWARD); KEY_MAP.put(54, Key.SHIFT_RIGHT); KEY_MAP.put(29, Key.CONTROL_LEFT); KEY_MAP.put(219, Key.META_LEFT); KEY_MAP.put(56, Key.ALT_LEFT); KEY_MAP.put(57, Key.SPACE); KEY_MAP.put(184, Key.ALT_RIGHT); KEY_MAP.put(220, Key.META_RIGHT); KEY_MAP.put(184, Key.MENU); KEY_MAP.put(157, Key.CONTROL_RIGHT); } private static final BiMap<Integer, Button> BUTTON_MAP = HashBiMap.create(); static { BUTTON_MAP.put(0, Button.ONE); } public static Key getKey(int keyCode) { return KEY_MAP.getOrDefault(keyCode, Key.NULL); } public static int getKeyCode(Key key) { return KEY_MAP.inverse().get(key); } public static Button getButton(int buttonCode) { return BUTTON_MAP.getOrDefault(buttonCode, Button.NULL); } public static int getButtonCode(Button button) { return BUTTON_MAP.inverse().get(button); } }
30.08547
80
0.582386
35f380a12fa86adf9f7d810bc00f779f60f8875a
856
package com.github.games647.scoreboardstats.pvpstats; import com.avaje.ebeaninternal.server.util.ClassPathReader; import org.apache.commons.lang.ArrayUtils; /** * This is workaround to a bug in Java 6. eBean 2.7.3 has a bug catching up * the wrong exception while scanning through the ebean.properties. Spigot * fixed this with updating eBean to 2.8.1 and newer versions of eBean has * fixed it completely. * * The actually problem is that non-latin characters cannot be read in Java 6. * Java 7 has a fix for it by passing a charset, but this still cannot be used in * Java 6 and eBean doesn't use it either. */ public class PathReader implements ClassPathReader { @Override public Object[] readPath(ClassLoader classLoader) { //return an empty array without creating one return ArrayUtils.EMPTY_OBJECT_ARRAY; } }
34.24
81
0.748832
60f9923add3feb41d6e1486031728e06358b7c3e
272
package uk.gov.dft.bluebadge.webapp.citizen.client.applicationmanagement.model; /** Gets or Sets EligibilityCodeField */ public enum EligibilityCodeField { PIP, DLA, AFRFCS, WPMS, BLIND, WALKD, ARMS, CHILDBULK, CHILDVEHIC, TERMILL, NONE, HIDDEN }
15.111111
79
0.716912
ff7c8c5abeb0cba5b00489768e38585486d0f021
1,676
package com.github.nenomm.groovyboot.builder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class FileFetcher { private static final String GROOVY_SRC_PATH = "groovySources"; private static Logger log = LoggerFactory.getLogger(FileFetcher.class); private static FileFetcher instance; static { instance = new FileFetcher(); } private FileFetcher() { // for internal use } public static List<File> fetchSourceFiles() { try { return instance.fetchFiles(GROOVY_SRC_PATH).stream().filter(file -> file.getPath().endsWith(".groovy")).collect(Collectors.toList()); } catch (URISyntaxException e) { log.error("Exception while fetching files!", e); } return Collections.emptyList(); } private List<File> fetchFiles(String basePath) throws URISyntaxException { ArrayList<File> results = new ArrayList<>(); fetchFilesRecursively(new File(getClass().getClassLoader().getResource(basePath).toURI()), results); return results; } private void fetchFilesRecursively(File path, List<File> results) { if (path.isDirectory()) { log.info("Trying to fetch files from {}", path.getPath()); for (File file : path.listFiles()) { fetchFilesRecursively(file, results); } } else { log.info("Adding file: {}", path.getPath()); results.add(path); } } }
28.896552
145
0.647971
9da9a3e114b9e3ee41217aca7446ebe8b01cbd4b
4,411
/** * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.interestrate.capletstripping; import com.opengamma.analytics.financial.model.interestrate.curve.ForwardCurve; import com.opengamma.analytics.financial.model.volatility.discrete.DiscreteVolatilityFunction; import com.opengamma.analytics.financial.model.volatility.discrete.ParameterizedSABRModelDiscreteVolatilityFunctionProvider; import com.opengamma.analytics.financial.model.volatility.discrete.ParameterizedSmileModelDiscreteVolatilityFunctionProvider; import com.opengamma.analytics.financial.model.volatility.smile.function.SABRFormulaData; import com.opengamma.analytics.math.curve.InterpolatedDoublesCurve; import com.opengamma.analytics.math.function.DoublesVectorFunctionProvider; import com.opengamma.analytics.math.function.VectorFunction; import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory; import com.opengamma.analytics.math.interpolation.Interpolator1DFactory; import com.opengamma.util.ArgumentChecker; /** * Caplet stripper using Hagan's SABR formula. The SABR parameters (alpha, beta, rho & nu) are themselves represented as * parameterised term structures, and this collection of parameters are the <i>model parameters</i>. For a particular * caplet, we can find the smile model parameters at its expiry, then (using the SABR formula) find the (Black) * volatility at its strike; hence the model parameters describe a caplet volatility surface. * <p> * For a set of market cap values, we can find, in a least-square sense, the optimal set of model parameters to reproduce the market values. Since the smiles are smooth functions of a few (4) * parameters, it is generally not possible to recover exactly market values using this method. */ public class CapletStripperSABRModel extends CapletStripperSmileModel<SABRFormulaData> { private static final int NUM_MODEL_PARMS = 4; /** * Set up the stripper. * @param pricer The pricer (which contained the details of the market values of the caps/floors) * @param volFuncProvider This will 'provide' a {@link DiscreteVolatilityFunction} that maps from a set of model * parameters (describing the term structures of SABR parameters) to the volatilities of the requested caplets. */ public CapletStripperSABRModel(MultiCapFloorPricer pricer, ParameterizedSmileModelDiscreteVolatilityFunctionProvider<SABRFormulaData> volFuncProvider) { super(pricer, volFuncProvider); } /** * Set up the stripper. * @param pricer The pricer (which contained the details of the market values of the caps/floors) * @param smileModelParameterProviders each of these providers represents a different smile parameter - <b>there * must be one for each smile model parameter</b>. Given a (common) set of expiries, each one provides a {@link VectorFunction} that gives the corresponding smile model parameter at each expiry for * a set of model * parameters. This gives a lot of flexibility as to how the (smile model) parameter term structures are * represented. */ public CapletStripperSABRModel(MultiCapFloorPricer pricer, DoublesVectorFunctionProvider[] smileModelParameterProviders) { super(pricer, getDiscreteVolatilityFunctionProvider(pricer, smileModelParameterProviders)); } private static ParameterizedSABRModelDiscreteVolatilityFunctionProvider getDiscreteVolatilityFunctionProvider(MultiCapFloorPricer pricer, DoublesVectorFunctionProvider[] smileModelParameterProviders) { ArgumentChecker.notNull(pricer, "pricer"); ArgumentChecker.noNulls(smileModelParameterProviders, "smileModelParameterProviders"); ArgumentChecker.isTrue(NUM_MODEL_PARMS == smileModelParameterProviders.length, "Require {} smileModelParameterProviders", NUM_MODEL_PARMS); // this interpolated forward curve that will only be hit at the knots, so don't need anything more than linear ForwardCurve fwdCurve = new ForwardCurve(InterpolatedDoublesCurve.from(pricer.getCapletExpiries(), pricer.getCapletForwardRates(), CombinedInterpolatorExtrapolatorFactory.getInterpolator(Interpolator1DFactory.LINEAR, Interpolator1DFactory.LINEAR_EXTRAPOLATOR))); return new ParameterizedSABRModelDiscreteVolatilityFunctionProvider(fwdCurve, smileModelParameterProviders); } }
65.835821
203
0.815461
8d762b05372da35572f024bad77b6cabb00cd6b7
2,615
package net.cattaka.hungrycatball.ui; import net.cattaka.hungrycatball.HungryCatBallConstants; import net.cattaka.hungrycatball.core.SceneBundle; import net.cattaka.hungrycatball.gl.CtkGL; import net.cattaka.hungrycatball.stage.StageInfo; import net.cattaka.hungrycatball.utils.DrawingUtil.Align; import net.cattaka.hungrycatball.utils.DrawingUtil.AlphaMode; import net.cattaka.hungrycatball.utils.ImageResource; import net.cattaka.hungrycatball.utils.ImageResource.TextureId; import org.jbox2d.common.Vec2; public class UiStageButton extends UiView { private ImageResource mBackImageResource; private ImageResource mLockImageResource; private StageInfo stageInfo; private UiStageButton(Vec2 position, Vec2 size, ImageResource backImageResource, ImageResource lockImageResource, StageInfo stageInfo) { super(position, size); this.mBackImageResource = backImageResource; this.mLockImageResource = lockImageResource; this.stageInfo = stageInfo; } public static UiStageButton createUiPanel(Vec2 position, Vec2 size, SceneBundle sceneBundle, StageInfo stageInfo) { return new UiStageButton(position, size, sceneBundle.getDrawUtil().getImageResource(TextureId.UI_STAGE_BUTTON), sceneBundle.getDrawUtil().getImageResource(TextureId.UI_LOCK), stageInfo ); } @Override public void draw(CtkGL gl, SceneBundle sceneBundle) { super.draw(gl, sceneBundle); int row = 0; switch (getTouchState()) { default: case RELEASE: case RELEASED: row = 0; break; case PRESSE: case PRESSED: row = 1; break; } sceneBundle.getDrawUtil().drawBitmap(gl, mBackImageResource, row, 0, mPosition, mSize, 0, 1, null, AlphaMode.STD); final Vec2 pos = new Vec2(); pos.set(mPosition.x, mPosition.y + 0.4f); sceneBundle.getDrawUtil().drawNumber(gl, stageInfo.getStageNo(), 0, pos, HungryCatBallConstants.CELL_SIZE * 2, Align.CENTER, null, 1f); pos.set(mPosition.x + 0.8f, mPosition.y - 0.8f); sceneBundle.getDrawUtil().drawNumber(gl, stageInfo.getHighScore(), 0, pos, HungryCatBallConstants.CELL_SIZE * 0.8f, Align.RIGHT, null, 1f); if (!stageInfo.isUnlocked()) { final Vec2 size = new Vec2(); size.set(mSize.x * 0.8f, mSize.y * 0.8f); sceneBundle.getDrawUtil().drawBitmap(gl, mLockImageResource, 0, 0, mPosition, size, 0, 1, null, AlphaMode.STD); } } }
40.859375
147
0.676864
b0f3544821d436969c145a866d54b148952b216e
340
package cn.shishuihao.thirdparty.api.pay.domain.merchant.business_info; import lombok.Data; import lombok.experimental.SuperBuilder; /** * 经营场景. * 一种经营场景只能一项 * * @author shishuihao * @version 1.0.0 */ @SuperBuilder @Data public class SalesScenes { /** * 经营场景类型. */ private final SalesScenesType salesScenesType; }
16.190476
71
0.705882
14d2b281bcf7636ad32cf632c1ab22f978d43d11
3,757
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.CRBranchLocationManagementPlanRetrieveInputModelBranchLocationManagementPlanInstanceAnalysis; import org.bian.dto.CRBranchLocationManagementPlanRetrieveInputModelBranchLocationManagementPlanInstanceReportRecord; import javax.validation.Valid; /** * CRBranchLocationManagementPlanRetrieveInputModel */ public class CRBranchLocationManagementPlanRetrieveInputModel { private Object branchLocationManagementPlanRetrieveActionTaskRecord = null; private String branchLocationManagementPlanRetrieveActionRequest = null; private CRBranchLocationManagementPlanRetrieveInputModelBranchLocationManagementPlanInstanceReportRecord branchLocationManagementPlanInstanceReportRecord = null; private CRBranchLocationManagementPlanRetrieveInputModelBranchLocationManagementPlanInstanceAnalysis branchLocationManagementPlanInstanceAnalysis = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The retrieve service call consolidated processing record * @return branchLocationManagementPlanRetrieveActionTaskRecord **/ public Object getBranchLocationManagementPlanRetrieveActionTaskRecord() { return branchLocationManagementPlanRetrieveActionTaskRecord; } public void setBranchLocationManagementPlanRetrieveActionTaskRecord(Object branchLocationManagementPlanRetrieveActionTaskRecord) { this.branchLocationManagementPlanRetrieveActionTaskRecord = branchLocationManagementPlanRetrieveActionTaskRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the retrieve action service request (lists requested reports) * @return branchLocationManagementPlanRetrieveActionRequest **/ public String getBranchLocationManagementPlanRetrieveActionRequest() { return branchLocationManagementPlanRetrieveActionRequest; } public void setBranchLocationManagementPlanRetrieveActionRequest(String branchLocationManagementPlanRetrieveActionRequest) { this.branchLocationManagementPlanRetrieveActionRequest = branchLocationManagementPlanRetrieveActionRequest; } /** * Get branchLocationManagementPlanInstanceReportRecord * @return branchLocationManagementPlanInstanceReportRecord **/ public CRBranchLocationManagementPlanRetrieveInputModelBranchLocationManagementPlanInstanceReportRecord getBranchLocationManagementPlanInstanceReportRecord() { return branchLocationManagementPlanInstanceReportRecord; } public void setBranchLocationManagementPlanInstanceReportRecord(CRBranchLocationManagementPlanRetrieveInputModelBranchLocationManagementPlanInstanceReportRecord branchLocationManagementPlanInstanceReportRecord) { this.branchLocationManagementPlanInstanceReportRecord = branchLocationManagementPlanInstanceReportRecord; } /** * Get branchLocationManagementPlanInstanceAnalysis * @return branchLocationManagementPlanInstanceAnalysis **/ public CRBranchLocationManagementPlanRetrieveInputModelBranchLocationManagementPlanInstanceAnalysis getBranchLocationManagementPlanInstanceAnalysis() { return branchLocationManagementPlanInstanceAnalysis; } public void setBranchLocationManagementPlanInstanceAnalysis(CRBranchLocationManagementPlanRetrieveInputModelBranchLocationManagementPlanInstanceAnalysis branchLocationManagementPlanInstanceAnalysis) { this.branchLocationManagementPlanInstanceAnalysis = branchLocationManagementPlanInstanceAnalysis; } }
45.26506
214
0.87144
d753bb1daba3d82c9a9b317244c1ddb15a6258e6
3,130
/* * Copyright (c) 2016-2017, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see the LICENSE.txt file in repo root * or https://opensource.org/licenses/BSD-3-Clause */ package com.salesforce.pyplyn.util; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import java.util.List; import org.testng.annotations.Test; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.multibindings.Multibinder; import com.salesforce.pyplyn.configuration.EndpointConnector; import com.salesforce.pyplyn.model.Extract; import com.salesforce.pyplyn.model.Load; import com.salesforce.pyplyn.model.Transform; import com.salesforce.pyplyn.processor.ExtractProcessor; import com.salesforce.pyplyn.processor.LoadProcessor; import com.salesforce.pyplyn.status.SystemStatusConsumer; /** * Test class * * @author Mihai Bojin &lt;[email protected]&gt; * @since 3.0 */ public class MultibinderFactoryTest { /** * This test provides little value other than asserting that all methods return a valid Multibinder */ @Test public void testHelperMethodsReturnNonNullSets() throws Exception { // ARRANGE Module module = new Module(); // ACT Guice.createInjector(module); // ASSERT assertThat(module.appConnectors, not(nullValue())); assertThat(module.extractDatasources, not(nullValue())); assertThat(module.extractProcessors, not(nullValue())); assertThat(module.loadDestinations, not(nullValue())); assertThat(module.loadProcessors, not(nullValue())); assertThat(module.statusConsumers, not(nullValue())); assertThat(module.transformFunctions, not(nullValue())); } /** * Module implementation that makes use of Guice's Binder to create all expected Multibinders */ private static class Module extends AbstractModule { Multibinder<List<EndpointConnector>> appConnectors; Multibinder<Class<? extends Extract>> extractDatasources; Multibinder<ExtractProcessor<? extends Extract>> extractProcessors; Multibinder<Class<? extends Load>> loadDestinations; Multibinder<LoadProcessor<? extends Load>> loadProcessors; Multibinder<SystemStatusConsumer> statusConsumers; Multibinder<Class<? extends Transform>> transformFunctions; @Override protected void configure() { appConnectors = MultibinderFactory.appConnectors(binder()); extractDatasources = MultibinderFactory.extractDatasources(binder()); extractProcessors = MultibinderFactory.extractProcessors(binder()); loadDestinations = MultibinderFactory.loadDestinations(binder()); loadProcessors = MultibinderFactory.loadProcessors(binder()); statusConsumers = MultibinderFactory.statusConsumers(binder()); transformFunctions = MultibinderFactory.transformFunctions(binder()); } } }
38.170732
103
0.72524
e1448fa265410d2bd1959550cacee84a81218db3
2,836
/* * Copyright 2012-2014 Dan Cioca * * 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.dci.intellij.dbn.common.ui.tab; import com.intellij.ui.tabs.TabInfo; import javax.swing.Icon; import javax.swing.JTabbedPane; import javax.swing.plaf.TabbedPaneUI; import java.awt.Component; public class TabbedPaneUtil { public static void setSelectComponentTab(Component component) { Component parent = component.getParent(); while (parent != null) { if (parent instanceof JTabbedPane) { JTabbedPane tabbedPane = (JTabbedPane) parent; tabbedPane.setSelectedComponent(component); break; } component = parent; parent = parent.getParent(); } } public static void setComponentTabIcon(Component component, Icon icon) { Component parent = component.getParent(); while (parent != null) { if (parent instanceof JTabbedPane) { JTabbedPane tabbedPane = (JTabbedPane) parent; int index = tabbedPane.indexOfComponent(component); tabbedPane.setIconAt(index, icon); break; } component = parent; parent = parent.getParent(); } } public static int getTabIndexAt(JTabbedPane tabbedPane, int x, int y) { TabbedPaneUI tabbedPaneUI = tabbedPane.getUI(); for (int k = 0; k < tabbedPane.getTabCount(); k++) { java.awt.Rectangle rectangle = tabbedPaneUI.getTabBounds(tabbedPane, k); if (rectangle.contains(x, y)) return k; } return -1; } public static String getSelectedTabName(TabbedPane tabbedPane) { TabInfo selectedInfo = tabbedPane.getSelectedInfo(); return selectedInfo == null ? null : selectedInfo.getText(); } public static void selectTab(TabbedPane tabbedPane, String tabName) { if (tabName != null) { for (TabInfo tabInfo : tabbedPane.getTabs()) { if (tabInfo.getText().equals(tabName)) { tabbedPane.select(tabInfo, false); return; } } } } }
34.585366
85
0.601199
c67162438efb876e35d71ddd8988de401067b0ba
808
package com.shoukailiang.community.util.base; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.experimental.Accessors; import java.io.Serializable; /** * 请求参数基础类、带分页参数 * @param <T> */ @Accessors(chain = true) @Data public class BaseRequest<T> implements Serializable { @ApiModelProperty(value = "页码", required = true) private long current; @ApiModelProperty(value = "每页显示多少条", required = true) private long size; /** * 封装分页对象 * @return */ @ApiModelProperty(hidden = true) // 不在swagger接口文档中显示 public IPage<T> getPage() { return new Page<T>().setCurrent(this.current).setSize(this.size); } }
23.085714
73
0.709158
0caa188183c363d039c65d549d9742f39dbe5936
7,445
/** * Copyright 2009 Humboldt-Universität zu Berlin. * * 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.corpus_tools.salt.graph.impl; import java.util.HashSet; import java.util.Set; import org.corpus_tools.salt.Beta; import org.corpus_tools.salt.graph.Graph; import org.corpus_tools.salt.graph.Layer; import org.corpus_tools.salt.graph.Node; import org.corpus_tools.salt.graph.Relation; import org.corpus_tools.salt.graph.impl.GraphImpl.UPDATE_TYPE; @SuppressWarnings("serial") public class RelationImpl<S extends Node, T extends Node> extends IdentifiableElementImpl implements Relation<S, T> { /** * Initializes an object of type {@link Relation}. */ public RelationImpl() { } /** * Initializes an object of type {@link Relation}. If {@link #delegate} is * not null, all functions of this method are delegated to the delegate * object. Setting {@link #delegate} makes this object to a container. * * @param a * delegate object of the same type. */ public RelationImpl(Relation<S, T> delegate) { super(delegate); } /** * {@inheritDoc Relation#getDelegate()} */ public Relation<S, T> getDelegate() { return ((Relation<S, T>) super.getDelegate()); } /** source node of this relation. **/ protected S source = null; /** * {@inheritDoc Relation#getSource()} */ public S getSource() { // delegate method to delegate if set if (getDelegate() != null) { return (getDelegate().getSource()); } return source; } /** * {@inheritDoc Relation#setSource(Node)} Notifies the graph, about the * change of the source. */ public void setSource(S source) { if (source == null) { return; } // delegate method to delegate if set if (getDelegate() != null) { getDelegate().setSource(source); return; } S oldValue = getSource(); this.source = source; // notify graph about change of target if (getGraph() != null && getGraph() instanceof GraphImpl) { ((GraphImpl) getGraph()).update(oldValue, this, UPDATE_TYPE.RELATION_SOURCE); } } /** target node of this relation. **/ private T target = null; /** * {@inheritDoc Relation#getTarget()} */ public T getTarget() { // delegate method to delegate if set if (getDelegate() != null) { return (getDelegate().getTarget()); } return target; } /** * {@inheritDoc Relation#setTarget(Node)} Notifies the graph, about the * change of the target. */ public void setTarget(T target) { // delegate method to delegate if set if (getDelegate() != null) { getDelegate().setTarget(target); return; } T oldValue = this.getTarget(); this.target = target; // notify graph about change of target if (getGraph() != null && getGraph() instanceof GraphImpl) { ((GraphImpl) getGraph()).update(oldValue, this, UPDATE_TYPE.RELATION_TARGET); } } /** container graph **/ protected Graph graph = null; /** {@inheritDoc Relation#getGraph()} **/ @Override public Graph getGraph() { // delegate method to delegate if set if (getDelegate() != null) { return getDelegate().getGraph(); } return (graph); } /** {@inheritDoc Relation#setGraph(Graph)} **/ @Override public void setGraph(Graph graph) { // delegate method to delegate if set if (getDelegate() != null) { getDelegate().setGraph(graph); return; } Graph oldGraph = getGraph(); if (graph != null) { graph.addRelation(this); } if (oldGraph != null && oldGraph != graph && oldGraph instanceof GraphImpl) { // remove relation from old graph ((GraphImpl) oldGraph).basicRemoveRelation(this); } basicSetGraph(graph); } /** * This is an internally used method. To implement a double chaining of * {@link Graph} and {@link Relation} object when an relation is inserted * into this graph and to avoid an endless invocation the insertion of an * relation is splited into the two methods {@link #setGraph(Graph)} and * {@link #basicSetGraph(Graph)}. The invocation of methods is implement as * follows: * * <pre> * {@link Graph#addRelation(Relation)} {@link Relation#setGraph(Graph)} * || \ / || * || X || * \/ / \ \/ * {@link Graph#basicAddRelation(Relation)} {@link Relation#basicSetGraph(Graph)} * </pre> * * That means method {@link #setGraph(Graph)} calls * {@link #basicSetGraph(Graph)} and * {@link Graph#basicAddRelation(Relation)}. And method * {@link #setGraph(Graph)} calls {@link Graph#basicAddRelation(Relation)} * and {@link Relation#basicSetGraph(Graph)}. * * @param graph * graph which contains this relation */ protected void basicSetGraph(Graph graph) { // delegate method to delegate if set if (getDelegate() != null && getDelegate() instanceof RelationImpl) { ((RelationImpl) getDelegate()).basicSetGraph(graph); return; } // remove from old graph if it was changed if (this.graph != graph && this.graph instanceof GraphImpl) { ((GraphImpl) this.graph).basicRemoveRelation(this); } this.graph = graph; } /** * Same as {@link #basicSetGraph(Graph)} but does not remove this relation * from old graph, if it was not equal to the passed graph. * * @param graph */ @Beta public void basicSetGraph_WithoutRemoving(Graph graph) { if (getDelegate() != null && getDelegate() instanceof RelationImpl) { ((RelationImpl) getDelegate()).basicSetGraph_WithoutRemoving(graph); return; } this.graph = graph; } /** {@inheritDoc} **/ @Override public Set<? extends Layer> getLayers() { // delegate method to delegate if set if (getDelegate() != null) { return (getDelegate().getLayers()); } Set<Layer> layers = new HashSet<>(); if (getGraph() != null) { Set<Layer> allLayers = getGraph().getLayers(); if ((allLayers != null) && (allLayers.size() > 0)) { for (Layer layer : allLayers) { if (layer.getRelations().contains(this)) { layers.add(layer); } } } } return (layers); } /** * {@inheritDoc}<br/> * Since the method {@link #getLayers()} retrieves all layers by accessing * the layers in graph, this class does not contain an own collection of * layers. **/ @Override public void addLayer(Layer layer) { // delegate method to delegate if set if (getDelegate() != null) { getDelegate().addLayer(layer); } if (layer != null) { layer.addRelation(this); } } /** * {@inheritDoc} <br/> * Since the method {@link #getLayers()} retrieves all layers by accessing * the layers in graph, this class does not contain an own collection of * layers. **/ @Override public void removeLayer(Layer layer) { // delegate method to delegate if set if (getDelegate() != null) { getDelegate().removeLayer(layer); } if (layer != null) { layer.removeRelation(this); } } }
27.072727
117
0.654936
b0b776fec289f54b5ebf7585860a70447ae96b58
3,125
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.annotation; import org.springframework.beans.factory.wiring.BeanWiringInfo; import org.springframework.beans.factory.wiring.BeanWiringInfoResolver; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * {@link org.springframework.beans.factory.wiring.BeanWiringInfoResolver} that * uses the Configurable annotation to identify which classes need autowiring. * The bean name to look up will be taken from the {@link Configurable} annotation * if specified; otherwise the default will be the fully-qualified name of the * class being configured. * * @author Rod Johnson * @author Juergen Hoeller * @see Configurable * @see org.springframework.beans.factory.wiring.ClassNameBeanWiringInfoResolver * @since 2.0 */ public class AnnotationBeanWiringInfoResolver implements BeanWiringInfoResolver { @Override @Nullable public BeanWiringInfo resolveWiringInfo(Object beanInstance) { Assert.notNull(beanInstance, "Bean instance must not be null"); Configurable annotation = beanInstance.getClass().getAnnotation(Configurable.class); return (annotation != null ? buildWiringInfo(beanInstance, annotation) : null); } /** * Build the BeanWiringInfo for the given Configurable annotation. * * @param beanInstance the bean instance * @param annotation the Configurable annotation found on the bean class * @return the resolved BeanWiringInfo */ protected BeanWiringInfo buildWiringInfo(Object beanInstance, Configurable annotation) { if (!Autowire.NO.equals(annotation.autowire())) { return new BeanWiringInfo(annotation.autowire().value(), annotation.dependencyCheck()); } else { if (!"".equals(annotation.value())) { // explicitly specified bean name return new BeanWiringInfo(annotation.value(), false); } else { // default bean name return new BeanWiringInfo(getDefaultBeanName(beanInstance), true); } } } /** * Determine the default bean name for the specified bean instance. * <p>The default implementation returns the superclass name for a CGLIB * proxy and the name of the plain bean class else. * * @param beanInstance the bean instance to build a default name for * @return the default bean name to use * @see org.springframework.util.ClassUtils#getUserClass(Class) */ protected String getDefaultBeanName(Object beanInstance) { return ClassUtils.getUserClass(beanInstance).getName(); } }
37.650602
90
0.7632
22fe3f29860c6a50171c41132ebdc4a5eacccd5a
749
package net.openid.conformance.condition.client; import net.openid.conformance.condition.PostEnvironment; import net.openid.conformance.condition.PreEnvironment; import net.openid.conformance.testmodule.Environment; public class BuildRequestObjectByValueRedirectToAuthorizationEndpoint extends AbstractBuildRequestObjectRedirectToAuthorizationEndpoint { @Override @PreEnvironment(required = { "authorization_endpoint_request", "request_object_claims", "server" }, strings = "request_object") @PostEnvironment(strings = "redirect_to_authorization_endpoint") public Environment evaluate(Environment env) { String requestObject = env.getString("request_object"); return buildRedirect(env, "request", requestObject); } }
39.421053
138
0.813084
641e1b78e5b2d0825869016daaef0350be817acb
4,338
package com.z.controller; import com.z.pojo.Goods; import com.z.service.GoodsService; import com.z.service.impl.GoodsServiceImpl; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.UUID; @WebServlet("/admin/manage/updateGoodsbygid.do") public class UpdateGoodsServlet extends HttpServlet { private GoodsService goodsService = new GoodsServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); FileItemFactory fileItemFactory =new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(fileItemFactory); List<FileItem> fileItems=null; try { fileItems = sfu.parseRequest(req); } catch (FileUploadException e) { e.printStackTrace(); } // for (FileItem fileItem : fileItems) { // System.out.println("fileItem.getFieldName() = " + fileItem.getFieldName()); // System.out.println("fileItem.getContentType() = " + fileItem.getContentType()); // System.out.println("fileItem.getName() = " + fileItem.getName()); // System.out.println("fileItem.getSize() = " + fileItem.getSize()); // System.out.println("fileItem.getString() = " + fileItem.getString("utf-8")); // } FileItem fileItem0 = fileItems.get(0); String gid = fileItem0.getString("utf-8"); FileItem fileItem = fileItems.get(1); String gname = fileItem.getString("utf-8"); FileItem fileItem1 = fileItems.get(2); String tid =fileItem1.getString("utf-8"); FileItem fileItem2 = fileItems.get(3); String filename = fileItem2.getName(); FileItem fileItem3 = fileItems.get(4); String price =fileItem3.getString("utf-8"); FileItem fileItem4 = fileItems.get(5); String gdesc =fileItem4.getString("utf-8"); Goods goods = new Goods(); goods.setGid(Integer.valueOf(gid)); goods.setPrice(Double.valueOf(price)); goods.setGname(gname); goods.setGdesc(gdesc); if(filename==null||"".equals(filename)){ }else { String savepath = getServletContext().getRealPath("/") + "upload\\"; File savefile = new File(savepath); if(!savefile.isDirectory()){ if(savefile.exists()){ savefile.delete(); savefile.mkdir(); }else { savefile.mkdir(); } } // 2.修改上传图片的名称。 // 1.确定上传文件名称没有路径/ // 1.windows linux mac。 if(filename.indexOf(File.separator)>-1){ filename =filename.substring(filename.lastIndexOf(File.separator)); } // 修改名称 String newName = UUID.randomUUID().toString()+"_"+new Date().getTime()+"_"+filename; File save = new File(savepath,newName); try { fileItem2.write(save); } catch (Exception e) { e.printStackTrace(); } String usepath ="upload\\"+newName; goods.setG_img(usepath); } Integer flag = 0; try { flag = goodsService.updataGoods(goods); } catch (SQLException throwables) { throwables.printStackTrace(); } if(flag > 0){ req.setAttribute("msg","修改成功"); req.getRequestDispatcher("/admin/manage/adminfindgoodspage.do").forward(req,resp); }else { req.setAttribute("msg","修改失败"); req.getRequestDispatcher("/admin/manage/adminfindgoodspage.do").forward(req,resp); } } }
36.762712
115
0.621946
d66e07e33ada7157630e315d27e8a766c3ca82a7
3,584
package com.bina.varsim.types; import java.util.logging.Logger; /** * Used to represent the chromosome name, able to useful things like determine sex * <p/> * Created by johnmu on 1/27/15. */ public class ChrString implements Comparable<ChrString>{ private final static Logger log = Logger.getLogger(ChrString.class.getName()); final String name; public ChrString(final String name) { this.name = name; } /** * Converts hg19 or b37 format chromosomes to b37 format * * @param chr Chromosome name as a string * @return chromosome name as a string in b37 format */ public static String stripChr(final String chr) { if (chr.length() > 3 && chr.substring(0, 3).equalsIgnoreCase("chr")) { return chr.substring(3); } if (chr.equals("M")) { return "MT"; } return chr; } /** * convert string array to ChrString array * @param s * @return */ public static ChrString[] string2ChrString(final String[] s) { if (s == null) { return new ChrString[0]; } ChrString[] chrStrings = new ChrString[s.length]; for (int i = 0; i < s.length; i++) { chrStrings[i] = new ChrString(s[i]); } return chrStrings; } public String getName() { return name; } @Override public String toString() { return name; } public boolean isX() { if (name.equals("X") || name.equals("chrX")) { return true; } else if (name.startsWith("X") || name.startsWith("chrX")) { //TODO: handle restricted X chromosome (say X_1_1000) log.warning("Prefix looks like chromosome X, but might be treated as diploid genome."); return false; } return false; } public boolean isY() { if (name.equals("Y") || name.equals("chrY")) { return true; } else if (name.startsWith("Y") || name.startsWith("chrY")) { //TODO: handle restricted Y chromosome (say Y_1_1000) log.warning("Prefix looks like chromosome Y, but might be treated as diploid genome."); return false; } return false; } public boolean isMT() { if (name.equals("MT") || name.equals("chrM")) { return true; } else if (name.startsWith("MT") || name.startsWith("chrM")) { //TODO: handle restricted MT chromosome (say chrM_1_1000) log.warning("Prefix looks like chromosome MT, but might be treated as diploid genome."); return false; } return false; } /** * Checks if the chromosome is haploid. * TODO ignore the alternate contigs for now * * @param gender Gender of individual * @return True if the chromosome is haploid given the sex */ public boolean isHaploid(final GenderType gender) { if (isMT()) { return true; } else if (gender == GenderType.MALE) { return (isX() || isY()); } return false; } @Override public boolean equals(final Object o) { if (this == o) return true; if (!(o instanceof ChrString)) return false; ChrString chrString = (ChrString) o; return name.equals(chrString.name); } @Override public int hashCode() { return name.hashCode(); } @Override public int compareTo(final ChrString other) { return name.compareTo(other.getName()); } }
27.782946
100
0.567801
ad7f5fe6f983d91b41923670eee212703e27cd99
1,802
package Algorithmique.hexGame.view; import Algorithmique.hexGame.model.Cell; import Algorithmique.hexGame.model.HexModel; import javax.swing.*; import java.awt.*; /*................................................................................................................................ . Copyright (c) . . The GamePanel Class was Coded by : Alexandre BOLOT . . Last Modified : 27/12/2019 12:59 . . Contact : [email protected] ...............................................................................................................................*/ /** * Abomnes Gauthier * Bretheau Yann * S3C */ public class GamePanel extends JPanel { public JButton bReturn = new JButton("Retour menu"); private HexModel model; GamePanel(HexModel model) { super(); this.model = model; bReturn.setSize(100, 75); add(bReturn); } @Override public void paint(Graphics g) { super.paint(g); // if(model.getPlayer() == Color.BLUE) currentPlayer.setText("C'est au currentPlayer du bleu!"); // else currentPlayer.setText("C'est au currentPlayer du rouge!"); for (Cell c : this.model.grid) { Graphics2D g2 = (Graphics2D) g; //Cell g2.setColor(c.getColor()); g2.fillPolygon(c); //Bordure Stroke s; if (c.getBorder()) s = new BasicStroke(4f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10.0f); else s = new BasicStroke(1.5f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10.0f); g2.setStroke(s); Color cBordure = new Color(37, 36, 37); g2.setColor(cBordure); g2.drawPolygon(c); revalidate(); repaint(); } } }
27.723077
130
0.508879
063b918a9dcb17810c6b8aa3886a36b35b2e087b
1,799
package filters; // cc InclusiveStopFilterExample Example using a filter to include a stop row import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.InclusiveStopFilter; import org.apache.hadoop.hbase.util.Bytes; import util.HBaseHelper; public class InclusiveStopFilterExample { public static void main(String[] args) throws IOException { Configuration conf = HBaseConfiguration.create(); HBaseHelper helper = HBaseHelper.getHelper(conf); helper.dropTable("testtable"); helper.createTable("testtable", "colfam1"); System.out.println("Adding rows to table..."); helper.fillTable("testtable", 1, 100, 1, "colfam1"); Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("testtable")); // vv InclusiveStopFilterExample Filter filter = new InclusiveStopFilter(Bytes.toBytes("row-5")); Scan scan = new Scan(); scan.setStartRow(Bytes.toBytes("row-3")); scan.setFilter(filter); ResultScanner scanner = table.getScanner(scan); // ^^ InclusiveStopFilterExample System.out.println("Results of scan:"); // vv InclusiveStopFilterExample for (Result result : scanner) { System.out.println(result); } scanner.close(); // ^^ InclusiveStopFilterExample } }
35.27451
77
0.75542
fb4e092b3be8a6c7a4d9567b0d0eb9d56cbe7a3d
1,045
package com.fh.service.news; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.fh.dao.DaoSupport; import com.fh.entity.Page; import com.fh.util.PageData; @Service("newsService") public class NewsService{ @Resource(name = "daoSupport") private DaoSupport dao; //新增 public void save(PageData pd)throws Exception{ dao.save("NewsMapper.save", pd); } //修改 public void edit(PageData pd)throws Exception{ dao.update("NewsMapper.edit", pd); } //通过id获取数据 public PageData findById(PageData pd) throws Exception { return (PageData) dao.findForObject("NewsMapper.findById", pd); } //列出同一父类id下的数据 public List<PageData> dictlistPage(Page page) throws Exception { return (List<PageData>) dao.findForList("NewsMapper.dictlistPage", page); } //删除 public void delete(PageData pd) throws Exception { dao.delete("NewsMapper.delete", pd); } //推送 public void push(PageData pd) throws Exception { dao.delete("NewsMapper.push", pd); } }
19
75
0.722488
36c6961030b601882935db928b008c0a23620669
380
package dkrylov.petprojects.devschool.repository; import dkrylov.petprojects.devschool.model.Student; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * Student repository */ public interface StudentRepository extends JpaRepository<Student, Long>, JpaSpecificationExecutor<Student> { }
31.666667
108
0.839474
cc1a76e85eeef831c66cbfdd35223314dbd595a0
393
package com.eis.broker.repository; import com.eis.broker.entity.QuantityLog; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; public interface QuantityLogRepository extends JpaRepository<QuantityLog, Integer> { Page<QuantityLog> getByProduct(String product, Pageable pageable); }
35.727273
84
0.834606
976d54a0e36b6ad08056675b720f63afeb02e808
3,413
package dao.custom.impl; import dao.CrudUtil; import dao.custom.LecturerDAO; import entity.Lecturer; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class LecturerDAOImpl implements LecturerDAO { @Override public String getLastLecturerId() throws Exception { ResultSet rst = CrudUtil.execute("SELECT id FROM Lecturer ORDER BY id DESC LIMIT 1"); if (rst.next()) { return rst.getString(1); } else { return null; } } @Override public List<Lecturer> findAll() throws Exception { ResultSet rst = CrudUtil.execute("SELECT * FROM Lecturer"); List<Lecturer> lecturers = new ArrayList<>(); while (rst.next()) { lecturers.add(new Lecturer(rst.getString(1), rst.getString(2), rst.getString(3), rst.getString(4), rst.getString(5), rst.getString(6), rst.getString(7), rst.getString(8))); } return lecturers; } @Override public Lecturer find(String key) throws Exception { ResultSet rst = CrudUtil.execute("SELECT * FROM Lecturer WHERE id=?", key); if (rst.next()) { return new Lecturer(rst.getString(1), rst.getString(2), rst.getString(3), rst.getString(4), rst.getString(5), rst.getString(6), rst.getString(7), rst.getString(8) ); } return null; } @Override public boolean delete(String key) throws Exception { return CrudUtil.execute("DELETE FROM Lecturer WHERE id=?",key); } @Override public boolean update(Lecturer lecturer) throws Exception { return CrudUtil.execute("UPDATE Lecturer SET courseId=?, name=?,address=?,contact=?,username=?,password=?,nic=?,email=?,userId=? WHERE id=?", lecturer.getCourseId(),lecturer.getName(),lecturer.getAddress(),lecturer.getContact(),lecturer.getNic(),lecturer.getEmail(),lecturer.getUserId(),lecturer.getId()); } @Override public boolean save(Lecturer lecturer) throws Exception { return CrudUtil.execute("INSERT INTO Lecturer VALUES (?,?,?,?,?,?,?,?)",lecturer.getId(),lecturer.getCourseId(), lecturer.getName(),lecturer.getAddress(),lecturer.getContact(),lecturer.getNic(),lecturer.getEmail(),lecturer.getUserId()); } public String getUserId(String pk) throws Exception { ResultSet resultSet = CrudUtil.execute("SELECT userId FROM LM_System.Lecturer WHERE id=?", pk); if(resultSet.next()){ return resultSet.getString(1); } return null; } public String getLecturerCount() throws Exception{ ResultSet rst = CrudUtil.execute("SELECT COUNT(*) AS Total FROM Lecturer"); if (rst.next()){ return rst.getString(1); }else{ return null; } } public String getLecturerId(String fk) throws Exception { ResultSet resultSet = CrudUtil.execute("SELECT id FROM LM_System.Lecturer WHERE userId=?", fk); if(resultSet.next()){ return resultSet.getString(1); } return null; } }
32.504762
179
0.588046
be7284a4db3bd8f62bbf278568137090785194c6
1,393
package com.wjiec.springaio.webflux.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.time.LocalDateTime; import java.util.Collection; import java.util.Collections; @Data @Builder @Document @NoArgsConstructor @AllArgsConstructor public class User implements UserDetails { @Id private String id; private String username; private String password; private LocalDateTime createdAt; private LocalDateTime updatedAt; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return Collections.singleton(new SimpleGrantedAuthority("ADMIN")); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
22.836066
75
0.713568
2b321f302e09b4ef6524681e45b5746afc30e360
430
package org.googlecode.userapi; import java.util.List; /** * Created by Ildar Karimov * Date: Aug 26, 2009 */ public class ListWithTotal<T> { private List<T> list; private long count; public ListWithTotal(List<T> list, long count) { this.list = list; this.count = count; } public List<T> getList() { return list; } public long getCount() { return count; } }
16.538462
52
0.595349
ebd35af9375cac116fe47f29ac259239896344aa
2,542
package com.javaee.hotel.service; import com.sun.xml.messaging.saaj.packaging.mime.internet.MimeUtility; import org.mybatis.logging.Logger; import org.mybatis.logging.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpSession; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Random; @Service("mailService") public class MailService { @Value("${spring.mail.username}") private String from; @Autowired private JavaMailSender mailSender; Logger logger = LoggerFactory.getLogger(this.getClass()); public void sendSimpleMail(String to,String title,String content){ SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(title); message.setText(content); mailSender.send(message); } public void sendAttachmentsMail(String to, String title, String cotent, List<File> fileList){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message,true); helper.setFrom(from); helper.setTo(to); helper.setSubject(title); helper.setText(cotent); String fileName = null; for (File file:fileList) { fileName = MimeUtility.encodeText(file.getName(), "GB2312", "B"); helper.addAttachment(fileName, file); } } catch (Exception e) { e.printStackTrace(); } mailSender.send(message); } public void sendEmail(String email, HttpSession session){ String checkCode = String.valueOf(new Random().nextInt(899999) + 100000); String message = "您的注册验证码为:"+checkCode; try { sendSimpleMail(email, "注册验证码", message); HashMap hashMap = new HashMap(); Date date = new Date(); hashMap.put("time",date.getTime()); hashMap.put("checkCode",checkCode); session.setAttribute("checkCode",hashMap); }catch (Exception e){ e.toString(); } } }
36.314286
97
0.670338
24df76e0fbfd33290e7a82cee8e1c7777fa1f924
3,578
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.activemq.converter; import java.util.ArrayList; import java.util.List; import javax.jms.Message; import javax.jms.MessageListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; public class ConsumerBean implements MessageListener { private static final Logger LOG = LoggerFactory.getLogger(ConsumerBean.class); private final List<Message> messages = new ArrayList(); private boolean verbose; private String id; public ConsumerBean() { } public List<Message> flushMessages() { List<Message> answer = null; synchronized (this.messages) { answer = new ArrayList(this.messages); this.messages.clear(); return answer; } } public void onMessage(Message message) { synchronized (this.messages) { this.messages.add(message); if (this.verbose) { LOG.info("{} Received: {}", this.id, message); } this.messages.notifyAll(); } } public void waitForMessagesToArrive(int messageCount, long maxWaitTime) { long maxRemainingMessageCount = getRemaining(messageCount); LOG.info("Waiting for ({}) message(s) to arrive", maxRemainingMessageCount); long start = System.currentTimeMillis(); for (long endTime = start + maxWaitTime; maxRemainingMessageCount > 0L; maxRemainingMessageCount = getRemaining( messageCount)) { try { synchronized (this.messages) { this.messages.wait(1000L); } if (this.hasReceivedMessages(messageCount) || System.currentTimeMillis() > endTime) { break; } } catch (InterruptedException var13) { LOG.info("Caught: {}", var13); } } long end = System.currentTimeMillis() - start; LOG.info("End of wait for {} millis", end); } private long getRemaining(int messageCount) { return Math.max(0, messageCount - this.messages.size()); } public void assertMessagesArrived(int total, long maxWaitTime) { this.waitForMessagesToArrive(total, maxWaitTime); synchronized (this.messages) { int count = this.messages.size(); assertEquals((long) total, (long) count, "Messages received"); } } public List<Message> getMessages() { return this.messages; } protected boolean hasReceivedMessages(int messageCount) { synchronized (this.messages) { return this.messages.size() >= messageCount; } } }
33.439252
101
0.64114
ceb0925d0a0acb2a041a796d371f7117e1b9eb94
1,226
package br.com.alura.teste.util; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import br.com.alura.modelo.Conta; import br.com.alura.modelo.ContaCorrente; import br.com.alura.modelo.ContaPoupanca; public class TesteComparatorConta { public static void main(String[] args) { Conta cc1 = new ContaCorrente(22, 33); cc1.deposita(333.0); Conta cc2 = new ContaCorrente(22, 44); cc2.deposita(150.0); Conta cc3 = new ContaCorrente(22, 22); cc3.deposita(111.0); Conta cc4 = new ContaPoupanca(22, 15); cc4.deposita(100.0); List<Conta> lista = new ArrayList<>(); lista.add(cc1); lista.add(cc2); lista.add(cc3); lista.add(cc4); for (Conta conta : lista) { System.out.println(conta); } NumeroDaContaComparator comparator = new NumeroDaContaComparator(); lista.sort(comparator); System.out.println("Ordenado!"); for (Conta conta : lista) { System.out.println(conta); } } } class NumeroDaContaComparator implements Comparator<Conta>{ @Override public int compare(Conta c1, Conta c2) { if(c1.getNumero() > c2.getNumero()) { return 1; }else if(c1.getNumero() < c2.getNumero()) { return -1; } return 0; } }
20.098361
69
0.681077
7a5b556e1be9888af18759de9ef15660dff89c7e
2,022
package me.idarkyy.nanocore.commands; import me.idarkyy.nanocore.constructors.ActionPlayer; import me.idarkyy.nanocore.managers.ConfigurationManager; import me.idarkyy.nanocore.managers.PrivateMessageManager; import net.minecraft.util.org.apache.commons.lang3.StringUtils; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class ReplyCommand implements CommandExecutor { ConfigurationManager config = ConfigurationManager.getManager(); PrivateMessageManager pmManager = PrivateMessageManager.getManager(); @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { if (commandSender instanceof Player) { Player player = (Player) commandSender; ActionPlayer ap = new ActionPlayer(player); if (args.length == 0) { ap.sendMessage(config.getLanguage().getString("PRIVATE_MESSAGE_REPLY_CORRECT_USAGE") .replace("%command%", command.getName()) .replace("%player%", player.getName())); } else { if (pmManager.getLastReply(player) != null) { Player target = pmManager.getLastReply(player); if (((OfflinePlayer) target).isOnline()) { pmManager.privateMessage(player, target, StringUtils.join(args, " ", 0, args.length)); } else { ap.sendMessage(config.getLanguage().getString("NOT_ONLINE") .replace("%player%", ((OfflinePlayer) target).getName())); } } else { ap.sendMessage(config.getLanguage().getString("PRIVATE_MESSAGE_REPLY_DID_NOT_MESSAGE" .replace("%player%", player.getName()))); } } } return false; } }
44.933333
110
0.62364
6394cae6854bbb60fc37f9ebbe3a6769a219d7ad
12,202
package net.minecraft.world.level.block; import com.google.common.base.MoreObjects; import java.util.Random; import javax.annotation.Nullable; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.block.state.properties.DirectionProperty; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; public class TripWireHookBlock extends Block { public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; public static final BooleanProperty POWERED = BlockStateProperties.POWERED; public static final BooleanProperty ATTACHED = BlockStateProperties.ATTACHED; protected static final int WIRE_DIST_MIN = 1; protected static final int WIRE_DIST_MAX = 42; private static final int RECHECK_PERIOD = 10; protected static final int AABB_OFFSET = 3; protected static final VoxelShape NORTH_AABB = Block.box(5.0D, 0.0D, 10.0D, 11.0D, 10.0D, 16.0D); protected static final VoxelShape SOUTH_AABB = Block.box(5.0D, 0.0D, 0.0D, 11.0D, 10.0D, 6.0D); protected static final VoxelShape WEST_AABB = Block.box(10.0D, 0.0D, 5.0D, 16.0D, 10.0D, 11.0D); protected static final VoxelShape EAST_AABB = Block.box(0.0D, 0.0D, 5.0D, 6.0D, 10.0D, 11.0D); public TripWireHookBlock(BlockBehaviour.Properties p_57676_) { super(p_57676_); this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.NORTH).setValue(POWERED, Boolean.valueOf(false)).setValue(ATTACHED, Boolean.valueOf(false))); } public VoxelShape getShape(BlockState pState, BlockGetter pLevel, BlockPos pPos, CollisionContext pContext) { switch((Direction)pState.getValue(FACING)) { case EAST: default: return EAST_AABB; case WEST: return WEST_AABB; case SOUTH: return SOUTH_AABB; case NORTH: return NORTH_AABB; } } public boolean canSurvive(BlockState pState, LevelReader pLevel, BlockPos pPos) { Direction direction = pState.getValue(FACING); BlockPos blockpos = pPos.relative(direction.getOpposite()); BlockState blockstate = pLevel.getBlockState(blockpos); return direction.getAxis().isHorizontal() && blockstate.isFaceSturdy(pLevel, blockpos, direction); } /** * Update the provided state given the provided neighbor direction and neighbor state, returning a new state. * For example, fences make their connections to the passed in state if possible, and wet concrete powder immediately * returns its solidified counterpart. * Note that this method should ideally consider only the specific direction passed in. */ public BlockState updateShape(BlockState pState, Direction pFacing, BlockState pFacingState, LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pFacingPos) { return pFacing.getOpposite() == pState.getValue(FACING) && !pState.canSurvive(pLevel, pCurrentPos) ? Blocks.AIR.defaultBlockState() : super.updateShape(pState, pFacing, pFacingState, pLevel, pCurrentPos, pFacingPos); } @Nullable public BlockState getStateForPlacement(BlockPlaceContext pContext) { BlockState blockstate = this.defaultBlockState().setValue(POWERED, Boolean.valueOf(false)).setValue(ATTACHED, Boolean.valueOf(false)); LevelReader levelreader = pContext.getLevel(); BlockPos blockpos = pContext.getClickedPos(); Direction[] adirection = pContext.getNearestLookingDirections(); for(Direction direction : adirection) { if (direction.getAxis().isHorizontal()) { Direction direction1 = direction.getOpposite(); blockstate = blockstate.setValue(FACING, direction1); if (blockstate.canSurvive(levelreader, blockpos)) { return blockstate; } } } return null; } /** * Called by BlockItem after this block has been placed. */ public void setPlacedBy(Level pLevel, BlockPos pPos, BlockState pState, LivingEntity pPlacer, ItemStack pStack) { this.calculateState(pLevel, pPos, pState, false, false, -1, (BlockState)null); } public void calculateState(Level pLevel, BlockPos pPos, BlockState pHookState, boolean pAttaching, boolean pShouldNotifyNeighbours, int pSearchRange, @Nullable BlockState pState) { Direction direction = pHookState.getValue(FACING); boolean flag = pHookState.getValue(ATTACHED); boolean flag1 = pHookState.getValue(POWERED); boolean flag2 = !pAttaching; boolean flag3 = false; int i = 0; BlockState[] ablockstate = new BlockState[42]; for(int j = 1; j < 42; ++j) { BlockPos blockpos = pPos.relative(direction, j); BlockState blockstate = pLevel.getBlockState(blockpos); if (blockstate.is(Blocks.TRIPWIRE_HOOK)) { if (blockstate.getValue(FACING) == direction.getOpposite()) { i = j; } break; } if (!blockstate.is(Blocks.TRIPWIRE) && j != pSearchRange) { ablockstate[j] = null; flag2 = false; } else { if (j == pSearchRange) { blockstate = MoreObjects.firstNonNull(pState, blockstate); } boolean flag4 = !blockstate.getValue(TripWireBlock.DISARMED); boolean flag5 = blockstate.getValue(TripWireBlock.POWERED); flag3 |= flag4 && flag5; ablockstate[j] = blockstate; if (j == pSearchRange) { pLevel.scheduleTick(pPos, this, 10); flag2 &= flag4; } } } flag2 &= i > 1; flag3 &= flag2; BlockState blockstate1 = this.defaultBlockState().setValue(ATTACHED, Boolean.valueOf(flag2)).setValue(POWERED, Boolean.valueOf(flag3)); if (i > 0) { BlockPos blockpos1 = pPos.relative(direction, i); Direction direction1 = direction.getOpposite(); pLevel.setBlock(blockpos1, blockstate1.setValue(FACING, direction1), 3); this.notifyNeighbors(pLevel, blockpos1, direction1); this.playSound(pLevel, blockpos1, flag2, flag3, flag, flag1); } this.playSound(pLevel, pPos, flag2, flag3, flag, flag1); if (!pAttaching) { pLevel.setBlock(pPos, blockstate1.setValue(FACING, direction), 3); if (pShouldNotifyNeighbours) { this.notifyNeighbors(pLevel, pPos, direction); } } if (flag != flag2) { for(int k = 1; k < i; ++k) { BlockPos blockpos2 = pPos.relative(direction, k); BlockState blockstate2 = ablockstate[k]; if (blockstate2 != null) { if (!pLevel.getBlockState(blockpos2).isAir()) { // FORGE: fix MC-129055 pLevel.setBlock(blockpos2, blockstate2.setValue(ATTACHED, Boolean.valueOf(flag2)), 3); } } } } } public void tick(BlockState pState, ServerLevel pLevel, BlockPos pPos, Random pRandom) { this.calculateState(pLevel, pPos, pState, false, true, -1, (BlockState)null); } private void playSound(Level pLevel, BlockPos pPos, boolean pAttaching, boolean pActivated, boolean pDetaching, boolean pDeactivating) { if (pActivated && !pDeactivating) { pLevel.playSound((Player)null, pPos, SoundEvents.TRIPWIRE_CLICK_ON, SoundSource.BLOCKS, 0.4F, 0.6F); pLevel.gameEvent(GameEvent.BLOCK_PRESS, pPos); } else if (!pActivated && pDeactivating) { pLevel.playSound((Player)null, pPos, SoundEvents.TRIPWIRE_CLICK_OFF, SoundSource.BLOCKS, 0.4F, 0.5F); pLevel.gameEvent(GameEvent.BLOCK_UNPRESS, pPos); } else if (pAttaching && !pDetaching) { pLevel.playSound((Player)null, pPos, SoundEvents.TRIPWIRE_ATTACH, SoundSource.BLOCKS, 0.4F, 0.7F); pLevel.gameEvent(GameEvent.BLOCK_ATTACH, pPos); } else if (!pAttaching && pDetaching) { pLevel.playSound((Player)null, pPos, SoundEvents.TRIPWIRE_DETACH, SoundSource.BLOCKS, 0.4F, 1.2F / (pLevel.random.nextFloat() * 0.2F + 0.9F)); pLevel.gameEvent(GameEvent.BLOCK_DETACH, pPos); } } private void notifyNeighbors(Level pLevel, BlockPos pPos, Direction pDirection) { pLevel.updateNeighborsAt(pPos, this); pLevel.updateNeighborsAt(pPos.relative(pDirection.getOpposite()), this); } public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) { if (!pIsMoving && !pState.is(pNewState.getBlock())) { boolean flag = pState.getValue(ATTACHED); boolean flag1 = pState.getValue(POWERED); if (flag || flag1) { this.calculateState(pLevel, pPos, pState, true, false, -1, (BlockState)null); } if (flag1) { pLevel.updateNeighborsAt(pPos, this); pLevel.updateNeighborsAt(pPos.relative(pState.getValue(FACING).getOpposite()), this); } super.onRemove(pState, pLevel, pPos, pNewState, pIsMoving); } } /** * @deprecated call via {@link net.minecraft.world.level.block.state.BlockBehavior.BlockStateBase#getSignal} whenever * possible. Implementing/overriding is fine. */ public int getSignal(BlockState pBlockState, BlockGetter pBlockAccess, BlockPos pPos, Direction pSide) { return pBlockState.getValue(POWERED) ? 15 : 0; } /** * @deprecated call via {@link net.minecraft.world.level.block.state.BlockBehavior.BlockStateBase#getDirectSignal} * whenever possible. Implementing/overriding is fine. */ public int getDirectSignal(BlockState pBlockState, BlockGetter pBlockAccess, BlockPos pPos, Direction pSide) { if (!pBlockState.getValue(POWERED)) { return 0; } else { return pBlockState.getValue(FACING) == pSide ? 15 : 0; } } /** * Can this block provide power. Only wire currently seems to have this change based on its state. * @deprecated call via {@link net.minecraft.world.level.block.state.BlockBehavior.BlockStateBase#isSignalSource} * whenever possible. Implementing/overriding is fine. */ public boolean isSignalSource(BlockState pState) { return true; } /** * Returns the blockstate with the given rotation from the passed blockstate. If inapplicable, returns the passed * blockstate. * @deprecated call via {@link net.minecraft.world.level.block.state.BlockBehavior.BlockStateBase#rotate} whenever * possible. Implementing/overriding is fine. */ public BlockState rotate(BlockState pState, Rotation pRotation) { return pState.setValue(FACING, pRotation.rotate(pState.getValue(FACING))); } /** * Returns the blockstate with the given mirror of the passed blockstate. If inapplicable, returns the passed * blockstate. * @deprecated call via {@link net.minecraft.world.level.block.state.BlockBehavior.BlockStateBase#mirror} whenever * possible. Implementing/overriding is fine. */ public BlockState mirror(BlockState pState, Mirror pMirror) { return pState.rotate(pMirror.getRotation(pState.getValue(FACING))); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) { pBuilder.add(FACING, POWERED, ATTACHED); } }
44.860294
222
0.695296
f0b33b4bf8309e52cd561bea761dfe5b2c6f0b79
722
package codewars; import challenges.BinarySearch; import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class InsaneColouredTrianglesTest { @Test public void examples() { assertEquals('B', InsaneColouredTriangles.triangle("B")); assertEquals('R', InsaneColouredTriangles.triangle("GB")); assertEquals('R', InsaneColouredTriangles.triangle("RRR")); assertEquals('B', InsaneColouredTriangles.triangle("RGBG")); // assertEquals('G', InsaneColouredTriangles.triangle("RBRGBRB")); // assertEquals('G', InsaneColouredTriangles.triangle("RBRGBRBGGRRRBGBBBGG")); } }
32.818182
84
0.67313
7fe3fbfe13ed357fe760157cc46f4c86354c0380
4,735
// Copyright 2007-2021 Information & Computational Sciences, JHI. All rights // reserved. Use is subject to the accompanying licence terms. package jhi.flapjack.gui.visualization; import java.awt.*; import java.text.*; import jhi.flapjack.data.*; import jhi.flapjack.gui.*; import jhi.flapjack.gui.table.*; public class TablePanelTableModel extends LineDataTableModel { private final GTViewSet viewSet; private DecimalFormat df = new DecimalFormat("0.00"); // Variables for tracking where columns are in the table private int padIndex = -1; private int lineScoreIndex = -1; private int traitsOffset = -1; private int linkedOffset = -1; private int[] traitsModelCols; private int[] linkedModelCols; private LineDataTableModel traitsModel; private LineDataTableModel linkedModel; public TablePanelTableModel(GTViewSet viewSet) { this.viewSet = viewSet; // In the basic case (just showing line names) we only have one column int noCols = 1; columnNames = new String[noCols]; columnNames[0] = "Line"; if (viewSet != null) { lines = viewSet.getLines(); // Grab the linked model and the column indices we need from that model linkedModelCols = viewSet.getLinkedModelCols(); traitsModelCols = viewSet.getTxtTraits(); linkedModel = viewSet.tableHandler().model(); traitsModel = Flapjack.winMain.getNavPanel().getTraitsPanel(viewSet.getDataSet(), false).getTraitsTab(false).getModel(); // If we have line scores, or linked model columns we need to // add more columns to our table model if (viewSet.getDisplayLineScores() || traitsModelCols.length > 0 || linkedModelCols.length > 0 ) // <------------------------- UNCOMMENT FOR TRAITS { // Add an extra column for the padding column padIndex = 1; noCols++; // Setup the line score index if (viewSet.getDisplayLineScores()) { lineScoreIndex = noCols; noCols++; } if (traitsModelCols.length > 0) // <------------------------- UNCOMMENT FOR TRAITS { traitsOffset = noCols; noCols += traitsModelCols.length; } // Setup the linked table start index (and offset within the // linked columns) based on the column indices in this class if (linkedModelCols.length > 0) { linkedOffset = noCols; noCols += linkedModelCols.length; } } columnNames = new String[noCols]; columnNames[0] = "Line"; if (padIndex != -1) columnNames[1] = ""; if (lineScoreIndex != -1) columnNames[lineScoreIndex] = "Sort score"; if (traitsOffset != -1) for (int i = 0; i < traitsModelCols.length; i++) columnNames[i + traitsOffset] = viewSet.getDataSet().getTraits().get(traitsModelCols[i]).getName(); if (linkedOffset != -1) for (int i = 0; i < linkedModelCols.length; i++) columnNames[i + linkedOffset] = viewSet.tableHandler().model().getColumnName(linkedModelCols[i]); } } @Override public String getColumnName(int col) { return columnNames[col]; } @Override public int getRowCount() { return viewSet == null ? 0 : lines.size(); } @Override public Object getObjectAt(int row, int col) { LineInfo line = lines.get(row); if (col == 0) return line; else if (linkedOffset != -1 && col >= linkedOffset) return linkedModel.getObjectForLine( line, linkedModelCols[col - linkedOffset]); else if (traitsOffset != -1 && col >= traitsOffset) { // Special lines (splitters, etc) have no traits if (line.getLine().getTraitValues().size() > 0) return line.getLine().getTraitValues().get( traitsModelCols[col - traitsOffset]).tableValue(); } else if (col == lineScoreIndex) return df.format(lines.get(row).getScore()); return ""; } @Override public Class<?> getObjectColumnClass(int col) { if (col == 0) return LineInfo.class; else if (linkedOffset != -1 && col >= linkedOffset) return linkedModel.getObjectColumnClass(linkedModelCols[col - linkedOffset]); else if (traitsOffset != -1 && col >= traitsOffset) return traitsModel.getColumnClass(traitsModelCols[col - traitsOffset]); else if (col == lineScoreIndex) return Double.class; return String.class; } public Color getDisplayColor(int row, int col) { if (col == 0) return null; else if (linkedOffset != -1 && col >= linkedOffset) return linkedModel.getDisplayColor(row, linkedModelCols[col - linkedOffset]); else if (traitsOffset != -1 && col >= traitsOffset) return traitsModel.getDisplayColor(row, traitsModelCols[col - traitsOffset]); return null; } }
28.184524
157
0.655544
5fd458eaf2cdcec5a37ed858a0f9ec5e164dd916
384
package assignments; public class assign4 { public static void main(String[] args) { System.out.println("Test Data"); int a = -5+8*6; System.out.println("a. " +a); int b = (55+9) %9; System.out.println("b. " + b); int c = 20+ -3*5/8; System.out.println("c. " + c); int d = 5+15/3*2-8%3; System.out.println("d. " + d); } }
16.695652
42
0.513021
9588258bc31b246bfaf61e959c369b9489cd873f
953
package JavaSyntaxExercises; import java.util.Arrays; import java.util.Scanner; public class MaxSequenceOfIncreasingElements { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] numbers = Arrays.stream(scanner.nextLine() .split("\\s+")) .mapToInt(Integer::parseInt) .toArray(); int counter=0; int maxSequence=0; int endIndex=0; for (int i = 0; i < numbers.length-1; i++) { if(numbers[i+1]>numbers[i]){ counter++; if(counter>maxSequence){ maxSequence=counter; endIndex=i+1; } }else{ counter=0; } } int startIndex=endIndex-maxSequence; for (int i =startIndex; i<=endIndex; i++ ){ System.out.printf("%d ", numbers[i]); } } }
26.472222
56
0.498426
4613c47a8af0e43b12feca95c50cb1afc3b88b88
14,187
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.atomix.core.impl; import io.atomix.cluster.ClusterMembershipService; import io.atomix.cluster.messaging.ClusterCommunicationService; import io.atomix.cluster.messaging.ClusterEventService; import io.atomix.core.AtomixRegistry; import io.atomix.core.ManagedPrimitivesService; import io.atomix.core.PrimitivesService; import io.atomix.core.barrier.DistributedCyclicBarrier; import io.atomix.core.barrier.DistributedCyclicBarrierType; import io.atomix.core.counter.AtomicCounter; import io.atomix.core.counter.AtomicCounterType; import io.atomix.core.counter.DistributedCounter; import io.atomix.core.counter.DistributedCounterType; import io.atomix.core.election.LeaderElection; import io.atomix.core.election.LeaderElectionType; import io.atomix.core.election.LeaderElector; import io.atomix.core.election.LeaderElectorType; import io.atomix.core.idgenerator.AtomicIdGenerator; import io.atomix.core.idgenerator.AtomicIdGeneratorType; import io.atomix.core.list.DistributedList; import io.atomix.core.list.DistributedListType; import io.atomix.core.lock.AtomicLock; import io.atomix.core.lock.AtomicLockType; import io.atomix.core.lock.DistributedLock; import io.atomix.core.lock.DistributedLockType; import io.atomix.core.map.AtomicCounterMap; import io.atomix.core.map.AtomicCounterMapType; import io.atomix.core.map.AtomicMap; import io.atomix.core.map.AtomicMapType; import io.atomix.core.map.AtomicNavigableMap; import io.atomix.core.map.AtomicNavigableMapType; import io.atomix.core.map.AtomicSortedMap; import io.atomix.core.map.AtomicSortedMapType; import io.atomix.core.map.DistributedMap; import io.atomix.core.map.DistributedMapType; import io.atomix.core.map.DistributedNavigableMap; import io.atomix.core.map.DistributedNavigableMapType; import io.atomix.core.map.DistributedSortedMap; import io.atomix.core.map.DistributedSortedMapType; import io.atomix.core.multimap.AtomicMultimap; import io.atomix.core.multimap.AtomicMultimapType; import io.atomix.core.multimap.DistributedMultimap; import io.atomix.core.multimap.DistributedMultimapType; import io.atomix.core.multiset.DistributedMultiset; import io.atomix.core.multiset.DistributedMultisetType; import io.atomix.core.queue.DistributedQueue; import io.atomix.core.queue.DistributedQueueType; import io.atomix.core.semaphore.AtomicSemaphore; import io.atomix.core.semaphore.AtomicSemaphoreType; import io.atomix.core.semaphore.DistributedSemaphore; import io.atomix.core.semaphore.DistributedSemaphoreType; import io.atomix.core.set.DistributedNavigableSet; import io.atomix.core.set.DistributedNavigableSetType; import io.atomix.core.set.DistributedSet; import io.atomix.core.set.DistributedSetType; import io.atomix.core.set.DistributedSortedSet; import io.atomix.core.set.DistributedSortedSetType; import io.atomix.core.transaction.ManagedTransactionService; import io.atomix.core.transaction.TransactionBuilder; import io.atomix.core.transaction.TransactionConfig; import io.atomix.core.transaction.TransactionService; import io.atomix.core.transaction.impl.DefaultTransactionBuilder; import io.atomix.core.tree.AtomicDocumentTree; import io.atomix.core.tree.AtomicDocumentTreeType; import io.atomix.core.value.AtomicValue; import io.atomix.core.value.AtomicValueType; import io.atomix.core.value.DistributedValue; import io.atomix.core.value.DistributedValueType; import io.atomix.core.workqueue.WorkQueue; import io.atomix.core.workqueue.WorkQueueType; import io.atomix.primitive.ManagedPrimitiveRegistry; import io.atomix.primitive.PrimitiveBuilder; import io.atomix.primitive.PrimitiveCache; import io.atomix.primitive.PrimitiveInfo; import io.atomix.primitive.PrimitiveManagementService; import io.atomix.primitive.PrimitiveType; import io.atomix.primitive.SyncPrimitive; import io.atomix.primitive.config.ConfigService; import io.atomix.primitive.config.PrimitiveConfig; import io.atomix.primitive.impl.DefaultPrimitiveTypeRegistry; import io.atomix.primitive.partition.PartitionGroup; import io.atomix.primitive.partition.PartitionService; import io.atomix.primitive.partition.impl.DefaultPartitionGroupTypeRegistry; import io.atomix.primitive.protocol.PrimitiveProtocol; import io.atomix.primitive.protocol.impl.DefaultPrimitiveProtocolTypeRegistry; import io.atomix.primitive.serialization.SerializationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import static com.google.common.base.Preconditions.checkNotNull; /** * Default primitives service. */ public class CorePrimitivesService implements ManagedPrimitivesService { private static final Logger LOGGER = LoggerFactory.getLogger(CorePrimitivesService.class); private final PrimitiveManagementService managementService; private final ManagedPrimitiveRegistry primitiveRegistry; private final ManagedTransactionService transactionService; private final ConfigService configService; private final PrimitiveCache cache; private final AtomixRegistry registry; private final AtomicBoolean started = new AtomicBoolean(); public CorePrimitivesService( ScheduledExecutorService executorService, ClusterMembershipService membershipService, ClusterCommunicationService communicationService, ClusterEventService eventService, SerializationService serializationService, PartitionService partitionService, PrimitiveCache primitiveCache, AtomixRegistry registry, ConfigService configService) { this.cache = checkNotNull(primitiveCache); this.registry = checkNotNull(registry); this.primitiveRegistry = new CorePrimitiveRegistry(partitionService, new DefaultPrimitiveTypeRegistry(registry.getTypes(PrimitiveType.class))); this.managementService = new CorePrimitiveManagementService( executorService, membershipService, communicationService, eventService, serializationService, partitionService, primitiveCache, primitiveRegistry, new DefaultPrimitiveTypeRegistry(registry.getTypes(PrimitiveType.class)), new DefaultPrimitiveProtocolTypeRegistry(registry.getTypes(PrimitiveProtocol.Type.class)), new DefaultPartitionGroupTypeRegistry(registry.getTypes(PartitionGroup.Type.class))); this.transactionService = new CoreTransactionService(managementService); this.configService = checkNotNull(configService); } /** * Returns the primitive transaction service. * * @return the primitive transaction service */ public TransactionService transactionService() { return transactionService; } @Override public TransactionBuilder transactionBuilder(String name) { return new DefaultTransactionBuilder(name, new TransactionConfig(), managementService, transactionService); } @Override public <K, V> DistributedMap<K, V> getMap(String name) { return getPrimitive(name, DistributedMapType.instance()); } @Override public <K extends Comparable<K>, V> DistributedSortedMap<K, V> getSortedMap(String name) { return getPrimitive(name, DistributedSortedMapType.instance()); } @Override public <K extends Comparable<K>, V> DistributedNavigableMap<K, V> getNavigableMap(String name) { return getPrimitive(name, DistributedNavigableMapType.instance()); } @Override public <K, V> DistributedMultimap<K, V> getMultimap(String name) { return getPrimitive(name, DistributedMultimapType.instance()); } @Override public <K, V> AtomicMap<K, V> getAtomicMap(String name) { return getPrimitive(name, AtomicMapType.instance()); } @Override public <V> AtomicDocumentTree<V> getAtomicDocumentTree(String name) { return getPrimitive(name, AtomicDocumentTreeType.instance()); } @Override public <K extends Comparable<K>, V> AtomicSortedMap<K, V> getAtomicSortedMap(String name) { return getPrimitive(name, AtomicSortedMapType.instance()); } @Override public <K extends Comparable<K>, V> AtomicNavigableMap<K, V> getAtomicNavigableMap(String name) { return getPrimitive(name, AtomicNavigableMapType.instance()); } @Override public <K, V> AtomicMultimap<K, V> getAtomicMultimap(String name) { return getPrimitive(name, AtomicMultimapType.instance()); } @Override public <K> AtomicCounterMap<K> getAtomicCounterMap(String name) { return getPrimitive(name, AtomicCounterMapType.instance()); } @Override public <E> DistributedSet<E> getSet(String name) { return getPrimitive(name, DistributedSetType.instance()); } @Override public <E extends Comparable<E>> DistributedSortedSet<E> getSortedSet(String name) { return getPrimitive(name, DistributedSortedSetType.instance()); } @Override public <E extends Comparable<E>> DistributedNavigableSet<E> getNavigableSet(String name) { return getPrimitive(name, DistributedNavigableSetType.instance()); } @Override public <E> DistributedQueue<E> getQueue(String name) { return getPrimitive(name, DistributedQueueType.instance()); } @Override public <E> DistributedList<E> getList(String name) { return getPrimitive(name, DistributedListType.instance()); } @Override public <E> DistributedMultiset<E> getMultiset(String name) { return getPrimitive(name, DistributedMultisetType.instance()); } @Override public DistributedCounter getCounter(String name) { return getPrimitive(name, DistributedCounterType.instance()); } @Override public AtomicCounter getAtomicCounter(String name) { return getPrimitive(name, AtomicCounterType.instance()); } @Override public AtomicIdGenerator getAtomicIdGenerator(String name) { return getPrimitive(name, AtomicIdGeneratorType.instance()); } @Override public <V> DistributedValue<V> getValue(String name) { return getPrimitive(name, DistributedValueType.instance()); } @Override public <V> AtomicValue<V> getAtomicValue(String name) { return getPrimitive(name, AtomicValueType.instance()); } @Override public <T> LeaderElection<T> getLeaderElection(String name) { return getPrimitive(name, LeaderElectionType.instance()); } @Override public <T> LeaderElector<T> getLeaderElector(String name) { return getPrimitive(name, LeaderElectorType.instance()); } @Override public DistributedLock getLock(String name) { return getPrimitive(name, DistributedLockType.instance()); } @Override public AtomicLock getAtomicLock(String name) { return getPrimitive(name, AtomicLockType.instance()); } @Override public DistributedCyclicBarrier getCyclicBarrier(String name) { return getPrimitive(name, DistributedCyclicBarrierType.instance()); } @Override public DistributedSemaphore getSemaphore(String name) { return getPrimitive(name, DistributedSemaphoreType.instance()); } @Override public AtomicSemaphore getAtomicSemaphore(String name) { return getPrimitive(name, AtomicSemaphoreType.instance()); } @Override public <E> WorkQueue<E> getWorkQueue(String name) { return getPrimitive(name, WorkQueueType.instance()); } @Override public PrimitiveType getPrimitiveType(String typeName) { return registry.getType(PrimitiveType.class, typeName); } @Override public <B extends PrimitiveBuilder<B, C, P>, C extends PrimitiveConfig<C>, P extends SyncPrimitive> B primitiveBuilder( String name, PrimitiveType<B, C, P> primitiveType) { return primitiveType.newBuilder(name, configService.getConfig(name, primitiveType), managementService); } @Override @SuppressWarnings("unchecked") public <P extends SyncPrimitive> CompletableFuture<P> getPrimitiveAsync(String name, PrimitiveType<?, ?, P> primitiveType) { return getPrimitiveAsync(name, (PrimitiveType) primitiveType, null); } @Override @SuppressWarnings("unchecked") public <C extends PrimitiveConfig<C>, P extends SyncPrimitive> CompletableFuture<P> getPrimitiveAsync( String name, PrimitiveType<?, C, P> primitiveType, C primitiveConfig) { return cache.getPrimitive(name, () -> { C config = primitiveConfig; if (config == null) { config = configService.getConfig(name, primitiveType); } return primitiveType.newBuilder(name, config, managementService).buildAsync(); }); } @Override public Collection<PrimitiveInfo> getPrimitives() { return managementService.getPrimitiveRegistry().getPrimitives(); } @Override public Collection<PrimitiveInfo> getPrimitives(PrimitiveType primitiveType) { return managementService.getPrimitiveRegistry().getPrimitives(primitiveType); } @Override public CompletableFuture<PrimitivesService> start() { return primitiveRegistry.start() .thenCompose(v -> transactionService.start()) .thenRun(() -> { LOGGER.info("Started"); started.set(true); }) .thenApply(v -> this); } @Override public boolean isRunning() { return started.get(); } @Override public CompletableFuture<Void> stop() { return transactionService.stop().exceptionally(throwable -> { LOGGER.error("Failed stopping transaction service", throwable); return null; }).thenCompose(v -> primitiveRegistry.stop()).exceptionally(throwable -> { LOGGER.error("Failed stopping primitive registry", throwable); return null; }).whenComplete((r, e) -> { started.set(false); LOGGER.info("Stopped"); }); } }
36.849351
147
0.779728