hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
923a13cc2630e60338c0381404990275a8ab0b68
1,065
java
Java
core/src/main/java/com/project/core/models/impl/UserJsonImpl.java
Suraj-Chandiramani26/advanced_aem
9856ce55514aae6f554c3d5d78f058995bcdccfe
[ "Apache-2.0" ]
1
2022-03-24T19:51:38.000Z
2022-03-24T19:51:38.000Z
core/src/main/java/com/project/core/models/impl/UserJsonImpl.java
Suraj-Chandiramani26/advanced_aem
9856ce55514aae6f554c3d5d78f058995bcdccfe
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/project/core/models/impl/UserJsonImpl.java
Suraj-Chandiramani26/advanced_aem
9856ce55514aae6f554c3d5d78f058995bcdccfe
[ "Apache-2.0" ]
null
null
null
30.428571
83
0.770892
999,062
package com.project.core.models.impl; import com.project.core.models.UserJson; import com.project.core.services.SingleUserOsgi; import com.project.core.utils.JSONLoaders; import org.apache.sling.api.resource.Resource; import org.apache.sling.models.annotations.DefaultInjectionStrategy; import org.apache.sling.models.annotations.Model; import org.apache.sling.models.annotations.injectorspecific.OSGiService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; @Model(adaptables = Resource.class, adapters = UserJson.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL) public class UserJsonImpl implements UserJson { @OSGiService SingleUserOsgi singleUserOsgi; final Logger LOG = LoggerFactory.getLogger(UserJson.class); @Inject String url; @Override public String getUrl(String initialPath){ return initialPath+url; } @Override public String getMessage() { return JSONLoaders.readJson(getUrl(singleUserOsgi.getUserLinkData())); } }
923a14c1169b7c04475e20fe2c72012018966a0b
45,905
java
Java
midolman/src/test/java/org/midonet/cluster/data/neutron/DataCheckPointTest.java
alvico/midonet
2fa26a5c08fddd297d0806421cb1d62144308961
[ "Apache-2.0" ]
1
2015-05-19T08:36:55.000Z
2015-05-19T08:36:55.000Z
midolman/src/test/java/org/midonet/cluster/data/neutron/DataCheckPointTest.java
alvico/midonet
2fa26a5c08fddd297d0806421cb1d62144308961
[ "Apache-2.0" ]
null
null
null
midolman/src/test/java/org/midonet/cluster/data/neutron/DataCheckPointTest.java
alvico/midonet
2fa26a5c08fddd297d0806421cb1d62144308961
[ "Apache-2.0" ]
null
null
null
37.806425
92
0.594941
999,063
/* * Copyright 2014 Midokura SARL * * 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.midonet.cluster.data.neutron; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.UUID; import com.google.common.base.Objects; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.apache.commons.configuration.HierarchicalConfiguration; import org.apache.zookeeper.KeeperException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.midonet.cluster.DataClient; import org.midonet.cluster.config.ZookeeperConfig; import org.midonet.cluster.data.Chain; import org.midonet.cluster.data.IpAddrGroup; import org.midonet.cluster.data.Rule; import org.midonet.cluster.data.rules.ForwardNatRule; import org.midonet.cluster.data.rules.JumpRule; import org.midonet.midolman.Setup; import org.midonet.midolman.guice.cluster.TestDataClientModule; import org.midonet.midolman.guice.config.ConfigProviderModule; import org.midonet.midolman.guice.serialization.SerializationModule; import org.midonet.midolman.guice.zookeeper.MockZookeeperConnectionModule; import org.midonet.midolman.rules.Condition; import org.midonet.midolman.rules.NatTarget; import org.midonet.midolman.rules.RuleResult; import org.midonet.midolman.serialization.SerializationException; import org.midonet.midolman.state.CheckpointedDirectory; import org.midonet.midolman.state.CheckpointedMockDirectory; import org.midonet.midolman.state.Directory; import org.midonet.midolman.state.StateAccessException; import org.midonet.midolman.state.zkManagers.BridgeZkManager; import org.midonet.midolman.version.guice.VersionModule; import org.midonet.packets.ARP; public class DataCheckPointTest { @Inject NeutronPlugin plugin; @Inject DataClient dataClient; Injector injector = null; String zkRoot = "/test"; HierarchicalConfiguration fillConfig(HierarchicalConfiguration config) { config.addNodes(ZookeeperConfig.GROUP_NAME, Arrays.asList(new HierarchicalConfiguration.Node( "midolman_root_key", zkRoot))); return config; } CheckpointedDirectory zkDir() { return injector.getInstance(CheckpointedDirectory.class); } /* * Simple utility functions used in UT to test types of rules. */ public static <T extends Rule.Data, U extends Rule<T, U>> boolean isDropAllExceptArpRule(Rule<T, U> rule) { if (rule == null) { return false; } Condition cond = rule.getCondition(); if (cond == null) { return false; } if (!cond.etherType.equals(new Integer(ARP.ETHERTYPE))) { return false; } if (!(cond.invDlType)) { return false; } if (!Objects.equal(rule.getAction(), RuleResult.Action.DROP)) { return false; } return true; } public static <T extends Rule.Data, U extends Rule<T, U>> boolean isMacSpoofProtectionRule(String macAddress, Rule<T, U> rule) { if (rule == null) { return false; } Condition cond = rule.getCondition(); if (cond == null) { return false; } if (!cond.invDlSrc) { return false; } if (!Objects.equal(cond.ethSrc.toString(), macAddress)) { return false; } if (!Objects.equal(rule.getAction(), RuleResult.Action.DROP)) { return false; } return true; } public static <T extends Rule.Data, U extends Rule<T, U>> boolean isIpSpoofProtectionRule(IPAllocation subnet, Rule<T, U> rule) { if (rule == null) { return false; } Condition cond = rule.getCondition(); if (cond == null) { return false; } if (!cond.nwSrcInv) { return false; } String subnetStr = cond.nwSrcIp.getAddress().toString(); if (!Objects.equal(subnetStr, subnet.ipAddress)) { return false; } if (!Objects.equal(rule.getAction(), RuleResult.Action.DROP)) { return false; } return true; } public static boolean isAcceptReturnFlowRule(Rule<?, ?> rule) { if (rule == null) { return false; } Condition cond = rule.getCondition(); if (cond == null) { return false; } if (!cond.matchReturnFlow) { return false; } if (!Objects.equal(rule.getAction(), RuleResult.Action.ACCEPT)) { return false; } return true; } public Network createStockNetwork() { Network network = new Network(); network.adminStateUp = true; network.name = "net"; network.tenantId = "tenant"; network.shared = true; network.id = UUID.randomUUID(); return network; } public Subnet createStockSubnet() { Subnet subnet = new Subnet(); subnet.cidr = "10.0.0.0/24"; List<String> nss = new ArrayList<>(); nss.add("10.0.0.1"); nss.add("10.0.1.1"); nss.add("10.0.2.1"); List<Route> routes = new ArrayList<>(); Route r = new Route(); r.destination = "10.1.1.1"; r.nexthop = "10.1.1.2"; Route r2 = new Route(); r2.destination = "192.168.3.11"; r2.nexthop = "192.168.3.11"; routes.add(r); routes.add(r2); subnet.dnsNameservers = nss; subnet.hostRoutes = routes; subnet.enableDhcp = true; subnet.gatewayIp = "10.0.0.1"; subnet.ipVersion = 4; subnet.name = "sub"; subnet.tenantId = "tenant"; subnet.id = UUID.randomUUID(); return subnet; } public Port createStockPort(UUID subnetId, UUID networkId, UUID defaultSgId) { Port port = new Port(); port.adminStateUp = true; List<IPAllocation> ips = new ArrayList<>(); IPAllocation ip = new IPAllocation(); ip.ipAddress = "10.0.0.10"; ip.subnetId = subnetId; ips.add(ip); List<UUID> secGroups = new ArrayList<>(); if (defaultSgId != null) { secGroups.add(defaultSgId); } port.fixedIps = ips; port.tenantId = "tenant"; port.networkId = networkId; port.macAddress = "aa:bb:cc:00:11:22"; port.securityGroups = secGroups; port.id = UUID.randomUUID(); return port; } public SecurityGroup createStockSecurityGroup() { SecurityGroup sg = new SecurityGroup(); sg.description = "block stuff"; sg.tenantId = "tenant"; sg.id = UUID.randomUUID(); sg.name = "nameOfSg"; SecurityGroupRule sgr1 = new SecurityGroupRule(); sgr1.direction = RuleDirection.INGRESS; sgr1.ethertype = RuleEthertype.IPv4; sgr1.securityGroupId = sg.id; sgr1.id = UUID.randomUUID(); SecurityGroupRule sgr2 = new SecurityGroupRule(); sgr2.direction = RuleDirection.INGRESS; sgr2.ethertype = RuleEthertype.IPv4; sgr2.securityGroupId = sg.id; sgr2.id = UUID.randomUUID(); sg.securityGroupRules = new ArrayList<>(); sg.securityGroupRules.add(sgr1); sg.securityGroupRules.add(sgr2); return sg; } public Router createStockRouter() { Router r = new Router(); r.id = UUID.randomUUID(); r.externalGatewayInfo = new ExternalGatewayInfo(); r.adminStateUp = true; r.tenantId = "tenant"; return r; } public RouterInterface createStockRouterInterface(UUID portId, UUID subnetId) throws StateAccessException { RouterInterface ri = new RouterInterface(); ri.id = UUID.randomUUID(); ri.portId = portId; ri.subnetId = subnetId; return ri; } public void verifyIpAddrGroups() throws StateAccessException, SerializationException { List<IpAddrGroup> ipgs = dataClient.ipAddrGroupsGetAll(); List<Port> ports = plugin.getPorts(); // Each Ip under the ipaddr groups needs to be associated with a port for (IpAddrGroup ipg : ipgs) { Set<String> ips = dataClient.getAddrsByIpAddrGroup(ipg.getId()); for (String ip : ips) { boolean found = false; for (Port port : ports) { if (port.securityGroups.contains(ipg.getId())) { for (IPAllocation ipAllocation : port.fixedIps) { if (ipAllocation.ipAddress.equals(ip)) { found = true; } } } } Assert.assertTrue(found); } } } public void verifySGRules(Port port) throws StateAccessException, SerializationException { // Ensure that the port has both of its INBOUND and OUTBOUND chains. Chain inbound = null, outbound = null; for (Chain c : dataClient.chainsGetAll()) { String cName = c.getName(); if (cName == null) { continue; } if (cName.contains("INBOUND") && cName .contains(port.id.toString())) { inbound = c; } else if (cName.contains("OUTBOUND") && cName .contains(port.id.toString())) { outbound = c; } } Assert.assertNotNull(inbound); Assert.assertNotNull(outbound); List<Rule<?, ?>> inboundRules = dataClient.rulesFindByChain(inbound.getId()); List<Rule<?, ?>> outboundRules = dataClient.rulesFindByChain(outbound.getId()); Assert.assertTrue(isAcceptReturnFlowRule(outboundRules.get(0))); Assert.assertTrue(isDropAllExceptArpRule( outboundRules.get(outboundRules.size() - 1))); List<Rule<?, ?>> spoofRules = inboundRules.subList(0, port.fixedIps.size()); for (IPAllocation ip : port.fixedIps) { // verify the rule exists boolean found = false; for (Rule<?, ?> r : spoofRules) { if (isIpSpoofProtectionRule(ip, r)) { found = true; break; } } Assert.assertTrue(found); } Assert.assertTrue(isMacSpoofProtectionRule(port.macAddress, inboundRules.get( spoofRules.size()))); Assert.assertTrue( isAcceptReturnFlowRule(inboundRules.get(spoofRules.size() + 1))); List<Rule<?, ?>> sgJumpRulesInbound = inboundRules.subList(spoofRules.size() + 2, inboundRules.size() - 1); // TODO: FAILS //Assert.assertEquals(sgJumpRulesInbound.size(), // port.securityGroups.size()); List<Rule<?, ?>> sgJumpRulesOutbound = outboundRules.subList(1, outboundRules.size() - 1); // TODO: FAILS //Assert.assertEquals(sgJumpRulesOutbound.size(), // port.securityGroups.size()); for (UUID sgid : port.securityGroups) { // First verify that the security group chains exists Chain ingress = null, egress = null; for (Chain c : dataClient.chainsGetAll()) { String cName = c.getName(); if (cName == null) { continue; } if (cName.contains("INGRESS") && cName .contains(sgid.toString())) { ingress = c; } else if (cName.contains("EGRESS") && cName .contains(sgid.toString())) { egress = c; } } Assert.assertNotNull(ingress); Assert.assertNotNull(egress); // Each security group should have all of this ports ips for (IPAllocation ip : port.fixedIps) { // verify this ip is part of the ip addr group associated // with this security group Assert.assertTrue( dataClient.ipAddrGroupHasAddr(sgid, ip.ipAddress)); } //Verify that there is a jump rule to the egress and ingress chains boolean inboundFound = false, outboundFound = false; for (Rule<?, ?> r : sgJumpRulesInbound) { JumpRule jr = (JumpRule) r; if (egress.getName().equals(jr.getJumpToChainName()) && egress.getId().equals(jr.getJumpToChainId())) { inboundFound = true; } } for (Rule<?, ?> r : sgJumpRulesOutbound) { JumpRule jr = (JumpRule) r; if (ingress.getName().equals(jr.getJumpToChainName()) && ingress.getId().equals(jr.getJumpToChainId())) { outboundFound = true; } } Assert.assertTrue(inboundFound); Assert.assertTrue(outboundFound); SecurityGroup sg = plugin.getSecurityGroup(sgid); for (SecurityGroupRule sgr : sg.securityGroupRules) { SecurityGroupRule zkSgr = plugin.getSecurityGroupRule(sgr.id); Assert.assertTrue(Objects.equal(sgr, zkSgr)); Rule<?, ?> r = dataClient.rulesGet(sgr.id); Assert.assertNotNull(r); } } Assert.assertTrue( isDropAllExceptArpRule(inboundRules.get(inboundRules.size() - 1))); } private class CheckpointMockZookeeperConnectionModule extends MockZookeeperConnectionModule { @Override protected void bindDirectory() { CheckpointedDirectory dir = new CheckpointedMockDirectory(); bind(Directory.class).toInstance(dir); bind(CheckpointedDirectory.class).toInstance(dir); expose(CheckpointedDirectory.class); } } @Before public void initialize() throws InterruptedException, KeeperException { HierarchicalConfiguration config = fillConfig(new HierarchicalConfiguration()); injector = Guice.createInjector( new VersionModule(), new SerializationModule(), new ConfigProviderModule(config), new CheckpointMockZookeeperConnectionModule(), new TestDataClientModule(), new NeutronClusterModule(), new AbstractModule() { @Override protected void configure() { bind(NeutronPlugin.class); } } ); injector.injectMembers(this); Setup.ensureZkDirectoryStructureExists(zkDir(), zkRoot); } @Test public void testSubnetCRUD() throws StateAccessException, SerializationException { int cp1 = zkDir().createCheckPoint(); Network network = plugin.createNetwork(createStockNetwork()); int cp2 = zkDir().createCheckPoint(); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); int cp3 = zkDir().createCheckPoint(); subnet.enableDhcp = false; plugin.updateSubnet(subnet.id, subnet); int cp4 = zkDir().createCheckPoint(); assert (zkDir().getRemovedPaths(cp3, cp4).size() == 0); assert (zkDir().getModifiedPaths(cp3, cp4).size() == 1); assert (zkDir().getAddedPaths(cp3, cp4).size() == 0); subnet.enableDhcp = true; plugin.updateSubnet(subnet.id, subnet); int cp5 = zkDir().createCheckPoint(); assert (zkDir().getRemovedPaths(cp4, cp5).size() == 0); assert (zkDir().getModifiedPaths(cp4, cp5).size() == 1); assert (zkDir().getAddedPaths(cp4, cp5).size() == 0); plugin.deleteSubnet(subnet.id); int cp6 = zkDir().createCheckPoint(); assert (zkDir().getRemovedPaths(cp2, cp6).size() == 0); assert (zkDir().getModifiedPaths(cp2, cp6).size() == 0); assert (zkDir().getAddedPaths(cp2, cp6).size() == 0); plugin.deleteNetwork(network.id); int cp7 = zkDir().createCheckPoint(); assert (zkDir().getRemovedPaths(cp1, cp7).size() == 0); assert (zkDir().getModifiedPaths(cp1, cp7).size() == 0); // There is one added path we expect: the gre tunnel key assert (zkDir().getAddedPaths(cp1, cp7).size() == 1); } @Test public void testNetworkCRUD() throws SerializationException, StateAccessException, BridgeZkManager.VxLanPortIdUpdateException { int cp1 = zkDir().createCheckPoint(); Network network = createStockNetwork(); network.external = true; network = plugin.createNetwork(createStockNetwork()); int cp2 = zkDir().createCheckPoint(); network.adminStateUp = false; network = plugin.updateNetwork(network.id, network); int cp3 = zkDir().createCheckPoint(); assert (zkDir().getRemovedPaths(cp2, cp3).size() == 0); assert (zkDir().getModifiedPaths(cp2, cp3).size() == 2); assert (zkDir().getAddedPaths(cp2, cp3).size() == 0); network.adminStateUp = true; network = plugin.updateNetwork(network.id, network); int cp4 = zkDir().createCheckPoint(); assert (zkDir().getRemovedPaths(cp3, cp4).size() == 0); assert (zkDir().getModifiedPaths(cp3, cp4).size() == 2); assert (zkDir().getAddedPaths(cp3, cp4).size() == 0); assert (zkDir().getRemovedPaths(cp2, cp4).size() == 0); assert (zkDir().getModifiedPaths(cp2, cp4).size() == 0); assert (zkDir().getAddedPaths(cp2, cp4).size() == 0); plugin.deleteNetwork(network.id); int cp5 = zkDir().createCheckPoint(); assert (zkDir().getRemovedPaths(cp1, cp5).size() == 0); assert (zkDir().getModifiedPaths(cp1, cp5).size() == 0); assert (zkDir().getAddedPaths(cp1, cp5).size() == 1); } @Test public void testPortCRUD() throws SerializationException, StateAccessException, Rule.RuleIndexOutOfBoundsException { Network network = plugin.createNetwork(createStockNetwork()); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); int cp1 = zkDir().createCheckPoint(); Port port = createStockPort(subnet.id, network.id, null); port = plugin.createPort(port); int cp2 = zkDir().createCheckPoint(); Port dhcpPort = createStockPort(subnet.id, network.id, null); dhcpPort.deviceOwner = DeviceOwner.DHCP; dhcpPort = plugin.createPort(dhcpPort); int cp3 = zkDir().createCheckPoint(); dhcpPort.securityGroups.add(UUID.randomUUID()); dhcpPort = plugin.updatePort(dhcpPort.id, dhcpPort); int cp4 = zkDir().createCheckPoint(); assert (zkDir().getRemovedPaths(cp3, cp4).size() == 0); assert (zkDir().getModifiedPaths(cp3, cp4).size() == 1); assert (zkDir().getAddedPaths(cp3, cp4).size() == 0); plugin.deletePort(dhcpPort.id); int cp6 = zkDir().createCheckPoint(); assert (zkDir().getRemovedPaths(cp2, cp6).size() == 0); assert (zkDir().getModifiedPaths(cp2, cp6).size() == 0); assert (zkDir().getAddedPaths(cp2, cp6).size() == 0); plugin.deletePort(port.id); int cp7 = zkDir().createCheckPoint(); assert (zkDir().getRemovedPaths(cp1, cp7).size() == 0); assert (zkDir().getModifiedPaths(cp1, cp7).size() == 0); assert (zkDir().getAddedPaths(cp1, cp7).size() == 0); plugin.deleteSubnet(subnet.id); plugin.deleteNetwork(network.id); } @Test public void testSecurityGroupCRUD() throws SerializationException, StateAccessException, Rule.RuleIndexOutOfBoundsException { Network network = plugin.createNetwork(createStockNetwork()); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); int cp1 = zkDir().createCheckPoint(); // Create a security group and a port SecurityGroup csg = createStockSecurityGroup(); Collections.sort(csg.securityGroupRules); SecurityGroup sg = plugin.createSecurityGroup(csg); Collections.sort(sg.securityGroupRules); Assert.assertTrue(Objects.equal(sg, csg)); Port port = createStockPort(subnet.id, network.id, sg.id); port = plugin.createPort(port); // Create a second security group and add it to the port SecurityGroup sg2 = createStockSecurityGroup(); sg2 = plugin.createSecurityGroup(sg2); port.securityGroups.add(sg2.id); port = plugin.updatePort(port.id, port); verifyIpAddrGroups(); verifySGRules(port); // Create a second port and add one of the security groups to it Port port2 = createStockPort(subnet.id, network.id, null); port2.id = UUID.randomUUID(); port2.fixedIps = new ArrayList<>(); port2.fixedIps.add(new IPAllocation("10.0.1.0", subnet.id)); port2.macAddress = "11:22:33:44:55:66"; port2 = plugin.createPort(port2); verifyIpAddrGroups(); verifySGRules(port2); verifySGRules(port); // Add a security group to port2 port2.securityGroups.add(sg2.id); port2 = plugin.updatePort(port2.id, port2); verifyIpAddrGroups(); verifySGRules(port2); verifySGRules(port); // Remove a security group from a port port2.securityGroups = new ArrayList<>(); port2 = plugin.updatePort(port2.id, port2); verifyIpAddrGroups(); verifySGRules(port2); verifySGRules(port); // Remove all security groups from a port port.securityGroups = new ArrayList<>(); port = plugin.updatePort(port.id, port); verifyIpAddrGroups(); verifySGRules(port2); verifySGRules(port); // Create a third port with no fixedIps Port port3 = createStockPort(subnet.id, network.id, null); port3.id = UUID.randomUUID(); port3.fixedIps = new ArrayList<>(); port3.macAddress = "11:22:33:44:55:66"; port3 = plugin.createPort(port3); verifyIpAddrGroups(); verifySGRules(port3); verifySGRules(port2); verifySGRules(port); port3.name = "RYU"; port3 = plugin.updatePort(port3.id, port3); verifyIpAddrGroups(); verifySGRules(port3); verifySGRules(port2); verifySGRules(port); // Delete security groups plugin.deleteSecurityGroup(sg.id); plugin.deleteSecurityGroup(sg2.id); plugin.deletePort(port.id); plugin.deletePort(port2.id); plugin.deletePort(port3.id); verifyIpAddrGroups(); int cp2 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp1, cp2).size(), 0); Assert.assertEquals(zkDir().getModifiedPaths(cp1, cp2).size(), 0); // TODO: FAILS //Assert.assertEquals(zkDir().getAddedPaths(cp1, cp2).size(), 0); } @Test public void testSGSameIpCreate() throws StateAccessException, SerializationException, Rule.RuleIndexOutOfBoundsException { Network network = plugin.createNetwork(createStockNetwork()); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); Network network2 = plugin.createNetwork(createStockNetwork()); Subnet subnet2 = createStockSubnet(); subnet2.networkId = network2.id; subnet2 = plugin.createSubnet(subnet2); SecurityGroup sg = createStockSecurityGroup(); sg = plugin.createSecurityGroup(sg); Port port = createStockPort(subnet.id, network.id, sg.id); port = plugin.createPort(port); String bothPortsIp = port.fixedIps.get(0).ipAddress; Assert.assertTrue(dataClient.ipAddrGroupHasAddr(sg.id, bothPortsIp)); Port port2 = createStockPort(subnet2.id, network2.id, sg.id); port2.id = UUID.randomUUID(); port2 = plugin.createPort(port2); Assert.assertTrue(dataClient.ipAddrGroupHasAddr(sg.id, bothPortsIp)); // Delete just one of the ports. The IP should remain. plugin.deletePort(port.id); Assert.assertTrue(dataClient.ipAddrGroupHasAddr(sg.id, bothPortsIp)); // Delete the other port. The IP should not be present. plugin.deletePort(port2.id); Assert.assertFalse(dataClient.ipAddrGroupHasAddr(sg.id, bothPortsIp)); plugin.deleteSecurityGroup(sg.id); plugin.deleteSubnet(subnet.id); plugin.deleteNetwork(network.id); plugin.deleteSubnet(subnet2.id); plugin.deleteNetwork(network2.id); } @Test public void testSGSameIpUpdate() throws StateAccessException, SerializationException, Rule.RuleIndexOutOfBoundsException { Network network = plugin.createNetwork(createStockNetwork()); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); Network network2 = plugin.createNetwork(createStockNetwork()); Subnet subnet2 = createStockSubnet(); subnet2.networkId = network2.id; subnet2 = plugin.createSubnet(subnet2); SecurityGroup sg = createStockSecurityGroup(); sg = plugin.createSecurityGroup(sg); SecurityGroup sg2 = createStockSecurityGroup(); sg2 = plugin.createSecurityGroup(sg2); Port port = createStockPort(subnet.id, network.id, sg.id); port = plugin.createPort(port); String portsIp = port.fixedIps.get(0).ipAddress; Assert.assertTrue(dataClient.ipAddrGroupHasAddr(sg.id, portsIp)); port.securityGroups.add(sg2.id); port = plugin.updatePort(port.id, port); Assert.assertTrue(dataClient.ipAddrGroupHasAddr(sg.id, portsIp)); Assert.assertTrue(dataClient.ipAddrGroupHasAddr(sg2.id, portsIp)); port.securityGroups = new ArrayList<>(); port.securityGroups.add(sg2.id); port = plugin.updatePort(port.id, port); Assert.assertFalse(dataClient.ipAddrGroupHasAddr(sg.id, portsIp)); Assert.assertTrue(dataClient.ipAddrGroupHasAddr(sg2.id, portsIp)); port.securityGroups = new ArrayList<>(); plugin.updatePort(port.id, port); Assert.assertFalse(dataClient.ipAddrGroupHasAddr(sg.id, portsIp)); Assert.assertFalse(dataClient.ipAddrGroupHasAddr(sg2.id, portsIp)); } @Test public void testAddRouterInterfaceCreateDelete() throws StateAccessException, SerializationException, Rule.RuleIndexOutOfBoundsException { Network network = createStockNetwork(); network = plugin.createNetwork(network); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); int cp1 = zkDir().createCheckPoint(); Router r = createStockRouter(); r = plugin.createRouter(r); int cp2 = zkDir().createCheckPoint(); Port p = createStockPort(subnet.id, network.id, null); p.deviceOwner = DeviceOwner.ROUTER_INTF; p.deviceId = r.id.toString(); p = plugin.createPort(p); RouterInterface ri = createStockRouterInterface(p.id, subnet.id); ri.id = r.id; plugin.addRouterInterface(r.id, ri); plugin.deletePort(p.id); int cp3 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp2, cp3).size(), 0); Assert.assertEquals(zkDir().getModifiedPaths(cp2, cp3).size(), 0); Assert.assertEquals(zkDir().getAddedPaths(cp2, cp3).size(), 0); plugin.deleteRouter(r.id); int cp4 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp1, cp4).size(), 0); Assert.assertEquals(zkDir().getModifiedPaths(cp1, cp4).size(), 0); Assert.assertEquals(zkDir().getAddedPaths(cp1, cp4).size(), 0); } @Test public void testRouterInterfaceConvertPort() throws StateAccessException, SerializationException, Rule.RuleIndexOutOfBoundsException { Network network = createStockNetwork(); network = plugin.createNetwork(network); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); int cp1 = zkDir().createCheckPoint(); Router r = createStockRouter(); r = plugin.createRouter(r); int cp2 = zkDir().createCheckPoint(); Port p = createStockPort(subnet.id, network.id, null); p = plugin.createPort(p); RouterInterface ri = createStockRouterInterface(p.id, subnet.id); ri.id = r.id; ri.portId = p.id; ri = plugin.addRouterInterface(r.id, ri); plugin.deletePort(p.id); int cp3 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp2, cp3).size(), 0); Assert.assertEquals(zkDir().getModifiedPaths(cp2, cp3).size(), 0); Assert.assertEquals(zkDir().getAddedPaths(cp2, cp3).size(), 0); plugin.deleteRouter(r.id); int cp4 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp1, cp4).size(), 0); Assert.assertEquals(zkDir().getModifiedPaths(cp1, cp4).size(), 0); Assert.assertEquals(zkDir().getAddedPaths(cp1, cp4).size(), 0); } @Test public void testRouterGatewayCreate() throws StateAccessException, SerializationException, Rule.RuleIndexOutOfBoundsException { Network network = createStockNetwork(); network.external = true; network = plugin.createNetwork(network); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); int cp1 = zkDir().createCheckPoint(); Port port = createStockPort(subnet.id, network.id, null); port.deviceOwner = DeviceOwner.ROUTER_GW; port = plugin.createPort(port); Router router = createStockRouter(); router.externalGatewayInfo.networkId = network.id; router.externalGatewayInfo.enableSnat = true; router.gwPortId = port.id; router = plugin.createRouter(router); plugin.deletePort(port.id); plugin.deleteRouter(router.id); int cp2 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp1, cp2).size(), 0); Assert.assertEquals(zkDir().getModifiedPaths(cp1, cp2).size(), 0); Assert.assertEquals(zkDir().getAddedPaths(cp1, cp2).size(), 0); } private void verifySnatAddr(UUID routerId, String snatIp) throws StateAccessException, SerializationException, Rule.RuleIndexOutOfBoundsException { org.midonet.cluster.data.Router routerMido = dataClient.routersGet(routerId); List<Rule<?, ?>> inboundRules = dataClient.rulesFindByChain(routerMido.getInboundFilter()); List<Rule<?, ?>> outboundRules = dataClient.rulesFindByChain(routerMido.getOutboundFilter()); boolean foundSnat = false; boolean foundRevSnat = false; for (Rule<?, ?> r : inboundRules) { String dstAddr = r.getCondition().nwDstIp.toString(); if (dstAddr.equals(snatIp + "/32")) { foundSnat = true; } } for (Rule<?, ?> r : outboundRules) { if (r instanceof ForwardNatRule) { Set<NatTarget> targets = ((ForwardNatRule) r).getTargets(); for (NatTarget nt : targets) { if (nt.getNwEnd().equals(snatIp) && nt.getNwStart().equals(snatIp)) { foundRevSnat = true; } } } } Assert.assertTrue(foundSnat && foundRevSnat); } private void verifyStaticNat(FloatingIp floatingIp, Port port, Router router) throws StateAccessException, SerializationException { boolean snatRuleFound = false; boolean dnatRuleFound = false; org.midonet.cluster.data.Router zkRouter = dataClient.routersGet(router.id); List<Rule<?, ?>> outRules = dataClient.rulesFindByChain(zkRouter.getInboundFilter()); List<Rule<?, ?>> inRules = dataClient.rulesFindByChain(zkRouter.getOutboundFilter()); for (Rule<?, ?> r : inRules) { if (r instanceof ForwardNatRule) { ForwardNatRule fnr = (ForwardNatRule) r; for (NatTarget target : fnr.getTargets()) { if (Objects.equal(target.getNwStart(), floatingIp.floatingIpAddress) && Objects.equal(target.getNwEnd(), floatingIp.floatingIpAddress) && target.tpEnd == 0 && target.tpStart == 0) { snatRuleFound = true; } } } } Assert.assertTrue(snatRuleFound); for (Rule<?, ?> r : outRules) { if (r instanceof ForwardNatRule) { ForwardNatRule fnr = (ForwardNatRule) r; for (NatTarget target : fnr.getTargets()) { if (Objects.equal(target.getNwStart(), port.fixedIps.get(0).ipAddress) && Objects.equal(target.getNwEnd(), port.fixedIps.get(0).ipAddress) && target.tpEnd == 0 && target.tpStart == 0) { dnatRuleFound = true; } } } } Assert.assertTrue(dnatRuleFound); } @Test public void testRouterGatewayUpdate() throws StateAccessException, SerializationException, Rule.RuleIndexOutOfBoundsException { Network network = createStockNetwork(); network.external = true; network = plugin.createNetwork(network); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); Network network2 = createStockNetwork(); network2.external = true; network2 = plugin.createNetwork(network2); Subnet subnet2 = createStockSubnet(); subnet2.networkId = network2.id; subnet2.cidr = "10.0.1.0/24"; subnet2 = plugin.createSubnet(subnet2); int cp1 = zkDir().createCheckPoint(); Port port2 = createStockPort(subnet2.id, network2.id, null); port2.fixedIps = new ArrayList<>(); IPAllocation ip = new IPAllocation(); ip.ipAddress = "10.0.1.10"; ip.subnetId = subnet2.id; port2.fixedIps.add(ip); port2.deviceOwner = DeviceOwner.ROUTER_GW; port2 = plugin.createPort(port2); Port port = createStockPort(subnet.id, network.id, null); port.deviceOwner = DeviceOwner.ROUTER_GW; port = plugin.createPort(port); Router router = createStockRouter(); router = plugin.createRouter(router); router.externalGatewayInfo.networkId = network.id; router.externalGatewayInfo.enableSnat = true; router.gwPortId = port.id; router = plugin.updateRouter(router.id, router); verifySnatAddr(router.id, port.fixedIps.get(0).ipAddress); router.externalGatewayInfo.networkId = network2.id; router.gwPortId = port2.id; plugin.deletePort(port.id); router = plugin.updateRouter(router.id, router); verifySnatAddr(router.id, port2.fixedIps.get(0).ipAddress); router.externalGatewayInfo.networkId = null; router.externalGatewayInfo.enableSnat = false; router.gwPortId = null; plugin.deletePort(port2.id); router = plugin.updateRouter(router.id, router); plugin.deletePort(port2.id); plugin.deleteRouter(router.id); int cp2 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp1, cp2).size(), 0); Assert.assertEquals(zkDir().getModifiedPaths(cp1, cp2).size(), 0); Assert.assertEquals(zkDir().getAddedPaths(cp1, cp2).size(), 0); } @Test public void testFIPCreateDelete() throws StateAccessException, SerializationException, Rule.RuleIndexOutOfBoundsException { // Create the external network Network network = createStockNetwork(); network.external = true; network = plugin.createNetwork(network); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); int cp1 = zkDir().createCheckPoint(); // Create a router and hook it up to the external network Port port = createStockPort(subnet.id, network.id, null); port.deviceOwner = DeviceOwner.ROUTER_GW; port = plugin.createPort(port); Router router = createStockRouter(); router.externalGatewayInfo.networkId = network.id; router.gwPortId = port.id; router = plugin.createRouter(router); // Create a new network Network network2 = createStockNetwork(); network2 = plugin.createNetwork(network2); Subnet subnet2 = createStockSubnet(); subnet2.networkId = network2.id; subnet2 = plugin.createSubnet(subnet2); Port p = createStockPort(subnet2.id, network2.id, null); p = plugin.createPort(p); int cp2 = zkDir().createCheckPoint(); FloatingIp fip = new FloatingIp(); fip.routerId = router.id; fip.fixedIpAddress = p.fixedIps.get(0).ipAddress; fip.floatingIpAddress = "10.0.1.5"; fip.portId = p.id; fip.floatingNetworkId = network.id; fip.tenantId = "tenant"; fip.id = UUID.randomUUID(); fip = plugin.createFloatingIp(fip); verifyStaticNat(fip, p, router); plugin.deleteFloatingIp(fip.id); int cp3 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp2, cp3).size(), 0); Assert.assertEquals(zkDir().getModifiedPaths(cp2, cp3).size(), 0); Assert.assertEquals(zkDir().getAddedPaths(cp2, cp3).size(), 0); } @Test public void testFIPUpdate() throws StateAccessException, SerializationException, Rule.RuleIndexOutOfBoundsException { // Create the external network Network network = createStockNetwork(); network.external = true; network = plugin.createNetwork(network); Subnet subnet = createStockSubnet(); subnet.networkId = network.id; subnet = plugin.createSubnet(subnet); // Create a router and hook it up to the external network Port port = createStockPort(subnet.id, network.id, null); port.deviceOwner = DeviceOwner.ROUTER_GW; port = plugin.createPort(port); Router router = createStockRouter(); router.externalGatewayInfo.networkId = network.id; router.gwPortId = port.id; router = plugin.createRouter(router); // Create a new network Network network2 = createStockNetwork(); network2 = plugin.createNetwork(network2); Subnet subnet2 = createStockSubnet(); subnet2.networkId = network2.id; subnet2 = plugin.createSubnet(subnet2); // Create a Port port2 = createStockPort(subnet2.id, network2.id, null); port2 = plugin.createPort(port2); Port port3 = createStockPort(subnet2.id, network2.id, null); port3.fixedIps = new ArrayList<>(); IPAllocation ip = new IPAllocation(); ip.ipAddress = "10.0.0.11"; ip.subnetId = subnet2.id; port3.fixedIps.add(ip); port3.macAddress = "01:23:45:67:89:ab"; port3 = plugin.createPort(port3); // Create a floating IP not attached to a port FloatingIp fip = new FloatingIp(); fip.routerId = router.id; fip.floatingIpAddress = "10.0.1.5"; fip.floatingNetworkId = network.id; fip.tenantId = "tenant"; fip.id = UUID.randomUUID(); fip = plugin.createFloatingIp(fip); int cp1 = zkDir().createCheckPoint(); // update to associate fip.fixedIpAddress = port2.fixedIps.get(0).ipAddress; fip.portId = port2.id; fip = plugin.updateFloatingIp(fip.id, fip); // update to disassociate fip.fixedIpAddress = null; fip.portId = null; fip = plugin.updateFloatingIp(fip.id, fip); int cp2 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp1, cp2).size(), 0); Assert.assertEquals(zkDir().getModifiedPaths(cp1, cp2).size(), 0); Assert.assertEquals(zkDir().getAddedPaths(cp1, cp2).size(), 0); // Update to associate fip.fixedIpAddress = port3.fixedIps.get(0).ipAddress; fip.portId = port3.id; fip = plugin.updateFloatingIp(fip.id, fip); // update to disassociate fip.fixedIpAddress = null; fip.portId = null; fip = plugin.updateFloatingIp(fip.id, fip); int cp3 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp1, cp3).size(), 0); Assert.assertEquals(zkDir().getModifiedPaths(cp1, cp3).size(), 0); Assert.assertEquals(zkDir().getAddedPaths(cp1, cp3).size(), 0); // Now try with a FIP created with a port attached // Create a floating IP not attached to a port FloatingIp fip2 = new FloatingIp(); fip2.routerId = router.id; fip2.fixedIpAddress = port3.fixedIps.get(0).ipAddress; fip2.floatingIpAddress = "10.0.1.5"; fip2.portId = port3.id; fip2.floatingNetworkId = network.id; fip2.tenantId = "tenant"; fip2.id = UUID.randomUUID(); fip2 = plugin.createFloatingIp(fip2); int cp4 = zkDir().createCheckPoint(); // update to disassociate fip2.fixedIpAddress = null; fip2.portId = null; fip2 = plugin.updateFloatingIp(fip2.id, fip2); int cp5 = zkDir().createCheckPoint(); // update to associate fip2.fixedIpAddress = port3.fixedIps.get(0).ipAddress; fip2.portId = port3.id; fip.floatingIpAddress = "10.0.1.5"; fip2 = plugin.updateFloatingIp(fip2.id, fip2); int cp6 = zkDir().createCheckPoint(); // Added Paths needs to equal Removed paths. Although the content // of the paths is logically the same, different UUIDs will be used // for the new routes. Assert.assertEquals(zkDir().getRemovedPaths(cp4, cp6).size(), zkDir().getAddedPaths(cp4, cp6).size(), 4); Assert.assertEquals(zkDir().getModifiedPaths(cp4, cp6).size(), 2); // update to associate with a different port fip2.fixedIpAddress = port2.fixedIps.get(0).ipAddress; fip2.portId = port2.id; fip2 = plugin.updateFloatingIp(fip2.id, fip2); // associate back to the first port fip2.fixedIpAddress = port3.fixedIps.get(0).ipAddress; fip2.portId = port3.id; fip2 = plugin.updateFloatingIp(fip2.id, fip2); int cp7 = zkDir().createCheckPoint(); Assert.assertEquals(zkDir().getRemovedPaths(cp4, cp7).size(), zkDir().getAddedPaths(cp4, cp7).size(), 4); Assert.assertEquals(zkDir().getModifiedPaths(cp4, cp7).size(), 2); } }
923a150608456964fa0979d63446ad4831bc6ebc
1,724
java
Java
kernel-d-validator/validator-api/src/main/java/cn/stylefeng/roses/kernel/validator/api/context/RequestGroupContext.java
nimoqqq/roses
881d9c75cc7b3928a8d73a951722d028d5b072e0
[ "Apache-2.0" ]
null
null
null
kernel-d-validator/validator-api/src/main/java/cn/stylefeng/roses/kernel/validator/api/context/RequestGroupContext.java
nimoqqq/roses
881d9c75cc7b3928a8d73a951722d028d5b072e0
[ "Apache-2.0" ]
null
null
null
kernel-d-validator/validator-api/src/main/java/cn/stylefeng/roses/kernel/validator/api/context/RequestGroupContext.java
nimoqqq/roses
881d9c75cc7b3928a8d73a951722d028d5b072e0
[ "Apache-2.0" ]
null
null
null
25.352941
88
0.667053
999,064
/* * Copyright [2020-2030] [https://www.stylefeng.cn] * * 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. * * Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点: * * 1.请不要删除和修改根目录下的LICENSE文件。 * 2.请不要删除和修改Guns源码头部的版权声明。 * 3.请保留源码和相关描述文件的项目出处,作者声明等。 * 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns * 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns * 6.若您的项目无法满足以上几点,可申请商业授权 */ package cn.stylefeng.roses.kernel.validator.api.context; /** * 保存控制器的方法上的校验组,group class * * @author fengshuonan * @date 2020/11/4 14:31 */ public class RequestGroupContext { private static final ThreadLocal<Class<?>> GROUP_CLASS_HOLDER = new ThreadLocal<>(); /** * 设置临时的校验分组 * * @author fengshuonan * @date 2020/11/4 14:32 */ public static void set(Class<?> groupValue) { GROUP_CLASS_HOLDER.set(groupValue); } /** * 获取临时校验分组 * * @author fengshuonan * @date 2020/11/4 14:32 */ public static Class<?> get() { return GROUP_CLASS_HOLDER.get(); } /** * 清除临时缓存的校验分组 * * @author fengshuonan * @date 2020/11/4 14:32 */ public static void clear() { GROUP_CLASS_HOLDER.remove(); } }
923a15093e9619ee0b678f8f10b2221c47979034
1,868
java
Java
pso-epub-core/src/main/java/org/pageseeder/epub/ItemPathMapper.java
pageseeder/epub
03f9d0a81ba8f8508ba5566918e7d17276bbc17f
[ "Apache-2.0" ]
null
null
null
pso-epub-core/src/main/java/org/pageseeder/epub/ItemPathMapper.java
pageseeder/epub
03f9d0a81ba8f8508ba5566918e7d17276bbc17f
[ "Apache-2.0" ]
null
null
null
pso-epub-core/src/main/java/org/pageseeder/epub/ItemPathMapper.java
pageseeder/epub
03f9d0a81ba8f8508ba5566918e7d17276bbc17f
[ "Apache-2.0" ]
null
null
null
26.309859
121
0.65364
999,065
/* * Copyright (c) 1999-2012 weborganic systems pty. ltd. */ package org.pageseeder.epub; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.pageseeder.epub.util.Paths; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * This file generates a mapping between the original file path and the new file paths. * * @author Christophe Lauret * @version 1 March 2013 */ public final class ItemPathMapper extends DefaultHandler { /** * The base path of the file being parsed. */ private final String _base; /** * The mapping from the old path to the new ones. */ private Map<String, String> map = new HashMap<String, String>(); /** * The root path of the * @param path * @throws IOException */ public ItemPathMapper(String path) throws IOException { this._base = Paths.toBase(path); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // <item href="[href]" id="[id]" media-type="image/jpeg"/> if (qName.equals("item")) { startItemElement(attributes); } } public void startItemElement(Attributes attributes) throws SAXException { String media = attributes.getValue("media-type"); if (media.startsWith("image/")) { String href = attributes.getValue("href"); String oldPath = Paths.simplify(this._base + href); String newPath = Paths.simplify(Config.MEDIA_FOLDER + "/" + attributes.getValue("id") + Paths.getExtension(href)); System.out.println(oldPath+" -> "+newPath); this.map.put(oldPath, newPath); } } /** * @return the map */ public Map<String, String> getMap() { return this.map; } }
923a15632c7b561ad3f764a9843a501be1789555
886
java
Java
src/main/java/com/liuwill/kata/promise/FutureTicket.java
liuwill/java-data-structure
a35425804144fc9510abc01b608fd28f41fab7b4
[ "MIT" ]
null
null
null
src/main/java/com/liuwill/kata/promise/FutureTicket.java
liuwill/java-data-structure
a35425804144fc9510abc01b608fd28f41fab7b4
[ "MIT" ]
null
null
null
src/main/java/com/liuwill/kata/promise/FutureTicket.java
liuwill/java-data-structure
a35425804144fc9510abc01b608fd28f41fab7b4
[ "MIT" ]
null
null
null
22.15
60
0.61851
999,066
package com.liuwill.kata.promise; public class FutureTicket<T> implements Ticket<T> { private Future future; private T data; private ErrorHandler errorHandler; private Exception exception; public FutureTicket(Future future) { this.future = future; } public void resolve(T response) { this.data = response; } public void reject(Exception exception) { this.exception = exception; if (this.errorHandler != null) { this.errorHandler.handle(exception); } } public Exception getException() { if (this.exception == null) { return new Exception(); } return this.exception; } public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } public T prevTicketData() { return this.data; } }
923a171ddd5cd4320937ba0f27d05382701eb037
825
java
Java
msa/black-box-tests/src/test/java/org/thingsboard/server/msa/mapper/AttributesResponse.java
fcnrk/thingsboard
5206a0e4e9c8b037e9ea3e18277a8b51b799c079
[ "ECL-2.0", "Apache-2.0" ]
13
2019-03-25T06:27:05.000Z
2021-05-19T16:13:32.000Z
msa/black-box-tests/src/test/java/org/thingsboard/server/msa/mapper/AttributesResponse.java
mgbin088/thingsboard
7f843f61071308e96d7fcb9ebd971b04d741c338
[ "ECL-2.0", "Apache-2.0" ]
19
2020-02-21T19:02:24.000Z
2022-02-26T17:39:53.000Z
msa/black-box-tests/src/test/java/org/thingsboard/server/msa/mapper/AttributesResponse.java
xurongxin666/viot
21fd43c6a81d109d1c57a6e5f651253892412b84
[ "ECL-2.0", "Apache-2.0" ]
3
2019-03-25T09:17:22.000Z
2021-05-02T04:16:46.000Z
30.555556
75
0.741818
999,067
/** * Copyright © 2016-2019 The Thingsboard 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.thingsboard.server.msa.mapper; import lombok.Data; import java.util.Map; @Data public class AttributesResponse { private Map<String, Object> client; private Map<String, Object> shared; }
923a17baa77ca1dd40450ed44d58b637fca97fce
739
java
Java
src/main/java/io/github/dailystruggle/commandsapi/bukkit/LocalParameters/WorldParameter.java
DailyStruggle/CommandsAPI
b0028bc965891dccf450f4d7bb6859198c80e294
[ "Unlicense" ]
null
null
null
src/main/java/io/github/dailystruggle/commandsapi/bukkit/LocalParameters/WorldParameter.java
DailyStruggle/CommandsAPI
b0028bc965891dccf450f4d7bb6859198c80e294
[ "Unlicense" ]
null
null
null
src/main/java/io/github/dailystruggle/commandsapi/bukkit/LocalParameters/WorldParameter.java
DailyStruggle/CommandsAPI
b0028bc965891dccf450f4d7bb6859198c80e294
[ "Unlicense" ]
null
null
null
30.791667
121
0.775372
999,068
package io.github.dailystruggle.commandsapi.bukkit.LocalParameters; import io.github.dailystruggle.commandsapi.bukkit.BukkitParameter; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.command.CommandSender; import java.util.Collection; import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors; public class WorldParameter extends BukkitParameter { public WorldParameter(String permission, String description, BiFunction<CommandSender, String, Boolean> isRelevant) { super(permission, description, isRelevant); } @Override public Set<String> values() { return Bukkit.getWorlds().stream().map(World::getName).collect(Collectors.toSet()); } }
923a17e7c9c878b9c2489b8103a0362c37f2ff04
1,535
java
Java
src/main/java/com/ferreusveritas/dynamictrees/ModItems.java
OrionDevelopment/DynamicTrees
33aa5d57a1a0ae54da0c41e5f840ff435d4ff434
[ "MIT" ]
null
null
null
src/main/java/com/ferreusveritas/dynamictrees/ModItems.java
OrionDevelopment/DynamicTrees
33aa5d57a1a0ae54da0c41e5f840ff435d4ff434
[ "MIT" ]
null
null
null
src/main/java/com/ferreusveritas/dynamictrees/ModItems.java
OrionDevelopment/DynamicTrees
33aa5d57a1a0ae54da0c41e5f840ff435d4ff434
[ "MIT" ]
null
null
null
33.369565
115
0.794788
999,069
package com.ferreusveritas.dynamictrees; import java.util.ArrayList; import com.ferreusveritas.dynamictrees.api.TreeHelper; import com.ferreusveritas.dynamictrees.items.DendroPotion; import com.ferreusveritas.dynamictrees.items.DirtBucket; import com.ferreusveritas.dynamictrees.items.Staff; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraftforge.registries.IForgeRegistry; public class ModItems { public static DendroPotion dendroPotion; public static DirtBucket dirtBucket; public static Staff treeStaff; public static void preInit() { dendroPotion = new DendroPotion();//Potions dirtBucket = new DirtBucket();//Dirt Bucket treeStaff = new Staff();//Creative Mode Staff } public static void registerItems(IForgeRegistry<Item> registry) { ArrayList<Item> treeItems = new ArrayList<Item>(); ModTrees.baseFamilies.forEach(tree -> tree.getRegisterableItems(treeItems)); ModTrees.dynamicCactus.getRegisterableItems(treeItems); TreeHelper.getLeavesMapForModId(ModConstants.MODID).forEach((key, block) -> treeItems.add(makeItemBlock(block))); registry.registerAll(dendroPotion, dirtBucket, treeStaff); registry.registerAll(treeItems.toArray(new Item[0])); } public static Item makeItemBlock(Block block) { return new ItemBlock(block).setRegistryName(block.getRegistryName()); } public static void registerItemBlock(final IForgeRegistry<Item> registry, Block block) { registry.register(makeItemBlock(block)); } }
923a18f4212174f996f8af12f17f6d445d019386
10,605
java
Java
ruoyi-detection/src/main/java/com/ruoyi/detection/domain/vo/CommissionSampleRegisterVO.java
cxz1276316542/lims
e227cc9d90ec82058163625f0f5b0859333d9568
[ "MIT" ]
1
2021-10-04T08:29:17.000Z
2021-10-04T08:29:17.000Z
ruoyi-detection/src/main/java/com/ruoyi/detection/domain/vo/CommissionSampleRegisterVO.java
cxz1276316542/lims
e227cc9d90ec82058163625f0f5b0859333d9568
[ "MIT" ]
null
null
null
ruoyi-detection/src/main/java/com/ruoyi/detection/domain/vo/CommissionSampleRegisterVO.java
cxz1276316542/lims
e227cc9d90ec82058163625f0f5b0859333d9568
[ "MIT" ]
null
null
null
25.190024
80
0.609335
999,070
package com.ruoyi.detection.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.common.annotation.Excel; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; /** * @author liukun * @date 2021/8/3 */ public class CommissionSampleRegisterVO implements Serializable { private static final long serialVersionUID = -8773766621836617819L; /** 委托样品ID */ @Excel(name = "委托样品ID") private Long sampleID; /** * 客户ID */ @Excel(name = "客户ID") private String customerID; /** * 客户账号 */ @Excel(name = "客户账号") private String customerNumber; /** 样品编号 由各机构确定格式自动生成 */ @Excel(name = "样品编号 由各机构确定格式自动生成") private String sampleNumber; /** 优先级 1-正常;2-急;3-加急;4-特急(客户、业务员操作)默认正常 */ @Excel(name = "优先级 1-正常;2-急;3-加急;4-特急", readConverterExp = "客户、业务员操作") private Integer priority; /** 采样方式(1-抽检、2-送检)默认送检 */ @Excel(name = "采样方式", readConverterExp = "1=-抽检、2-送检") private Integer samplingMode; /** 检测类别 (1-委托、2-仲裁、3-其他)默认委托 */ @Excel(name = "检测类别 ", readConverterExp = "1=-委托、2-仲裁、3-其他") private Integer detectionCategory; /** * 检测标准 */ @Excel(name = "检测标准") private String detectionStandardName; /** 报告领取方式 0-邮寄,1-自取 */ @Excel(name = "报告领取方式 0-邮寄,1-自取") private Integer reportReceiveWay; /** * 报告邮寄地址 */ @Excel(name = "报告邮寄地址") private String receiptAddress; /** 送样人电话 客户填写或业务员代写 */ @Excel(name = "送样人电话 客户填写或业务员代写") private String sampleSenderPhone; /** 送样人名称 */ @Excel(name = "送样人名称") private String sampleSenderName; /** 采样时间 */ @JsonFormat(pattern = "yyyy-MM-dd") @Excel(name = "采样时间", width = 30, dateFormat = "yyyy-MM-dd") private Date samplingTime; /** 样品名称 */ @Excel(name = "样品名称") private String sampleName; /** 样品学名 */ @Excel(name = "样品学名") private String sampleScientificName; /** 样品状态:1-固体;2-液体;3-胶体;4-气体;5-其他 */ @Excel(name = "样品状态:1-固体;2-液体;3-胶体;4-气体;5-其他") private Integer sampleStatus; /** 样品数量 */ @Excel(name = "样品数量") private BigDecimal sampleQuantity; /** 样品计量单位 */ @Excel(name = "样品计量单位") private String measureUnit; /** 抽样基数 */ @Excel(name = "抽样基数") private String samplingBase; /** 样品生产单位 */ @Excel(name = "样品生产单位") private String productionUnit; /** 生产单位地址 */ @Excel(name = "生产单位地址") private String productionUnitAddress; /** 样品描述 */ private String sampleDescription; /** 样品描述 */ @Excel(name = "样品描述") private List<String> sampleDescriptionArray; /** 是否回收剩余样品 0-否 1-是 */ @Excel(name = "是否回收剩余样品 0-否 1-是") private Integer recycle; /** 样品图像地址 */ @Excel(name = "样品图像地址") private String sampleImage; /** 二维码地址 */ @Excel(name = "二维码地址") private String QRcodeAddress; /** 操作者名称 */ @Excel(name = "操作者名称") private String operator; /** 操作时间 */ @JsonFormat(pattern = "yyyy-MM-dd") @Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd") private Date operationTime; /** * 状态 委托保存(01)默认 * 委托修改(02) * 委托退出(00) * 业务保存(11)默认 * 业务提交(12) * 退回修改(10) * 受理审核通过(21) * 受理审核不通过(20) */ @Excel(name = "状态") private Integer status; public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getCustomerID() { return customerID; } public void setCustomerID(String customerID) { this.customerID = customerID; } public Long getSampleID() { return sampleID; } public void setSampleID(Long sampleID) { this.sampleID = sampleID; } public String getCustomerNumber() { return customerNumber; } public void setCustomerNumber(String customerNumber) { this.customerNumber = customerNumber; } public String getSampleNumber() { return sampleNumber; } public void setSampleNumber(String sampleNumber) { this.sampleNumber = sampleNumber; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Integer getSamplingMode() { return samplingMode; } public void setSamplingMode(Integer samplingMode) { this.samplingMode = samplingMode; } public Integer getDetectionCategory() { return detectionCategory; } public void setDetectionCategory(Integer detectionCategory) { this.detectionCategory = detectionCategory; } public String getDetectionStandardName() { return detectionStandardName; } public void setDetectionStandardName(String detectionStandardName) { this.detectionStandardName = detectionStandardName; } public Integer getReportReceiveWay() { return reportReceiveWay; } public void setReportReceiveWay(Integer reportReceiveWay) { this.reportReceiveWay = reportReceiveWay; } public String getReceiptAddress() { return receiptAddress; } public void setReceiptAddress(String receiptAddress) { this.receiptAddress = receiptAddress; } public String getSampleSenderPhone() { return sampleSenderPhone; } public void setSampleSenderPhone(String sampleSenderPhone) { this.sampleSenderPhone = sampleSenderPhone; } public String getSampleSenderName() { return sampleSenderName; } public void setSampleSenderName(String sampleSenderName) { this.sampleSenderName = sampleSenderName; } public Date getSamplingTime() { return samplingTime; } public void setSamplingTime(Date samplingTime) { this.samplingTime = samplingTime; } public String getSampleName() { return sampleName; } public void setSampleName(String sampleName) { this.sampleName = sampleName; } public String getSampleScientificName() { return sampleScientificName; } public void setSampleScientificName(String sampleScientificName) { this.sampleScientificName = sampleScientificName; } public Integer getSampleStatus() { return sampleStatus; } public void setSampleStatus(Integer sampleStatus) { this.sampleStatus = sampleStatus; } public BigDecimal getSampleQuantity() { return sampleQuantity; } public void setSampleQuantity(BigDecimal sampleQuantity) { this.sampleQuantity = sampleQuantity; } public String getMeasureUnit() { return measureUnit; } public void setMeasureUnit(String measureUnit) { this.measureUnit = measureUnit; } public String getSamplingBase() { return samplingBase; } public void setSamplingBase(String samplingBase) { this.samplingBase = samplingBase; } public String getProductionUnit() { return productionUnit; } public void setProductionUnit(String productionUnit) { this.productionUnit = productionUnit; } public String getProductionUnitAddress() { return productionUnitAddress; } public void setProductionUnitAddress(String productionUnitAddress) { this.productionUnitAddress = productionUnitAddress; } public String getSampleDescription() { return sampleDescription; } public void setSampleDescription(String sampleDescription) { this.sampleDescription = sampleDescription; } public Integer getRecycle() { return recycle; } public void setRecycle(Integer recycle) { this.recycle = recycle; } public String getSampleImage() { return sampleImage; } public void setSampleImage(String sampleImage) { this.sampleImage = sampleImage; } public String getQRcodeAddress() { return QRcodeAddress; } public void setQRcodeAddress(String QRcodeAddress) { this.QRcodeAddress = QRcodeAddress; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public Date getOperationTime() { return operationTime; } public void setOperationTime(Date operationTime) { this.operationTime = operationTime; } public List<String> getSampleDescriptionArray() { return sampleDescriptionArray; } public void setSampleDescriptionArray(List<String> sampleDescriptionArray) { this.sampleDescriptionArray = sampleDescriptionArray; } @Override public String toString() { return "CommissionSampleRegisterVO{" + "sampleID=" + sampleID + ", customerID='" + customerID + '\'' + ", customerNumber='" + customerNumber + '\'' + ", sampleNumber='" + sampleNumber + '\'' + ", priority=" + priority + ", samplingMode=" + samplingMode + ", detectionCategory=" + detectionCategory + ", detectionStandardName='" + detectionStandardName + '\'' + ", reportReceiveWay=" + reportReceiveWay + ", receiptAddress='" + receiptAddress + '\'' + ", sampleSenderPhone='" + sampleSenderPhone + '\'' + ", sampleSenderName='" + sampleSenderName + '\'' + ", samplingTime=" + samplingTime + ", sampleName='" + sampleName + '\'' + ", sampleScientificName='" + sampleScientificName + '\'' + ", sampleStatus=" + sampleStatus + ", sampleQuantity=" + sampleQuantity + ", measureUnit='" + measureUnit + '\'' + ", samplingBase='" + samplingBase + '\'' + ", productionUnit='" + productionUnit + '\'' + ", productionUnitAddress='" + productionUnitAddress + '\'' + ", sampleDescription='" + sampleDescription + '\'' + ", sampleDescriptionArray=" + sampleDescriptionArray + ", recycle=" + recycle + ", sampleImage='" + sampleImage + '\'' + ", QRcodeAddress='" + QRcodeAddress + '\'' + ", operator='" + operator + '\'' + ", operationTime=" + operationTime + ", status=" + status + '}'; } }
923a1985a43d3656e667b387a1b4dd03cc2d75b9
2,891
java
Java
RobotCode/src/main/java/frc/lib/statemachine/ActionGroup.java
Worthington-Robotics/2020RobotCode
cee9a76285d1e6c5dfd712603b93e93cf4ecc375
[ "MIT" ]
1
2022-01-06T22:29:10.000Z
2022-01-06T22:29:10.000Z
RobotCode/src/main/java/frc/lib/statemachine/ActionGroup.java
Worthington-Robotics/2021RobotCode
11b7e8577d767cc8d27b6e9702e7ee232e0bec37
[ "MIT" ]
null
null
null
RobotCode/src/main/java/frc/lib/statemachine/ActionGroup.java
Worthington-Robotics/2021RobotCode
11b7e8577d767cc8d27b6e9702e7ee232e0bec37
[ "MIT" ]
null
null
null
28.623762
78
0.591145
999,071
package frc.lib.statemachine; import edu.wpi.first.wpilibj.Timer; import java.util.LinkedList; public class ActionGroup { private LinkedList<Action> group; private double t_Start, t_Timeout; /** * Constructs an action group from an array of actions. Actions will * be handled in the order they are added to the group * @param actions the array of actions to construc the group with * @param timeout_ms the timeout of the whoe group in msec */ ActionGroup(Action[] actions, long timeout_ms) { t_Timeout = (double) timeout_ms / 1000.000; group = new LinkedList<>(); for (Action action : actions) { group.add(action); } } /** * Constructs an action group frm a single action. Actions will * be handled in the order they are added to the group * @param action the single action to contruct the group from * @param timeout_ms the timeout of the group in msec */ ActionGroup(Action action, long timeout_ms) { t_Timeout = (double) timeout_ms / 1000.000; group = new LinkedList<>(); group.add(action); } /** * Runs the on-start code for each action in the group. * Also records the start time of state */ public void onStart() { t_Start = Timer.getFPGATimestamp(); group.forEach(Action::onStart); } /** * Runs the on-loop code for each action in the group. */ public void onLoop() { group.forEach(Action::onLoop); } /** * Determines if the state is ready to be advanced. This can * happen forcefully on a timeout or if all action in the * group time out individually. * <p>This also handles calling the stop code on actions who * have completed independently. * * @return true if all actions in the group have finished or * if they should be forcibly timed out */ public boolean isFinished() { if (t_Start + t_Timeout <= Timer.getFPGATimestamp()) { return true; } boolean temp = true; for (Action action : group) { if (action.isFinished()) { action.doStop(); } else { temp = false; } } return temp; } /** * forcibly terminate all actions within the group */ public void onStop() { group.forEach(Action::doStop); } /** * gets a string representation of the class names inside the action group * @return a string of all class names in the group */ public String toString(){ String classNames = ""; for (int i = 0; i < group.size(); i++) { classNames += group.get(i).getClass().getSimpleName(); if(i < group.size() - 1) classNames += " "; } return classNames; } }
923a19d7d04de85763b4fcad778a6435f6825a87
457
java
Java
YiXin-Data-library/src/com/yxst/epic/yixin/data/rest/YixinHost.java
glustful/mika
300c9e921fbefd00734882466819e5987cfc058b
[ "Apache-2.0" ]
null
null
null
YiXin-Data-library/src/com/yxst/epic/yixin/data/rest/YixinHost.java
glustful/mika
300c9e921fbefd00734882466819e5987cfc058b
[ "Apache-2.0" ]
null
null
null
YiXin-Data-library/src/com/yxst/epic/yixin/data/rest/YixinHost.java
glustful/mika
300c9e921fbefd00734882466819e5987cfc058b
[ "Apache-2.0" ]
null
null
null
28.5625
62
0.730853
999,072
package com.yxst.epic.yixin.data.rest; public class YixinHost { /*YixinPort:连接端口 * YixinHost:米聊地址 * PushHost:Gopush推送地址 */ // public static final String YixinHost = "192.168.1.22"; // public static final int YixinPort = 8093; // public static final String PushHost = "192.168.1.22"; public static final int YixinPort = 80; public static final String YixinHost = "push.miicaa.com"; public static final String PushHost = "pushcomet.miicaa.com"; }
923a1a868f1db83487c5e309a68303ef035a2ef9
17,025
java
Java
app/src/main/java/com/mcuhq/simplebluetooth/MainActivity.java
nguyencuong161199/cuong
bd24f9bf6d95f2577bfcd5e18a03f4411bb9dcd3
[ "MIT" ]
null
null
null
app/src/main/java/com/mcuhq/simplebluetooth/MainActivity.java
nguyencuong161199/cuong
bd24f9bf6d95f2577bfcd5e18a03f4411bb9dcd3
[ "MIT" ]
null
null
null
app/src/main/java/com/mcuhq/simplebluetooth/MainActivity.java
nguyencuong161199/cuong
bd24f9bf6d95f2577bfcd5e18a03f4411bb9dcd3
[ "MIT" ]
null
null
null
39.964789
132
0.591013
999,073
package com.mcuhq.simplebluetooth; import android.annotation.SuppressLint; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.util.Set; import java.util.UUID; public class MainActivity extends AppCompatActivity { // GUI Components private TextView mBluetoothStatus; private Button bFile; private TextView mReadBuffer; private Button mScanBtn; private Button mOffBtn; private Button mListPairedDevicesBtn; private Button mDiscoverBtn; private BluetoothAdapter mBTAdapter; private Set<BluetoothDevice> mPairedDevices; private ArrayAdapter<String> mBTArrayAdapter; private ListView mDevicesListView; private CheckBox mLED1; private byte[] mmBuffer; String sdata = ""; // Container data from hc06 private final String TAG = MainActivity.class.getSimpleName(); private Handler mHandler; // Our main handler that will receive callback notifications private ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier // #defines for identifying shared types between calling functions private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names. private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status @SuppressLint("HandlerLeak") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bFile = (Button) findViewById(R.id.buton_file); mBluetoothStatus = (TextView)findViewById(R.id.bluetoothStatus); mReadBuffer = (TextView) findViewById(R.id.readBuffer); mScanBtn = (Button)findViewById(R.id.scan); mOffBtn = (Button)findViewById(R.id.off); mDiscoverBtn = (Button)findViewById(R.id.discover); mListPairedDevicesBtn = (Button)findViewById(R.id.PairedBtn); mLED1 = (CheckBox)findViewById(R.id.checkboxLED1); mBTArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1); mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio mDevicesListView = (ListView)findViewById(R.id.devicesListView); mDevicesListView.setAdapter(mBTArrayAdapter); // assign model to view mDevicesListView.setOnItemClickListener(mDeviceClickListener); // Ask for location permission if not already allowed if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1); mHandler = new Handler(){ public void handleMessage(android.os.Message msg){ if(msg.what == MESSAGE_READ){ String readMessage = null; byte[] bytes = (byte[]) msg.obj; try { readMessage = new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } mReadBuffer.setText(readMessage); //int a = Integer.valueOf(readMessage); //for(int i=1; i<1000; i++) sdata += readMessage+"\n"; Log.d("Bluetooth_signal", readMessage + ""); } if(msg.what == CONNECTING_STATUS){ if(msg.arg1 == 1) mBluetoothStatus.setText("Connected to Device: " + (String)(msg.obj)); else mBluetoothStatus.setText("Connection Failed"); } } }; if (mBTArrayAdapter == null) { // Device does not support Bluetooth mBluetoothStatus.setText("Status: Bluetooth not found"); Toast.makeText(getApplicationContext(),"Bluetooth device not found!",Toast.LENGTH_SHORT).show(); } else { mLED1.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ if(mConnectedThread != null) //First check to make sure thread created mConnectedThread.write("1"); } }); mScanBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bluetoothOn(v); } }); mOffBtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ bluetoothOff(v); } }); mListPairedDevicesBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ listPairedDevices(v); } }); bFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { writeTofile("hc06_", sdata); } }); mDiscoverBtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ discover(v); } }); } } public void BPM(String string) { //for(int i=0; i<string.length(); i++) if (string[i] > 97); } private void bluetoothOn(View view){ if (!mBTAdapter.isEnabled()) { // if BT not open yet Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // generate request Enable BT startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); // send request mBluetoothStatus.setText("Bluetooth enabled"); Toast.makeText(getApplicationContext(),"Bluetooth turned on",Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getApplicationContext(),"Bluetooth is already on", Toast.LENGTH_SHORT).show(); } } // Enter here after user selects "yes" or "no" to enabling radio @Override protected void onActivityResult(int requestCode, int resultCode, Intent Data){ // Check which request we're responding to if (requestCode == REQUEST_ENABLE_BT) { // Make sure the request was successful if (resultCode == RESULT_OK) { // The user picked a contact. // The Intent's data Uri identifies which contact was selected. mBluetoothStatus.setText("Enabled"); } else mBluetoothStatus.setText("Disabled"); } } private void bluetoothOff(View view){ mBTAdapter.disable(); // turn off mBluetoothStatus.setText("Bluetooth disabled"); Toast.makeText(getApplicationContext(),"Bluetooth turned Off", Toast.LENGTH_SHORT).show(); } private void discover(View view){ // Check if the device is already discovering if(mBTAdapter.isDiscovering()){ mBTAdapter.cancelDiscovery(); Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show(); } else{ if(mBTAdapter.isEnabled()) { mBTArrayAdapter.clear(); // clear items mBTAdapter.startDiscovery(); Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show(); registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); } else{ Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show(); } } } final BroadcastReceiver blReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(BluetoothDevice.ACTION_FOUND.equals(action)){ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // add the name to the list mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress()); mBTArrayAdapter.notifyDataSetChanged(); } } }; private void listPairedDevices(View view){ mBTArrayAdapter.clear(); mPairedDevices = mBTAdapter.getBondedDevices(); if(mBTAdapter.isEnabled()) { // put it's one to the adapter for (BluetoothDevice device : mPairedDevices) mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress()); Toast.makeText(getApplicationContext(), "Showed Paired Devices", Toast.LENGTH_SHORT).show(); } else Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show(); } private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) { if(!mBTAdapter.isEnabled()) { Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show(); return; } mBluetoothStatus.setText("Connecting..."); // Get the device MAC address, which is the last 17 chars in the View String info = ((TextView) v).getText().toString(); final String address = info.substring(info.length() - 17); final String name = info.substring(0,info.length() - 17); // Spawn a new thread to avoid blocking the GUI one new Thread() { public void run() { boolean fail = false; BluetoothDevice device = mBTAdapter.getRemoteDevice(address); try { mBTSocket = createBluetoothSocket(device); } catch (IOException e) { fail = true; Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show(); } // Establish the Bluetooth socket connection. try { mBTSocket.connect(); } catch (IOException e) { try { fail = true; mBTSocket.close(); mHandler.obtainMessage(CONNECTING_STATUS, -1, -1) .sendToTarget(); } catch (IOException e2) { //insert code to deal with this Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show(); } } if(!fail) { mConnectedThread = new ConnectedThread(mBTSocket); mConnectedThread.start(); mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name) .sendToTarget(); } } }.start(); } }; private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { try { final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class); return (BluetoothSocket) m.invoke(device, BTMODULEUUID); } catch (Exception e) { Log.e(TAG, "Could not create Insecure RFComm Connection",e); } return device.createRfcommSocketToServiceRecord(BTMODULEUUID); } private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the input and output streams, using temp objects because // member streams are final try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { byte[] buffer = new byte[1024]; // buffer store for the stream int bytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); if(bytes != 0) { buffer = new byte[1024]; SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed. bytes = mmInStream.available(); // how many bytes are ready to be read? bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); // Send the obtained bytes to the UI activity } } catch (IOException e) { e.printStackTrace(); break; } } } /* Call this from the main activity to send data to the remote device */ public void write(String input) { byte[] bytes = input.getBytes(); //converts entered String into bytes try { mmOutStream.write(bytes); } catch (IOException e) { } } /* Call this from the main activity to shutdown the connection */ public void cancel() { try { mmSocket.close(); } catch (IOException e) { } } } // SenData_hc06_.txt public void writeTofile(String fileName, String data) { final File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/SenData_/" ); //Toast.makeText(getApplicationContext(),"File 1:" +path.toString(),Toast.LENGTH_LONG).show(); if(!path.exists()) { path.mkdirs(); } final File file = new File(path + fileName + ".txt"); // Ex:\Dowload\SenData_hc06.txt //Toast.makeText(getApplicationContext(),"File 2:" +file.toString(),Toast.LENGTH_LONG).show(); try { file.createNewFile(); FileOutputStream fOut = new FileOutputStream(file); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(data); Toast.makeText(getApplicationContext(),"ok :" + file.toString(),Toast.LENGTH_LONG).show(); myOutWriter.close(); fOut.flush(); fOut.close(); } catch (IOException e) { //Toast.makeText(getApplicationContext(),"Notice: " + e.toString(),Toast.LENGTH_LONG).show(); Log.e("Exception", "File write failed: " + e.toString()); } } }
923a1e58a44e42d4eba279ff46436dd36d1f0b83
1,118
java
Java
kanglib/src/main/java/com/kang/framework/KlJson.java
kangzhixing/kanglab
e8bc513a2bcc3bc891c15e6593c2e723daf308dc
[ "Apache-2.0" ]
null
null
null
kanglib/src/main/java/com/kang/framework/KlJson.java
kangzhixing/kanglab
e8bc513a2bcc3bc891c15e6593c2e723daf308dc
[ "Apache-2.0" ]
4
2020-05-28T05:35:03.000Z
2022-03-31T21:06:37.000Z
kanglib/src/main/java/com/kang/framework/KlJson.java
kangzhixing/kanglab
e8bc513a2bcc3bc891c15e6593c2e723daf308dc
[ "Apache-2.0" ]
null
null
null
19.614035
71
0.534884
999,074
package com.kang.framework; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.extern.slf4j.Slf4j; /** * Json工具类型 * * @author kangzhixing */ @Slf4j public class KlJson { /** * 创建Gson对象 */ private final static Gson STATIC_GSON = new GsonBuilder().create(); /** * 私有无参构造方法 */ private KlJson() { } /** * 将对象转成json格式 * * @param object 入参为对象 * @return String 出参为转换后的字符串 */ public static String toJSONString(Object object) { try { return STATIC_GSON.toJson(object); } catch (Exception e) { log.error("JSON转换异常:", e); return ""; } } /** * 将json转成特定的cls的对象 * * @param jsonString json串 * @param cls class对象 * @param <T> 对象类型 * @return 特定对象 */ public static <T> T parseObject(String jsonString, Class<T> cls) { try { return STATIC_GSON.fromJson(jsonString, cls); } catch (Exception e) { log.error("JSON转换异常:", e); return null; } } }
923a1ed73a8b23352ffa3464fc37fc78cebf5917
414
java
Java
src/main/java/com/rozsa/exception/ResourceNotFoundException.java
dendriel/npc-data-manager-auth
dcf089c80aa52d16a523b235e7d9965bdd344c2b
[ "MIT" ]
null
null
null
src/main/java/com/rozsa/exception/ResourceNotFoundException.java
dendriel/npc-data-manager-auth
dcf089c80aa52d16a523b235e7d9965bdd344c2b
[ "MIT" ]
null
null
null
src/main/java/com/rozsa/exception/ResourceNotFoundException.java
dendriel/npc-data-manager-auth
dcf089c80aa52d16a523b235e7d9965bdd344c2b
[ "MIT" ]
null
null
null
27.6
77
0.789855
999,075
package com.rozsa.exception; import lombok.NoArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @NoArgsConstructor @ResponseStatus(value= HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends NpcDataManagerAuthException { public ResourceNotFoundException(String message) { super(message); } }
923a200916db253b1224e43f97e6ba63d098ab9e
1,010
java
Java
src/main/java/se/jaitco/queueticketapi/config/SwaggerConfig.java
johanaschan/QueueTicketService
4ca00a6865c56a87d546b71aa52d0b057e830d6a
[ "MIT" ]
5
2016-09-22T20:05:09.000Z
2020-11-02T06:15:47.000Z
src/main/java/se/jaitco/queueticketapi/config/SwaggerConfig.java
johanaschan/QueueTicketService
4ca00a6865c56a87d546b71aa52d0b057e830d6a
[ "MIT" ]
3
2016-08-30T06:41:57.000Z
2016-08-31T09:05:51.000Z
src/main/java/se/jaitco/queueticketapi/config/SwaggerConfig.java
johanaschan/queue-ticket-service
4ca00a6865c56a87d546b71aa52d0b057e830d6a
[ "MIT" ]
1
2018-03-23T13:37:22.000Z
2018-03-23T13:37:22.000Z
31.5625
97
0.724752
999,076
package se.jaitco.queueticketapi.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket docket() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("se.jaitco.queueticketapi.controller")) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("QueueTicketService REST API") .build(); } }
923a20dcd3883a1c5f09ea6e0cd72ef3a70b9b14
1,542
java
Java
TVUIComponent/Calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/ReflectionUtils.java
veeta-tv/fire-app-builder
1e453b1f1c9a2e6639bbab0c3005d452b61757cd
[ "Apache-2.0" ]
196
2016-10-03T06:48:56.000Z
2022-03-29T18:30:34.000Z
TVUIComponent/Calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/ReflectionUtils.java
veeta-tv/fire-app-builder
1e453b1f1c9a2e6639bbab0c3005d452b61757cd
[ "Apache-2.0" ]
71
2016-11-09T14:57:52.000Z
2022-03-03T05:32:04.000Z
TVUIComponent/Calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/ReflectionUtils.java
veeta-tv/fire-app-builder
1e453b1f1c9a2e6639bbab0c3005d452b61757cd
[ "Apache-2.0" ]
313
2016-10-04T13:52:11.000Z
2022-03-30T20:27:13.000Z
26.586207
78
0.585603
999,077
package uk.co.chrisjenx.calligraphy; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Created by chris on 17/12/14. * For Calligraphy. */ class ReflectionUtils { static Field getField(Class clazz, String fieldName) { try { final Field f = clazz.getDeclaredField(fieldName); f.setAccessible(true); return f; } catch (NoSuchFieldException ignored) { } return null; } static Object getValue(Field field, Object obj) { try { return field.get(obj); } catch (IllegalAccessException ignored) { } return null; } static void setValue(Field field, Object obj, Object value) { try { field.set(obj, value); } catch (IllegalAccessException ignored) { } } static Method getMethod(Class clazz, String methodName) { final Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { method.setAccessible(true); return method; } } return null; } static void invokeMethod(Object object, Method method, Object... args) { try { if (method == null) return; method.invoke(object, args); } catch (IllegalAccessException | InvocationTargetException ignored) { ignored.printStackTrace(); } } }
923a214bdd9673394cbd61b46f8495fb7d54c24c
1,550
java
Java
Pepcoding/Level1/GenericTrees/SizeOfGenericTree.java
dakshkhetan/ds-and-algo
26a7c749c1da28375074159079604d94645a860c
[ "MIT" ]
2
2022-01-19T07:26:36.000Z
2022-02-08T14:07:58.000Z
Pepcoding/Level1/GenericTrees/SizeOfGenericTree.java
dakshkhetan/ds-and-algo
26a7c749c1da28375074159079604d94645a860c
[ "MIT" ]
null
null
null
Pepcoding/Level1/GenericTrees/SizeOfGenericTree.java
dakshkhetan/ds-and-algo
26a7c749c1da28375074159079604d94645a860c
[ "MIT" ]
3
2021-03-27T17:38:10.000Z
2022-03-19T17:12:20.000Z
16.489362
47
0.521935
999,078
/* Sample Input 12 10 20 -1 30 50 -1 60 -1 -1 40 -1 -1 Sample Output 6 */ import java.util.*; class TreeNode { int data; ArrayList<TreeNode> children; TreeNode(int data) { this.data = data; children = new ArrayList<>(); } } public class Main { public static void display(TreeNode root) { String str = root.data + " -> "; for (TreeNode child : root.children) { str += child.data + ", "; } str += "."; System.out.println(str); for (TreeNode child : root.children) { display(child); } } public static TreeNode construct(int[] arr) { TreeNode root = null; Stack<TreeNode> st = new Stack<>(); for (int i = 0; i < arr.length; i++) { if (arr[i] == -1) { st.pop(); } else { TreeNode node = new TreeNode(arr[i]); if (st.size() > 0) { st.peek().children.add(node); } else { root = node; } st.push(node); } } return root; } public static int size(TreeNode root) { if (root == null) { return 0; } int count = 1; // root for (TreeNode child : root.children) { count += size(child); } return count; } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } TreeNode root = construct(arr); int result = size(root); System.out.println(result); // display(root); } }
923a2173a999866f2695fe355eb5e524000adad0
2,825
java
Java
streams/src/main/java/org/apache/kafka/streams/processor/DefaultPartitionGrouper.java
h12w/kafka-dist
841d2d1a26af94ec95c480dbf2453f9c7d28c2f7
[ "Apache-2.0" ]
2
2017-09-02T03:18:02.000Z
2017-12-19T04:39:05.000Z
streams/src/main/java/org/apache/kafka/streams/processor/DefaultPartitionGrouper.java
Esquive/queryable-kafka
810f36ae5afb5d53aebc3d519a7a9f312e03007a
[ "Apache-2.0" ]
null
null
null
streams/src/main/java/org/apache/kafka/streams/processor/DefaultPartitionGrouper.java
Esquive/queryable-kafka
810f36ae5afb5d53aebc3d519a7a9f312e03007a
[ "Apache-2.0" ]
null
null
null
36.688312
118
0.675752
999,079
/** * 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.kafka.streams.processor; import org.apache.kafka.common.Cluster; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.PartitionInfo; import org.apache.kafka.common.TopicPartition; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class DefaultPartitionGrouper implements PartitionGrouper { public Map<TaskId, Set<TopicPartition>> partitionGroups(Map<Integer, Set<String>> topicGroups, Cluster metadata) { Map<TaskId, Set<TopicPartition>> groups = new HashMap<>(); for (Map.Entry<Integer, Set<String>> entry : topicGroups.entrySet()) { Integer topicGroupId = entry.getKey(); Set<String> topicGroup = entry.getValue(); int maxNumPartitions = maxNumPartitions(metadata, topicGroup); for (int partitionId = 0; partitionId < maxNumPartitions; partitionId++) { Set<TopicPartition> group = new HashSet<>(topicGroup.size()); for (String topic : topicGroup) { if (partitionId < metadata.partitionsForTopic(topic).size()) { group.add(new TopicPartition(topic, partitionId)); } } groups.put(new TaskId(topicGroupId, partitionId), Collections.unmodifiableSet(group)); } } return Collections.unmodifiableMap(groups); } protected int maxNumPartitions(Cluster metadata, Set<String> topics) { int maxNumPartitions = 0; for (String topic : topics) { List<PartitionInfo> infos = metadata.partitionsForTopic(topic); if (infos == null) throw new KafkaException("topic not found :" + topic); int numPartitions = infos.size(); if (numPartitions > maxNumPartitions) maxNumPartitions = numPartitions; } return maxNumPartitions; } }
923a221b62ea869e5b4938a84c499c4daa50ef65
16,396
java
Java
src/vm/jvm/runtime/org/raku/nqp/sixmodel/KnowHOWMethods.java
salortiz/nqp
bef3f1c3b8cb27b26cfe6e0a9ce465bc3ed7075c
[ "Artistic-2.0" ]
179
2015-01-06T13:57:20.000Z
2020-03-08T19:26:34.000Z
src/vm/jvm/runtime/org/raku/nqp/sixmodel/KnowHOWMethods.java
salortiz/nqp
bef3f1c3b8cb27b26cfe6e0a9ce465bc3ed7075c
[ "Artistic-2.0" ]
281
2015-01-03T06:33:36.000Z
2020-03-17T18:40:40.000Z
src/vm/jvm/runtime/org/raku/nqp/sixmodel/KnowHOWMethods.java
salortiz/nqp
bef3f1c3b8cb27b26cfe6e0a9ce465bc3ed7075c
[ "Artistic-2.0" ]
138
2015-01-23T04:09:42.000Z
2020-03-08T19:26:36.000Z
44.313514
131
0.596365
999,080
package org.raku.nqp.sixmodel; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.util.HashMap; import java.util.List; import org.raku.nqp.runtime.CallFrame; import org.raku.nqp.runtime.CallSiteDescriptor; import org.raku.nqp.runtime.CodeRef; import org.raku.nqp.runtime.CompilationUnit; import org.raku.nqp.runtime.ExceptionHandling; import org.raku.nqp.runtime.Ops; import org.raku.nqp.runtime.ThreadContext; import org.raku.nqp.sixmodel.reprs.KnowHOWAttributeInstance; import org.raku.nqp.sixmodel.reprs.KnowHOWREPR; import org.raku.nqp.sixmodel.reprs.KnowHOWREPRInstance; /** * This class contains methods that belong on the KnowHOW meta-object. It * pretends to be a compilation unit, so as to fit with the expected API * for code reference like things. */ public class KnowHOWMethods extends CompilationUnit { public void new_type(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { /* Get arguments. */ CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 1, 1); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); String repr_arg = Ops.namedparam_opt_s(cf, csd, args, "repr"); String name_arg = Ops.namedparam_opt_s(cf, csd, args, "name"); if (Ops.isnull(self) == 1 || !(self.st.REPR instanceof KnowHOWREPR)) throw ExceptionHandling.dieInternal(tc, "KnowHOW methods must be called on object with REPR KnowHOWREPR"); /* We first create a new HOW instance. */ SixModelObject HOW = self.st.REPR.allocate(tc, self.st); /* See if we have a representation name; if not default to P6opaque. */ String repr_name = repr_arg != null ? repr_arg : "P6opaque"; /* Create a new type object of the desired REPR. (Note that we can't * default to KnowHOWREPR here, since it doesn't know how to actually * store attributes, it's just for bootstrapping knowhow's. */ REPR repr_to_use = REPRRegistry.getByName(repr_name); SixModelObject type_object = repr_to_use.type_object_for(tc, HOW); /* See if we were given a name; put it into the meta-object if so. */ if (name_arg != null) ((KnowHOWREPRInstance)HOW).name = name_arg; /* Set .WHO to an empty hash. */ SixModelObject Hash = tc.gc.BOOTHash; type_object.st.WHO = Hash.st.REPR.allocate(tc, Hash.st); /* Return the type object. */ Ops.return_o(type_object, cf); } finally { cf.leave(); } } public void add_method(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 4, 4); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); String name = Ops.posparam_s(cf, csd, args, 2); SixModelObject method = Ops.posparam_o(cf, csd, args, 3); if (Ops.isnull(self) == 1 || !(self instanceof KnowHOWREPRInstance)) throw ExceptionHandling.dieInternal(tc, "KnowHOW methods must be called on object instance with REPR KnowHOWREPR"); ((KnowHOWREPRInstance)self).methods.put(name, method); Ops.return_o(method, cf); } finally { cf.leave(); } } public void add_attribute(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 3, 3); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); SixModelObject attribute = Ops.posparam_o(cf, csd, args, 2); if (Ops.isnull(self) == 1 || !(self instanceof KnowHOWREPRInstance)) throw ExceptionHandling.dieInternal(tc, "KnowHOW methods must be called on object instance with REPR KnowHOWREPR"); if (Ops.isnull(attribute) == 1 || !(attribute instanceof KnowHOWAttributeInstance)) throw ExceptionHandling.dieInternal(tc, "KnowHOW attributes must use KnowHOWAttributeREPR"); ((KnowHOWREPRInstance)self).attributes.add(attribute); Ops.return_o(attribute, cf); } finally { cf.leave(); } } public void compose(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 2, 2); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); SixModelObject type_obj = Ops.posparam_o(cf, csd, args, 1); if (Ops.isnull(self) == 1 || !(self instanceof KnowHOWREPRInstance)) throw ExceptionHandling.dieInternal(tc, "KnowHOW methods must be called on object instance with REPR KnowHOWREPR"); /* Set method cache. */ type_obj.st.MethodCache = ((KnowHOWREPRInstance)self).methods; type_obj.st.ModeFlags = STable.METHOD_CACHE_AUTHORITATIVE; /* Set type check cache. */ type_obj.st.TypeCheckCache = new SixModelObject[] { type_obj }; /* Use any attribute information to produce attribute protocol * data. The protocol consists of an array... */ SixModelObject repr_info = tc.gc.BOOTArray.st.REPR.allocate(tc, tc.gc.BOOTArray.st); /* ...which contains an array per MRO entry... */ SixModelObject type_info = tc.gc.BOOTArray.st.REPR.allocate(tc, tc.gc.BOOTArray.st); repr_info.push_boxed(tc, type_info); /* ...which in turn contains this type... */ type_info.push_boxed(tc, type_obj); /* ...then an array of hashes per attribute... */ SixModelObject attr_info_list = tc.gc.BOOTArray.st.REPR.allocate(tc, tc.gc.BOOTArray.st); type_info.push_boxed(tc, attr_info_list); List<SixModelObject> attributes = ((KnowHOWREPRInstance)self).attributes; for (int i = 0; i < attributes.size(); i++) { KnowHOWAttributeInstance attribute = (KnowHOWAttributeInstance)attributes.get(i); SixModelObject attr_info = tc.gc.BOOTHash.st.REPR.allocate(tc, tc.gc.BOOTHash.st); SixModelObject name_obj = tc.gc.BOOTStr.st.REPR.allocate(tc, tc.gc.BOOTStr.st); name_obj.set_str(tc, attribute.name); attr_info.bind_key_boxed(tc, "name", name_obj); attr_info.bind_key_boxed(tc, "type", attribute.type); if (attribute.box_target != 0) { /* Merely having the key serves as a "yes". */ attr_info.bind_key_boxed(tc, "box_target", attr_info); } attr_info_list.push_boxed(tc, attr_info); } /* ...followed by a list of parents (none). */ SixModelObject parent_info = tc.gc.BOOTArray.st.REPR.allocate(tc, tc.gc.BOOTArray.st); type_info.push_boxed(tc, parent_info); /* All of this goes in a hash. */ SixModelObject repr_info_hash = tc.gc.BOOTHash.st.REPR.allocate(tc, tc.gc.BOOTHash.st); repr_info_hash.bind_key_boxed(tc, "attribute", repr_info); /* Compose the representation using it. */ type_obj.st.REPR.compose(tc, type_obj.st, repr_info_hash); Ops.return_o(type_obj, cf); } finally { cf.leave(); } } public void attributes(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 2, 2); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); if (Ops.isnull(self) == 1 || !(self instanceof KnowHOWREPRInstance)) throw ExceptionHandling.dieInternal(tc, "KnowHOW methods must be called on object instance with REPR KnowHOWREPR"); SixModelObject BOOTArray = tc.gc.BOOTArray; SixModelObject result = BOOTArray.st.REPR.allocate(tc, BOOTArray.st); List<SixModelObject> attributes = ((KnowHOWREPRInstance)self).attributes; for (SixModelObject attr : attributes) result.push_boxed(tc, attr); Ops.return_o(result, cf); } finally { cf.leave(); } } public void methods(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 2, 2); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); if (Ops.isnull(self) == 1 || !(self instanceof KnowHOWREPRInstance)) throw ExceptionHandling.dieInternal(tc, "KnowHOW methods must be called on object instance with REPR KnowHOWREPR"); SixModelObject BOOTHash = tc.gc.BOOTHash; SixModelObject result = BOOTHash.st.REPR.allocate(tc, BOOTHash.st); HashMap<String, SixModelObject> methods = ((KnowHOWREPRInstance)self).methods; for (String name : methods.keySet()) result.bind_key_boxed(tc, name, methods.get(name)); Ops.return_o(result, cf); } finally { cf.leave(); } } public void name(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 2, 2); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); if (Ops.isnull(self) == 1 || !(self instanceof KnowHOWREPRInstance)) throw ExceptionHandling.dieInternal(tc, "KnowHOW methods must be called on object instance with REPR KnowHOWREPR"); Ops.return_s(((KnowHOWREPRInstance)self).name, cf); } finally { cf.leave(); } } public void attr_new(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { /* Process arguments. */ csd = Ops.checkarity(cf, csd, args, 1, 1); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); String name_arg = Ops.namedparam_s(cf, csd, args, "name"); SixModelObject type_arg = Ops.namedparam_opt_o(cf, csd, args, "type"); long bt_arg = Ops.namedparam_opt_i(cf, csd, args, "box_target"); /* Allocate attribute object. */ REPR repr = REPRRegistry.getByName("KnowHOWAttribute"); KnowHOWAttributeInstance obj = (KnowHOWAttributeInstance)repr.allocate(tc, self.st); /* Populate it. */ obj.name = name_arg; obj.type = Ops.isnull(type_arg) == 0 ? type_arg : tc.gc.KnowHOW; obj.box_target = bt_arg == 0 ? 0 : 1; /* Return produced object. */ Ops.return_o(obj, cf); } finally { cf.leave(); } } public void attr_compose(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 1, 1); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); Ops.return_o(self, cf); } finally { cf.leave(); } } public void attr_name(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 1, 1); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); Ops.return_s(((KnowHOWAttributeInstance)self).name, cf); } finally { cf.leave(); } } public void attr_type(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 1, 1); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); Ops.return_o(((KnowHOWAttributeInstance)self).type, cf); } finally { cf.leave(); } } public void attr_box_target(ThreadContext tc, CodeRef cr, CallSiteDescriptor csd, Object[] args) { CallFrame cf = new CallFrame(tc, cr); try { csd = Ops.checkarity(cf, csd, args, 1, 1); args = tc.flatArgs; SixModelObject self = Ops.posparam_o(cf, csd, args, 0); Ops.return_i(((KnowHOWAttributeInstance)self).box_target, cf); } finally { cf.leave(); } } public CodeRef[] getCodeRefs() { CodeRef[] refs = new CodeRef[12]; String[] snull = null; long[][] hnull = new long[0][]; MethodType mt = MethodType.methodType(void.class, ThreadContext.class, CodeRef.class, CallSiteDescriptor.class, Object[].class); Lookup l = MethodHandles.lookup(); try { refs[0] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "new_type", mt).bindTo(this), "new_type", "new_type", snull, snull, snull, snull, hnull, (short)0); refs[1] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "add_method", mt).bindTo(this), "add_method", "add_method", snull, snull, snull, snull, hnull, (short)0); refs[2] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "add_attribute", mt).bindTo(this), "add_attribute", "add_attribute", snull, snull, snull, snull, hnull, (short)0); refs[3] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "compose", mt).bindTo(this), "compose", "compose", snull, snull, snull, snull, hnull, (short)0); refs[4] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "attributes", mt).bindTo(this), "attributes", "attributes", snull, snull, snull, snull, hnull, (short)0); refs[5] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "methods", mt).bindTo(this), "methods", "methods", snull, snull, snull, snull, hnull, (short)0); refs[6] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "name", mt).bindTo(this), "name", "name", snull, snull, snull, snull, hnull, (short)0); refs[7] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "attr_new", mt).bindTo(this), "new", "attr_new", snull, snull, snull, snull, hnull, (short)0); refs[8] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "attr_compose", mt).bindTo(this), "compose", "attr_compose", snull, snull, snull, snull, hnull, (short)0); refs[9] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "attr_name", mt).bindTo(this), "name", "attr_name", snull, snull, snull, snull, hnull, (short)0); refs[10] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "attr_type", mt).bindTo(this), "type", "attr_type", snull, snull, snull, snull, hnull, (short)0); refs[11] = new CodeRef(this, l.findVirtual(KnowHOWMethods.class, "attr_box_target", mt).bindTo(this), "box_target", "attr_box_target", snull, snull, snull, snull, hnull, (short)0); } catch (Exception e) { throw new RuntimeException(e); } return refs; } public int[] getOuterMap() { return new int[0]; } public CallSiteDescriptor[] getCallSites() { return new CallSiteDescriptor[0]; } public String hllName() { return ""; } }
923a222c867bea87f2b25b2b7bf3105d6391f50f
2,586
java
Java
org.goffi.toffi/src/test/java/org/goffi/toffi/test/domainmodel/shell/commands/AesGeneralTest.java
dzhemriza/goffi
998005b76ae9c23f0e4ddf4a4e18fe867af9e24d
[ "Apache-2.0" ]
null
null
null
org.goffi.toffi/src/test/java/org/goffi/toffi/test/domainmodel/shell/commands/AesGeneralTest.java
dzhemriza/goffi
998005b76ae9c23f0e4ddf4a4e18fe867af9e24d
[ "Apache-2.0" ]
null
null
null
org.goffi.toffi/src/test/java/org/goffi/toffi/test/domainmodel/shell/commands/AesGeneralTest.java
dzhemriza/goffi
998005b76ae9c23f0e4ddf4a4e18fe867af9e24d
[ "Apache-2.0" ]
null
null
null
32.734177
80
0.724285
999,081
/* * org.goffi.toffi * * File Name: AesGeneralTest.java * * Copyright 2017 Dzhem Riza * * 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.goffi.toffi.test.domainmodel.shell.commands; import com.fasterxml.jackson.databind.ObjectMapper; import org.goffi.core.domainmodel.files.FileTestsBase; import org.goffi.toffi.shell.ConsoleKeyReader; import org.goffi.toffi.shell.commands.Aes; import org.goffi.toffi.shell.exceptions.InvalidAesModeException; import org.goffi.toffi.shell.exceptions.PathDoesntExistsException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import java.io.PrintStream; import java.nio.file.Paths; import java.util.UUID; @RunWith(MockitoJUnitRunner.class) public class AesGeneralTest extends FileTestsBase { @Spy private ObjectMapper objectMapper = new ObjectMapper(); @Mock private PrintStream outputLog; @Mock private ConsoleKeyReader consoleKeyReader; @InjectMocks private Aes aes; @Test(expected = PathDoesntExistsException.class) public void encodeCommandSourceDoNotExists() throws Exception { aes.encode(Paths.get(UUID.randomUUID().toString()).toFile(), null, "gcm", true, consoleKeyReader, null, 2); } @Test(expected = InvalidAesModeException.class) public void encodeInvalidMode() throws Exception { aes.encode(getTestFile().toFile(), null, "TEST", true, consoleKeyReader, null, 2); } @Test(expected = PathDoesntExistsException.class) public void decodeCommandSourceDoNotExists() throws Exception { aes.decode(Paths.get(UUID.randomUUID().toString()).toFile(), null, "gcm", true, consoleKeyReader, null, 2); } @Test(expected = InvalidAesModeException.class) public void decodeInvalidMode() throws Exception { aes.decode(getTestFile().toFile(), null, "TEST", true, consoleKeyReader, null, 2); } }
923a22e041e96ef917fd39f2df17f9557485bebd
3,003
java
Java
src/main/java/fr/anatom3000/gwwhit/item/PortableBlackHoleItem.java
UniqueName12345/GuessWhatWillHappenInThis
2191524ef65bc9f27463074f2ca2f4c0f4af06df
[ "MIT" ]
61
2021-04-25T09:10:31.000Z
2022-02-16T20:10:20.000Z
src/main/java/fr/anatom3000/gwwhit/item/PortableBlackHoleItem.java
UniqueName12345/GuessWhatWillHappenInThis
2191524ef65bc9f27463074f2ca2f4c0f4af06df
[ "MIT" ]
43
2021-04-25T10:16:59.000Z
2021-12-28T14:18:41.000Z
src/main/java/fr/anatom3000/gwwhit/item/PortableBlackHoleItem.java
UniqueName12345/GuessWhatWillHappenInThis
2191524ef65bc9f27463074f2ca2f4c0f4af06df
[ "MIT" ]
40
2021-04-25T09:53:10.000Z
2022-01-22T16:39:46.000Z
35.75
99
0.614386
999,082
package fr.anatom3000.gwwhit.item; import io.netty.util.internal.ConcurrentSet; import net.minecraft.block.Blocks; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUsageContext; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; public class PortableBlackHoleItem extends Item { private static final HashMap<ItemStack, ConcurrentSet<BlockPos>> STORAGE = new HashMap<>(); public PortableBlackHoleItem(Settings settings) { super(settings); } private static void breakStoredBlocks(World world, ItemStack stack) { if (world.isClient || !STORAGE.containsKey(stack)) { return; } ArrayList<BlockPos> positions = new ArrayList<>(STORAGE.get(stack)); Collections.shuffle(positions); int size = Math.min( positions.size(), 256 ); for (int i = 0; i < size; ++i) { BlockPos pos = positions.get(i); if (!world.getBlockState(pos).isAir()) { world.removeBlock(positions.get(i), false); world.updateNeighbors(pos, Blocks.AIR); } STORAGE.get(stack).remove(pos); } } private static void storeBlocks(World world, BlockPos pos, int distance, ItemStack stack) { if (!STORAGE.containsKey(stack)) { STORAGE.put(stack, new ConcurrentSet<>()); } for (int x = -distance; x <= distance; ++x) { for (int y = -distance; y <= distance; ++y) { for (int z = -distance; z <= distance; ++z) { if (STORAGE.get(stack).size() >= 16384) { return; } BlockPos newPos = new BlockPos(pos.getX() + x, pos.getY() + y, pos.getZ() + z); if (!world.getBlockState(newPos).isAir()) { STORAGE.get(stack).add(newPos); } } } } } @Override public ActionResult useOnBlock(ItemUsageContext context) { if (context.getPlayer() != null) { context.getPlayer().setCurrentHand(context.getHand()); } BlockPos startPos = context.getBlockPos(); new Thread(() -> storeBlocks(context.getWorld(), startPos, 8, context.getStack())).start(); return ActionResult.CONSUME; } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity player, Hand hand) { player.setCurrentHand(hand); breakStoredBlocks(world, player.getStackInHand(hand)); return TypedActionResult.consume(player.getStackInHand(hand)); } @Override public int getMaxUseTime(ItemStack stack) { return 1; } }
923a233da93398f93b5ce4862fc94ba440decd3d
3,531
java
Java
chicory-core/src/main/java/com/github/sviperll/concurrent/TimeoutingLock.java
sviperll/chicory
a88b05b7031b0446db7793b387dc540a749a5b3f
[ "BSD-3-Clause" ]
5
2015-02-02T21:25:31.000Z
2015-12-27T14:50:47.000Z
chicory-core/src/main/java/com/github/sviperll/concurrent/TimeoutingLock.java
sviperll/chicory
a88b05b7031b0446db7793b387dc540a749a5b3f
[ "BSD-3-Clause" ]
1
2015-03-20T03:01:57.000Z
2015-03-29T20:54:36.000Z
chicory-core/src/main/java/com/github/sviperll/concurrent/TimeoutingLock.java
sviperll/chicory
a88b05b7031b0446db7793b387dc540a749a5b3f
[ "BSD-3-Clause" ]
null
null
null
37.648936
92
0.70924
999,083
/* * Copyright (c) 2013, Victor Nazarov <envkt@example.com> * 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 Victor Nazarov 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.github.sviperll.concurrent; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; /** * Timeouting lock is a decorator for some other Lock implementation. * TimeoutingLock is constructor with maximum wait time as a parameter. * TimeoutingLock#lock operation throws RuntimeTimeoutException when * lock can't be aquired in less then maximum wait time. * * TimeoutingLocks can be used when blocking is unacceptable. * Applications can use TimeoutingLocks and inform user about * resource being blocked instead of blocking. */ public class TimeoutingLock implements Lock { private final Lock lock; private final long time; private final TimeUnit unit; public TimeoutingLock(Lock lock, long time, TimeUnit unit) { this.lock = lock; this.time = time; this.unit = unit; } @Override public void lock() throws UncheckedTimeoutException { for (;;) { try { lockInterruptibly(); return; } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } @Override public void lockInterruptibly() throws UncheckedTimeoutException, InterruptedException { boolean success = lock.tryLock(time, unit); if (!success) throw new UncheckedTimeoutException("Lock timeouted"); } @Override public boolean tryLock() { return lock.tryLock(); } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return lock.tryLock(time, unit); } @Override public void unlock() throws UncheckedTimeoutException { lock.unlock(); } @Override public Condition newCondition() { return lock.newCondition(); } }
923a2462daf48af3966adb611221622fa0f0f16d
15,076
java
Java
singa-features/src/main/java/bio/singa/features/units/UnitRegistry.java
cleberecht/singa
839b8a418e52af216367251bed2992803d32bdb1
[ "MIT" ]
10
2016-09-07T09:53:42.000Z
2018-03-27T10:23:26.000Z
singa-features/src/main/java/bio/singa/features/units/UnitRegistry.java
cleberecht/singa
839b8a418e52af216367251bed2992803d32bdb1
[ "MIT" ]
81
2016-09-09T07:56:56.000Z
2018-07-24T12:11:30.000Z
singa-features/src/main/java/bio/singa/features/units/UnitRegistry.java
cleberecht/singa
839b8a418e52af216367251bed2992803d32bdb1
[ "MIT" ]
2
2018-12-31T17:05:19.000Z
2020-05-08T12:42:50.000Z
37.879397
135
0.652295
999,084
package bio.singa.features.units; import bio.singa.features.model.FeatureRegistry; import bio.singa.features.parameters.Environment; import bio.singa.features.quantities.MolarConcentration; import tech.units.indriya.quantity.Quantities; import tech.units.indriya.unit.TransformedUnit; import tech.units.indriya.unit.Units; import javax.measure.Dimension; import javax.measure.Quantity; import javax.measure.Unit; import javax.measure.quantity.*; import java.util.HashMap; import java.util.Map; import static bio.singa.features.units.UnitProvider.MICRO_MOLE_PER_LITRE; import static bio.singa.features.units.UnitProvider.MOLE_PER_LITRE; import static tech.units.indriya.AbstractUnit.ONE; import static tech.units.indriya.quantity.QuantityDimension.*; import static tech.units.indriya.unit.MetricPrefix.MICRO; import static tech.units.indriya.unit.MetricPrefix.NANO; import static tech.units.indriya.unit.Units.*; /** * @author cl */ public class UnitRegistry { /** * Standard node distance [L] (100 nm) */ public static final Quantity<Length> DEFAULT_SPACE = Quantities.getQuantity(1.0, MICRO(METRE)); /** * Standard time step size [T] (1 us) */ public static final Quantity<Time> DEFAULT_TIME = Quantities.getQuantity(1.0, MICRO(SECOND)); /** * Standard molar concentration unit [N] */ public static final Quantity<AmountOfSubstance> DEFAULT_AMOUNT_OF_SUBSTANCE = Quantities.getQuantity(1.0, NANO(MOLE)); public static final Unit<Temperature> DEFAULT_TEMPERATURE_UNIT = KELVIN; public static final Unit<Mass> DEFAULT_MASS_UNIT = GRAM; public static final Unit<Time> DISPLAY_TIME = SECOND; public static final Unit<Volume> DISPLAY_VOLUME = LITRE; public static final Unit<AmountOfSubstance> DISPLAY_AMOUNT = MICRO(MOLE); public static final Unit<MolarConcentration> DISPLAY_CONCENTRATION = MICRO_MOLE_PER_LITRE; public static final Unit<Length> DISPLAY_LENGTH = MICRO(METRE); private static UnitRegistry instance = getInstance(); private Quantity<Length> space; private Quantity<Time> time; private Map<Dimension, Unit> defaultUnits; private Map<Dimension, Unit> displayUnits; private UnitRegistry() { space = DEFAULT_SPACE; time = DEFAULT_TIME; defaultUnits = new HashMap<>(); defaultUnits.put(LENGTH, space.getUnit()); defaultUnits.put(TIME, time.getUnit()); defaultUnits.put(AMOUNT_OF_SUBSTANCE, DEFAULT_AMOUNT_OF_SUBSTANCE.getUnit()); defaultUnits.put(MASS, DEFAULT_MASS_UNIT); defaultUnits.put(TEMPERATURE, DEFAULT_TEMPERATURE_UNIT); displayUnits = new HashMap<>(); displayUnits.put(LENGTH, DISPLAY_LENGTH); displayUnits.put(TIME, DISPLAY_TIME); displayUnits.put(AMOUNT_OF_SUBSTANCE, DISPLAY_AMOUNT); displayUnits.put(MASS, DEFAULT_MASS_UNIT); displayUnits.put(TEMPERATURE, DEFAULT_TEMPERATURE_UNIT); displayUnits.put(LITRE.getDimension(), DISPLAY_VOLUME); displayUnits.put(MOLE_PER_LITRE.getDimension(), DISPLAY_CONCENTRATION); } private static UnitRegistry getInstance() { if (instance == null) { reinitialize(); } return instance; } public static void reinitialize() { synchronized (UnitRegistry.class) { instance = new UnitRegistry(); } } public static Quantity<Length> getSpace() { return getInstance().space; } public static void setSpace(Quantity<Length> space) { setSpaceScale(space.getValue().doubleValue()); setSpaceUnit(space.getUnit()); FeatureRegistry.scale(); } public static double getSpaceScale() { return getInstance().space.getValue().doubleValue(); } public static double getSpaceToPixelScale() { return Environment.getSimulationScale(); } public static double scaleSpaceToPixel(Quantity<Length> length) { return length.to(getSpaceUnit()).getValue().doubleValue() * getSpaceToPixelScale(); } public static Quantity<Length> getPixelToSpaceScale() { return Environment.getSystemScale(); } public static Quantity<Length> scalePixelToSpace(double length) { return getPixelToSpaceScale().multiply(length); } public static void setSpaceScale(double scale) { getInstance().space = Quantities.getQuantity(scale, getInstance().space.getUnit()); } public static Unit<Length> getSpaceUnit() { return getInstance().space.getUnit(); } public static void setSpaceUnit(Unit<Length> unit) { // only rescale if unit was updated getInstance().space = Quantities.getQuantity(getInstance().space.getValue().doubleValue(), unit); getInstance().defaultUnits.put(LENGTH, unit); Environment.updateScales(); rescaleRegisteredUnits(); } public static void resetSpace() { setSpaceScale(DEFAULT_SPACE.getValue().doubleValue()); setSpaceUnit(DEFAULT_SPACE.getUnit()); } public static Quantity<Time> getTime() { return getInstance().time; } public static void setTime(Quantity<Time> time) { double previousTime = getTime().getValue().doubleValue(); setTimeScale(time.getValue().doubleValue()); setTimeUnit(time.getUnit()); double currentTime = getTime().getValue().doubleValue(); double scalingFactor = currentTime / previousTime; FeatureRegistry.scale(scalingFactor); } public static double getTimeScale() { return getInstance().time.getValue().doubleValue(); } public static void setTimeScale(double scale) { getInstance().time = Quantities.getQuantity(scale, getInstance().time.getUnit()); } public static Unit<Time> getTimeUnit() { return getInstance().time.getUnit(); } public static void setTimeUnit(Unit<Time> unit) { if (!getInstance().time.getUnit().equals(unit)) { getInstance().time = Quantities.getQuantity(getInstance().time.getValue().doubleValue(), unit); getInstance().defaultUnits.put(TIME, unit); rescaleRegisteredUnits(); } } public static void resetTime() { setTimeScale(DEFAULT_TIME.getValue().doubleValue()); setTimeUnit(DEFAULT_TIME.getUnit()); } public static void setUnit(Unit<?> unit) { getInstance().defaultUnits.put(unit.getDimension(), unit); } public static Unit<MolarConcentration> getConcentrationUnit() { return getDefaultUnit(MOLE_PER_LITRE); } public static Unit<Area> getAreaUnit() { return getDefaultUnit(SQUARE_METRE); } public static Quantity<Area> getArea() { return getSpace().multiply(getSpace()).asType(Area.class); } public static Unit<Volume> getVolumeUnit() { return getDefaultUnit(CUBIC_METRE); } public static Quantity<Volume> getVolume() { return getSpace().multiply(getSpace()).multiply(getSpace()).asType(Volume.class); } public static Quantity<MolarConcentration> concentration(double value) { return Quantities.getQuantity(value, getConcentrationUnit()); } public static Quantity<MolarConcentration> concentration(double value, Unit<MolarConcentration> unit) { return Quantities.getQuantity(value, unit).to(getConcentrationUnit()); } public static <QuantityType extends Quantity<QuantityType>> Quantity<QuantityType> humanReadable(Quantity<QuantityType> quantity) { Dimension dimension = quantity.getUnit().getDimension(); if (!getInstance().displayUnits.containsKey(dimension)) { // not base unit and not registered addUnitForDimension(dimension, getInstance().displayUnits); } return quantity.to(getInstance().displayUnits.get(dimension)); } public static Quantity<MolarConcentration> humanReadable(double concentration) { return humanReadable(concentration(concentration)); } public static <QuantityType extends Quantity<QuantityType>> Quantity<QuantityType> scale(Quantity<QuantityType> quantity) { Quantity<QuantityType> convert = convert(quantity); double value = convert.getValue().doubleValue(); int spaceExponent = getSpaceExponent(convert.getUnit()); int timeExponent = getTimeExponent(convert.getUnit()); if (spaceExponent != 0 || timeExponent != 0) { if (spaceExponent > 0 && getSpaceScale() != 1.0) { value = value / Math.pow(getSpaceScale(), spaceExponent); } else { value = value * Math.pow(getSpaceScale(), Math.abs(spaceExponent)); } if (timeExponent > 0 && getSpaceScale() != 1.0) { value = value / Math.pow(getTimeScale(), timeExponent); } else { value = value * Math.pow(getTimeScale(), Math.abs(timeExponent)); } return Quantities.getQuantity(value, convert.getUnit()); } return convert; } public static <QuantityType extends Quantity<QuantityType>> Quantity<QuantityType> scaleForPixel(Quantity<QuantityType> quantity) { if (getSpaceToPixelScale() == 0.0) { throw new IllegalStateException("Space scale is not initialized."); } Quantity<QuantityType> convert = convert(quantity); double value = convert.getValue().doubleValue(); int spaceExponent = getSpaceExponent(convert.getUnit()); int timeExponent = getTimeExponent(convert.getUnit()); if (spaceExponent != 0 || timeExponent != 0) { if (spaceExponent > 0) { value = value * Math.pow(getSpaceToPixelScale(), spaceExponent); } else { value = value / Math.pow(getSpaceToPixelScale(), Math.abs(spaceExponent)); } if (timeExponent > 0) { value = value / Math.pow(getTimeScale(), timeExponent); } else { value = value * Math.pow(getTimeScale(), Math.abs(timeExponent)); } return Quantities.getQuantity(value, convert.getUnit()); } return convert; } public static <QuantityType extends Quantity<QuantityType>> Quantity<QuantityType> scaleTime(Quantity<QuantityType> quantity) { Quantity<QuantityType> convert = convert(quantity); double value = convert.getValue().doubleValue(); int timeExponent = getTimeExponent(convert.getUnit()); if (timeExponent != 0) { if (timeExponent > 0 && getSpaceScale() != 1.0) { value = value / Math.pow(getTimeScale(), timeExponent); } else { value = value * Math.pow(getTimeScale(), Math.abs(timeExponent)); } return Quantities.getQuantity(value, convert.getUnit()); } return convert; } public static <QuantityType extends Quantity<QuantityType>> Quantity<QuantityType> convert(Quantity<QuantityType> quantity) { Dimension dimension = quantity.getUnit().getDimension(); if (!getInstance().defaultUnits.containsKey(dimension)) { // not base unit and not registered addUnitForDimension(dimension, getInstance().defaultUnits); } return quantity.to(getInstance().defaultUnits.get(dimension)); } private static void rescaleRegisteredUnits() { for (Dimension next : getInstance().defaultUnits.keySet()) { if (next.getBaseDimensions() != null) { addUnitForDimension(next, getInstance().defaultUnits); } } } public static <UnitType extends Quantity<UnitType>> Unit<UnitType> getDefaultUnit(Unit<UnitType> unit) { Dimension dimension = unit.getDimension(); if (!getInstance().defaultUnits.containsKey(dimension)) { // not base unit and not registered addUnitForDimension(dimension, getInstance().defaultUnits); } return getInstance().defaultUnits.get(dimension); } private static void addUnitForDimension(Dimension dimension, Map<Dimension, Unit> unitMap) { Unit unit = ONE; for (Map.Entry<? extends Dimension, Integer> entry : dimension.getBaseDimensions().entrySet()) { unit = unit.multiply(getPreferredUnit(entry.getKey(), entry.getValue(), unitMap)); } unitMap.put(dimension, unit); } private static Unit getPreferredUnit(Dimension baseDimension, int exponent, Map<Dimension, Unit> unitMap) { if (unitMap.containsKey(baseDimension.pow(Math.abs(exponent)))) { // if there is a defined complex unit (such as concentration) if (exponent < 0) { Unit unit = unitMap.get(baseDimension.pow(Math.abs(exponent))); return ONE.divide(unit); } else { return unitMap.get(baseDimension.pow(exponent)); } } else if (unitMap.containsKey(baseDimension)) { // if time or space use system scale return unitMap.get(baseDimension).pow(exponent); } else { // else use si units return Units.getInstance().getUnits(baseDimension).iterator().next().pow(exponent); } } public static int getTimeExponent(Unit<?> unit) { return getExponent(unit, SECOND); } public static int getSpaceExponent(Unit<?> unit) { return getExponent(unit, METRE); } private static int getExponent(Unit<?> testUnit, Unit<?> requiredUnit) { // check eventual base units Map<? extends Unit<?>, Integer> baseUnits = testUnit.getBaseUnits(); if (baseUnits == null) { if (testUnit.getDimension().equals(requiredUnit.getDimension())) { return 1; } return 0; } for (Map.Entry<? extends Unit<?>, Integer> entry : baseUnits.entrySet()) { Unit<?> unit = entry.getKey(); if (unit.getDimension().equals(requiredUnit.getDimension())) { return entry.getValue(); } if (unit instanceof TransformedUnit) { int scale = getExponent(unit, requiredUnit); if (scale != 0) { return entry.getValue(); } } } return 0; } public static Map<Dimension, Unit> getDefaultUnits() { return getInstance().defaultUnits; } public static boolean isTimeUnit(Unit<?> unit) { return unit.isCompatible(SECOND); } public static boolean isInverseTimeUnit(Unit<?> unit) { return unit.isCompatible(ONE.divide(SECOND)); } public static boolean isLengthUnit(Unit<?> unit) { return unit.isCompatible(METRE); } public static boolean isSubstanceUnit(Unit<?> unit) { return unit.isCompatible(MOLE); } public static boolean isConcentrationUnit(Unit<?> unit) { return unit.isCompatible(MOLE_PER_LITRE); } }
923a256b85ade59ba9797ec638842fc736cd0b38
4,473
java
Java
jans-client-api/server/src/main/java/io/jans/ca/server/service/RpService.java
JanssenProject/jans
8d57d01b998bfe87a2377bbe9023dd97fb03cc9f
[ "Apache-2.0" ]
18
2022-01-13T13:45:13.000Z
2022-03-30T04:41:18.000Z
jans-client-api/server/src/main/java/io/jans/ca/server/service/RpService.java
JanssenProject/jans
8d57d01b998bfe87a2377bbe9023dd97fb03cc9f
[ "Apache-2.0" ]
604
2022-01-13T12:32:50.000Z
2022-03-31T20:27:36.000Z
jans-client-api/server/src/main/java/io/jans/ca/server/service/RpService.java
JanssenProject/jans
8d57d01b998bfe87a2377bbe9023dd97fb03cc9f
[ "Apache-2.0" ]
8
2022-01-28T00:23:25.000Z
2022-03-16T05:12:12.000Z
28.132075
171
0.633803
999,085
package io.jans.ca.server.service; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.Maps; import io.jans.as.client.RegisterClient; import io.jans.as.client.RegisterRequest; import io.jans.ca.server.configuration.model.Rp; import io.jans.ca.server.op.OpClientFactoryImpl; import io.jans.ca.server.persistence.service.PersistenceServiceImpl; import io.jans.ca.server.persistence.service.MainPersistenceService; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * @author Yuriy Zabrovarnyy */ @ApplicationScoped public class RpService { @Inject Logger logger; private static Cache<String, Rp> rpCache; @Inject MainPersistenceService jansConfigurationService; @Inject ValidationService validationService; @Inject PersistenceServiceImpl persistenceService; @Inject OpClientFactoryImpl opClientFactory; @Inject HttpService httpService; private Cache<String, Rp> getRpCache() { if (rpCache != null) { return rpCache; } else { return CacheBuilder.newBuilder() .expireAfterWrite(jansConfigurationService.findConf() != null ? jansConfigurationService.find().getRpCacheExpirationInMinutes() : 60, TimeUnit.MINUTES) .build(); } } public void removeAllRps() { getRpCache().invalidateAll(); persistenceService.removeAllRps(); } public void load() { Set<Rp> rps = persistenceService.getRps(); if (rps == null) return; for (Rp rp : rps) { put(rp); } } public Rp getRp(String rpId) { Preconditions.checkNotNull(rpId); Preconditions.checkState(!Strings.isNullOrEmpty(rpId)); Rp rp = getRpCache().getIfPresent(rpId); if (rp == null) { rp = persistenceService.getRp(rpId); if (rp != null) { getRpCache().put(rpId, rp); } } rp = validationService.validate(rp); return rp; } public Map<String, Rp> getRps() { return Maps.newHashMap(getRpCache().asMap()); } public void update(Rp rp) { put(rp); persistenceService.update(rp); } public void updateSilently(Rp rp) { try { update(rp); } catch (Exception e) { logger.error("Failed to update site configuration: " + rp, e); } } public void create(Rp rp) { if (StringUtils.isBlank(rp.getRpId())) { rp.setRpId(UUID.randomUUID().toString()); } if (getRpCache().getIfPresent(rp.getRpId()) == null) { put(rp); persistenceService.create(rp); } else { logger.error("RP already exists in database, rp_id: {}", rp.getRpId()); } } private Rp put(Rp rp) { getRpCache().put(rp.getRpId(), rp); return rp; } public boolean remove(String rpId) { boolean ok = persistenceService.remove(rpId); if (ok) { getRpCache().invalidate(rpId); } return ok; } public Rp getRpByClientId(String clientId) { for (Rp rp : getRpCache().asMap().values()) { if (rp.getClientId().equalsIgnoreCase(clientId)) { logger.trace("Found rp by client_id: {}, rp: {}", clientId, rp); return rp; } } return null; } public Rp defaultRp() { return jansConfigurationService.find().getDefaultSiteConfig(); } public RegisterClient createRegisterClient(String registrationEndpoint, RegisterRequest registerRequest) { RegisterClient registerClient = opClientFactory.createRegisterClient(registrationEndpoint); registerClient.setRequest(registerRequest); registerClient.setExecutor(httpService.getClientEngine()); return registerClient; } public MainPersistenceService getConfigurationService() { return jansConfigurationService; } public PersistenceServiceImpl getPersistenceService() { return persistenceService; } }
923a26164084e322b7221eaf5e1e69ff3c09c5b5
1,874
java
Java
engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapVO.java
tsinik-dw/cloudstack
f17683779c7cb37ba5a52bf154e14680c6b60f93
[ "Apache-2.0" ]
1,131
2015-01-08T18:59:06.000Z
2022-03-29T11:31:10.000Z
engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapVO.java
RodrigoDLopez/cloudstack
6b757d502e1e827842bcaddc283503b95c8ce202
[ "Apache-2.0" ]
5,908
2015-01-13T15:28:37.000Z
2022-03-31T20:31:07.000Z
engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapVO.java
RodrigoDLopez/cloudstack
6b757d502e1e827842bcaddc283503b95c8ce202
[ "Apache-2.0" ]
1,083
2015-01-05T01:16:52.000Z
2022-03-31T12:14:10.000Z
29.746032
75
0.732124
999,086
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.network.dao; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "inline_load_balancer_nic_map") public class InlineLoadBalancerNicMapVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; @Column(name = "public_ip_address") private String publicIpAddress; @Column(name = "nic_id") private long nicId; public InlineLoadBalancerNicMapVO() { } public InlineLoadBalancerNicMapVO(String publicIpAddress, long nicId) { this.publicIpAddress = publicIpAddress; this.nicId = nicId; } @Override public long getId() { return id; } public String getPublicIpAddress() { return publicIpAddress; } public long getNicId() { return nicId; } }
923a26a9e192938cfaac07a6ffc9fd494f7da521
360
java
Java
sources/b/l/a/c/f/e/kb.java
tonioshikanlu/tubman-hack
8277e47c058174ca4411965ed67d05d2aba1c7fc
[ "MIT" ]
2
2021-03-20T07:33:30.000Z
2021-06-29T18:50:21.000Z
sources/b/l/a/c/f/e/kb.java
tonioshikanlu/tubman-hack
8277e47c058174ca4411965ed67d05d2aba1c7fc
[ "MIT" ]
null
null
null
sources/b/l/a/c/f/e/kb.java
tonioshikanlu/tubman-hack
8277e47c058174ca4411965ed67d05d2aba1c7fc
[ "MIT" ]
2
2021-03-20T15:56:20.000Z
2021-03-21T02:06:29.000Z
32.727273
114
0.730556
999,087
package b.l.a.c.f.e; import java.security.KeyPairGenerator; import java.security.Provider; public final class kb implements mb<KeyPairGenerator> { public final /* bridge */ /* synthetic */ Object a(String str, Provider provider) { return provider == null ? KeyPairGenerator.getInstance(str) : KeyPairGenerator.getInstance(str, provider); } }
923a26bf6e369234191be7345af5ad345e93c9b4
1,585
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Juding_Launcher_Low.java
ftc8424/sdk_22
8616f2a245768dba6d8524144982317ac4225a8a
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Juding_Launcher_Low.java
ftc8424/sdk_22
8616f2a245768dba6d8524144982317ac4225a8a
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Juding_Launcher_Low.java
ftc8424/sdk_22
8616f2a245768dba6d8524144982317ac4225a8a
[ "MIT" ]
null
null
null
32.346939
104
0.661199
999,088
//package org.firstinspires.ftc.teamcode; // ///** // * Created by FTC8424 on 1/14/2017. // */ // //import com.qualcomm.robotcore.eventloop.opmode.Autonomous; //import com.qualcomm.robotcore.eventloop.opmode.Disabled; //import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; //import com.qualcomm.robotcore.eventloop.opmode.OpMode; //import com.qualcomm.robotcore.util.ElapsedTime; // // //import static org.firstinspires.ftc.teamcode.HardwareHelper.RobotType.FULLAUTO; // //@Autonomous(name = "Judging_Launcher_Low", group = "Judge") // //public class Juding_Launcher_Low extends LinearOpMode{ // // HardwareHelper robot = new HardwareHelper(FULLAUTO); // // private double servoUpTime = 0; // private ElapsedTime runtime = new ElapsedTime(); // // @Override // public void runOpMode() throws InterruptedException { // robot.robot_init(hardwareMap); // // telemetry.addData("Init:", "Waiting for start"); // telemetry.update(); // idle(); // waitForStart(); // // //// robot.launchMotor1.setPower(0.35); //// telemetry.addData("Motor", "LaunchPower Set to " + robot.launchMotor1.getCurrentPosition()); //// robot.launchMotor2.setPower(0.35); //// telemetry.addData("Motor", "LaunchPower Set to " + robot.launchMotor2.getCurrentPosition()); //// sleep(2500); //// if ( !opModeIsActive() ) return; //// telemetry.addData("Status", "Debug 1 at: " + runtime.toString()); //// robot.launchServo.setPosition(robot.launchliftDeploy); //// sleep(500); // // // // } //}
923a27586eed4d2aceb77069b803089ac91da205
2,151
java
Java
src/main/java/org/rx/security/MD5Util.java
RockyLOMO/rxlib
a0e1c91aaafc87050553738b21c6d16292e5d93c
[ "Apache-2.0" ]
14
2017-08-24T08:25:13.000Z
2021-07-21T07:04:35.000Z
src/main/java/org/rx/security/MD5Util.java
RockyLOMO/rxlib
a0e1c91aaafc87050553738b21c6d16292e5d93c
[ "Apache-2.0" ]
5
2020-08-25T05:46:06.000Z
2022-03-11T14:04:22.000Z
src/main/java/org/rx/security/MD5Util.java
RockyLOMO/rxlib
a0e1c91aaafc87050553738b21c6d16292e5d93c
[ "Apache-2.0" ]
1
2017-10-25T08:17:33.000Z
2017-10-25T08:17:33.000Z
32.104478
83
0.582055
999,089
package org.rx.security; import io.netty.buffer.ByteBufUtil; import lombok.NonNull; import lombok.SneakyThrows; import org.rx.io.Bytes; import org.rx.io.FileStream; import java.io.File; import java.security.MessageDigest; public class MD5Util { @SneakyThrows public static byte[] md5(File file) { try (FileStream fs = new FileStream(file)) { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] buf = Bytes.arrayBuffer(); int read; while ((read = fs.read(buf)) > 0) { md.update(buf, 0, read); } return md.digest(); } } public static byte[] md5(@NonNull String data) { return md5(data.getBytes()); } @SneakyThrows public static byte[] md5(@NonNull byte[] data) { MessageDigest md = MessageDigest.getInstance("MD5"); return md.digest(data); } public static String md5Hex(@NonNull String data) { return md5Hex(data.getBytes()); } public static String md5Hex(@NonNull byte[] data) { return ByteBufUtil.hexDump(md5(data)); } // /** // * 方法md5HashCode32 中 ((int) md5Bytes[i]) & 0xff 操作的解释: // * 在Java语言中涉及到字节byte数组数据的一些操作时,经常看到 byte[i] & 0xff这样的操作,这里就记录总结一下这里包含的意义: // * 1、0xff是16进制(十进制是255),它默认为整形,二进制位为32位,最低八位是“1111 1111”,其余24位都是0。 2、&运算: // * 如果2个bit都是1,则得1,否则得0; 3、byte[i] & // * 0xff:首先,这个操作一般都是在将byte数据转成int或者其他整形数据的过程中;使用了这个操作,最终的整形数据只有低8位有数据,其他位数都为0。 // * 4、这个操作得出的整形数据都是大于等于0并且小于等于255的 // */ // public static String toHexString(byte[] data) { // // 用字节表示就是 16 个字节 // char[] str = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符, // // 所以表示成 16 进制需要 32 个字符 // int k = 0; // 表示转换结果中对应的字符位置 // for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节 // // 转换成 16 进制字符的转换 // byte byte0 = data[i]; // 取第 i 个字节 // str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, >>>, // // 逻辑右移,将符号位一起右移 // str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换 // } // return new String(str); // 换后的结果转换为字符串 // } }
923a27710f56f6610bf6bfe03a7550dba84fb8b9
14,965
java
Java
src/main/java/org/simplejavamail/email/Email.java
ragunath90/JavaMail-API
1ef21afecbe9658e9b6a97555528bf84bbc49313
[ "Apache-2.0" ]
null
null
null
src/main/java/org/simplejavamail/email/Email.java
ragunath90/JavaMail-API
1ef21afecbe9658e9b6a97555528bf84bbc49313
[ "Apache-2.0" ]
null
null
null
src/main/java/org/simplejavamail/email/Email.java
ragunath90/JavaMail-API
1ef21afecbe9658e9b6a97555528bf84bbc49313
[ "Apache-2.0" ]
null
null
null
32.252155
143
0.71694
999,090
package org.simplejavamail.email; import org.simplejavamail.internal.util.MimeMessageParser; import javax.activation.DataSource; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.util.ByteArrayDataSource; import java.io.*; import java.util.*; import java.util.regex.Pattern; import static java.lang.String.format; import static org.simplejavamail.internal.util.ConfigLoader.Property.*; import static org.simplejavamail.internal.util.ConfigLoader.getProperty; import static org.simplejavamail.internal.util.ConfigLoader.hasProperty; /** * Email message with all necessary data for an effective mailing action, including attachments etc. * * @author Benny Bottema */ @SuppressWarnings("SameParameterValue") public class Email { /** * The sender of the email. Can be used in conjunction with {@link #replyToRecipient}. */ private Recipient fromRecipient; /** * The reply-to-address, optional. Can be used in conjunction with {@link #fromRecipient}. */ private Recipient replyToRecipient; /** * The email message body in plain text. */ private String text; /** * The email message body in html. */ private String textHTML; /** * The subject of the email message. */ private String subject; /** * List of {@link Recipient}. */ private final List<Recipient> recipients; /** * List of {@link AttachmentResource}. */ private final List<AttachmentResource> embeddedImages; /** * List of {@link AttachmentResource}. */ private final List<AttachmentResource> attachments; /** * Map of header name and values, such as <code>X-Priority</code> etc. */ private final Map<String, String> headers; /* DKIM properties */ private boolean applyDKIMSignature = false; private InputStream dkimPrivateKeyInputStream; private String signingDomain; private String selector; /** * Constructor, creates all internal lists. Populates default from, reply-to, to, cc and bcc if provided in the config file. */ public Email() { recipients = new ArrayList<>(); embeddedImages = new ArrayList<>(); attachments = new ArrayList<>(); headers = new HashMap<>(); if (hasProperty(DEFAULT_FROM_ADDRESS)) { setFromAddress((String) getProperty(DEFAULT_FROM_NAME), (String) getProperty(DEFAULT_FROM_ADDRESS)); } if (hasProperty(DEFAULT_REPLYTO_ADDRESS)) { setReplyToAddress((String) getProperty(DEFAULT_REPLYTO_NAME), (String) getProperty(DEFAULT_REPLYTO_ADDRESS)); } if (hasProperty(DEFAULT_TO_ADDRESS)) { addRecipient((String) getProperty(DEFAULT_TO_NAME), (String) getProperty(DEFAULT_TO_ADDRESS), RecipientType.TO); } if (hasProperty(DEFAULT_CC_ADDRESS)) { addRecipient((String) getProperty(DEFAULT_CC_NAME), (String) getProperty(DEFAULT_CC_ADDRESS), RecipientType.CC); } if (hasProperty(DEFAULT_BCC_ADDRESS)) { addRecipient((String) getProperty(DEFAULT_BCC_NAME), (String) getProperty(DEFAULT_BCC_ADDRESS), RecipientType.BCC); } if (hasProperty(DEFAULT_SUBJECT)) { setSubject((String) getProperty(DEFAULT_SUBJECT)); } } /** * @see #signWithDomainKey(InputStream, String, String) */ @SuppressWarnings("WeakerAccess") public void signWithDomainKey(final File dkimPrivateKeyFile, final String signingDomain, final String selector) { FileInputStream dkimPrivateKeyInputStream = null; try { dkimPrivateKeyInputStream = new FileInputStream(dkimPrivateKeyFile); signWithDomainKey(dkimPrivateKeyInputStream, signingDomain, selector); } catch (final FileNotFoundException e) { throw new EmailException(format(EmailException.DKIM_ERROR_INVALID_FILE, dkimPrivateKeyFile), e); } finally { if (dkimPrivateKeyInputStream != null) { try { dkimPrivateKeyInputStream.close(); } catch (final IOException e) { //noinspection ThrowFromFinallyBlock throw new EmailException(format(EmailException.DKIM_ERROR_UNCLOSABLE_INPUTSTREAM, e.getMessage()), e); } } } } /** * Primes this email for signing with a DKIM domain key. Actual signing is done when sending using a <code>Mailer</code>. * <p/> * Also see: * <pre><ul> * <li>https://postmarkapp.com/guides/dkim</li> * <li>https://github.com/markenwerk/java-utils-mail-dkim</li> * <li>http://www.gettingemaildelivered.com/dkim-explained-how-to-set-up-and-use-domainkeys-identified-mail-effectively</li> * <li>https://en.wikipedia.org/wiki/DomainKeys_Identified_Mail</li> * </ul></pre> * * @param dkimPrivateKeyInputStream De key content used to sign for the sending party. * @param signingDomain The domain being authorized to send. * @param selector Additional domain specifier. */ @SuppressWarnings("WeakerAccess") public void signWithDomainKey(final InputStream dkimPrivateKeyInputStream, final String signingDomain, final String selector) { this.applyDKIMSignature = true; this.dkimPrivateKeyInputStream = dkimPrivateKeyInputStream; this.signingDomain = signingDomain; this.selector = selector; } /** * Sets the sender address. * * @param name The sender's name. * @param fromAddress The sender's email address. */ public void setFromAddress(final String name, final String fromAddress) { fromRecipient = new Recipient(name, fromAddress, null); } /** * Sets the reply-to address (optional). * * @param name The replied-to-receiver name. * @param replyToAddress The replied-to-receiver email address. */ public void setReplyToAddress(final String name, final String replyToAddress) { replyToRecipient = new Recipient(name, replyToAddress, null); } /** * Bean setters for {@link #subject}. */ public void setSubject(final String subject) { this.subject = subject; } /** * Bean setters for {@link #text}. */ public void setText(final String text) { this.text = text; } /** * Bean setters for {@link #textHTML}. */ public void setTextHTML(final String textHTML) { this.textHTML = textHTML; } /** * Adds a new {@link Recipient} to the list on account of name, address and recipient type (eg. {@link RecipientType#CC}). * * @param name The name of the recipient. * @param address The emailadres of the recipient. * @param type The type of receiver (eg. {@link RecipientType#CC}). * @see #recipients * @see Recipient * @see RecipientType */ public void addRecipient(final String name, final String address, final RecipientType type) { recipients.add(new Recipient(name, address, type)); } /** * Adds an embedded image (attachment type) to the email message and generates the necessary {@link DataSource} with the given byte data. Then * delegates to {@link #addEmbeddedImage(String, DataSource)}. At this point the datasource is actually a {@link ByteArrayDataSource}. * * @param name The name of the image as being referred to from the message content body (eg. '&lt;cid:signature&gt;'). * @param data The byte data of the image to be embedded. * @param mimetype The content type of the given data (eg. "image/gif" or "image/jpeg"). * @see ByteArrayDataSource * @see #addEmbeddedImage(String, DataSource) */ public void addEmbeddedImage(final String name, final byte[] data, final String mimetype) { final ByteArrayDataSource dataSource = new ByteArrayDataSource(data, mimetype); dataSource.setName(name); addEmbeddedImage(name, dataSource); } /** * Overloaded method which sets an embedded image on account of name and {@link DataSource}. * * @param name The name of the image as being referred to from the message content body (eg. '&lt;cid:embeddedimage&gt;'). * @param imagedata The image data. */ @SuppressWarnings("WeakerAccess") public void addEmbeddedImage(final String name, final DataSource imagedata) { embeddedImages.add(new AttachmentResource(name, imagedata)); } /** * Adds a header to the {@link #headers} list. The value is stored as a <code>String</code>. example: <code>email.addHeader("X-Priority", * 2)</code> * * @param name The name of the header. * @param value The value of the header, which will be stored using {@link String#valueOf(Object)}. */ @SuppressWarnings("WeakerAccess") public void addHeader(final String name, final Object value) { headers.put(name, String.valueOf(value)); } /** * Adds an attachment to the email message and generates the necessary {@link DataSource} with the given byte data. Then delegates to {@link * #addAttachment(String, DataSource)}. At this point the datasource is actually a {@link ByteArrayDataSource}. * * @param name The name of the extension (eg. filename including extension). * @param data The byte data of the attachment. * @param mimetype The content type of the given data (eg. "plain/text", "image/gif" or "application/pdf"). * @see ByteArrayDataSource * @see #addAttachment(String, DataSource) */ public void addAttachment(final String name, final byte[] data, final String mimetype) { final ByteArrayDataSource dataSource = new ByteArrayDataSource(data, mimetype); dataSource.setName(name); addAttachment(name, dataSource); } /** * Overloaded method which sets an attachment on account of name and {@link DataSource}. * * @param name The name of the attachment (eg. 'filename.ext'). * @param filedata The attachment data. */ public void addAttachment(final String name, final DataSource filedata) { attachments.add(new AttachmentResource(name, filedata)); } /** * Bean getter for {@link #fromRecipient}. */ public Recipient getFromRecipient() { return fromRecipient; } /** * Bean getter for {@link #replyToRecipient}. */ public Recipient getReplyToRecipient() { return replyToRecipient; } /** * Bean getter for {@link #subject}. */ public String getSubject() { return subject; } /** * Bean getter for {@link #text}. */ public String getText() { return text; } /** * Bean getter for {@link #textHTML}. */ public String getTextHTML() { return textHTML; } /** * Bean getter for {@link #attachments} as unmodifiable list. */ public List<AttachmentResource> getAttachments() { return Collections.unmodifiableList(attachments); } /** * Bean getter for {@link #embeddedImages} as unmodifiable list. */ public List<AttachmentResource> getEmbeddedImages() { return Collections.unmodifiableList(embeddedImages); } /** * Bean getter for {@link #recipients} as unmodifiable list. */ public List<Recipient> getRecipients() { return Collections.unmodifiableList(recipients); } /** * Bean getter for {@link #headers} as unmodifiable map. */ public Map<String, String> getHeaders() { return Collections.unmodifiableMap(headers); } public boolean isApplyDKIMSignature() { return applyDKIMSignature; } public InputStream getDkimPrivateKeyInputStream() { return dkimPrivateKeyInputStream; } public String getSigningDomain() { return signingDomain; } public String getSelector() { return selector; } @Override public int hashCode() { return 0; } @Override public boolean equals(final Object o) { return (this == o) || (o != null && getClass() == o.getClass() && EqualsHelper.equalsEmail(this, (Email) o)); } @Override public String toString() { return "Email{" + "\n\tfromRecipient=" + fromRecipient + ",\n\treplyToRecipient=" + replyToRecipient + ",\n\ttext='" + text + '\'' + ",\n\ttextHTML='" + textHTML + '\'' + ",\n\tsubject='" + subject + '\'' + ",\n\trecipients=" + recipients + ",\n\tembeddedImages=" + embeddedImages + ",\n\tattachments=" + attachments + ",\n\theaders=" + headers + "\n}"; } /** * Constructor for the Builder class * * @param builder The builder from which to create the email. */ Email(final EmailBuilder builder) { recipients = builder.getRecipients(); embeddedImages = builder.getEmbeddedImages(); attachments = builder.getAttachments(); headers = builder.getHeaders(); fromRecipient = builder.getFromRecipient(); replyToRecipient = builder.getReplyToRecipient(); text = builder.getText(); textHTML = builder.getTextHTML(); subject = builder.getSubject(); if (builder.getDkimPrivateKeyFile() != null) { signWithDomainKey(builder.getDkimPrivateKeyFile(), builder.getSigningDomain(), builder.getSelector()); } else if (builder.getDkimPrivateKeyInputStream() != null) { signWithDomainKey(builder.getDkimPrivateKeyInputStream(), builder.getSigningDomain(), builder.getSelector()); } } /* * Email from MimeMessage * * @author Benny Bottema */ /** * Constructor for {@link javax.mail.internet.MimeMessage}. * <p> * <strong>Doen add default recipient that may have been provided in a config file.</strong> * * @param mimeMessage The MimeMessage from which to create the email. */ public Email(final MimeMessage mimeMessage) { recipients = new ArrayList<>(); embeddedImages = new ArrayList<>(); attachments = new ArrayList<>(); headers = new HashMap<>(); try { fillEmailFromMimeMessage(new MimeMessageParser(mimeMessage).parse()); } catch (MessagingException | IOException e) { throw new EmailException(format(EmailException.PARSE_ERROR_MIMEMESSAGE, e.getMessage()), e); } } private void fillEmailFromMimeMessage(final MimeMessageParser parser) throws MessagingException { final InternetAddress from = parser.getFrom(); this.setFromAddress(from.getPersonal(), from.getAddress()); final InternetAddress replyTo = parser.getReplyTo(); this.setReplyToAddress(replyTo.getPersonal(), replyTo.getAddress()); for (final Map.Entry<String, Object> header : parser.getHeaders().entrySet()) { this.addHeader(header.getKey(), header.getValue()); } for (final InternetAddress to : parser.getTo()) { this.addRecipient(to.getPersonal(), to.getAddress(), RecipientType.TO); } //noinspection QuestionableName for (final InternetAddress cc : parser.getCc()) { this.addRecipient(cc.getPersonal(), cc.getAddress(), RecipientType.CC); } for (final InternetAddress bcc : parser.getBcc()) { this.addRecipient(bcc.getPersonal(), bcc.getAddress(), RecipientType.BCC); } this.setSubject(parser.getSubject()); this.setText(parser.getPlainContent()); this.setTextHTML(parser.getHtmlContent()); for (final Map.Entry<String, DataSource> cid : parser.getCidMap().entrySet()) { this.addEmbeddedImage(extractCID(cid.getKey()), cid.getValue()); } for (final Map.Entry<String, DataSource> attachment : parser.getAttachmentList().entrySet()) { this.addAttachment(extractCID(attachment.getKey()), attachment.getValue()); } } private static final Pattern MATCH_INSIDE_CIDBRACKETS = Pattern.compile("<?([^>]*)>?"); static String extractCID(final String cid) { return (cid != null) ? MATCH_INSIDE_CIDBRACKETS.matcher(cid).replaceAll("$1") : null; } }
923a27cc9430b06150521582a384534e04f51c83
2,355
java
Java
src/main/java/com/wedeploy/android/query/filter/Range.java
inacionery/wedeploy-sdk-android
bf7591fa70bbf05f4f9a6d3edeb06ac682768ae9
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/wedeploy/android/query/filter/Range.java
inacionery/wedeploy-sdk-android
bf7591fa70bbf05f4f9a6d3edeb06ac682768ae9
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/wedeploy/android/query/filter/Range.java
inacionery/wedeploy-sdk-android
bf7591fa70bbf05f4f9a6d3edeb06ac682768ae9
[ "BSD-3-Clause" ]
null
null
null
29.810127
79
0.73673
999,091
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Liferay, Inc. 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.wedeploy.android.query.filter; import com.wedeploy.android.query.BodyConvertible; import java.util.HashMap; import java.util.Map; /** * Range builder. */ public final class Range extends BodyConvertible { public static Range from(Object value) { return new Range(value, null); } public static Range range(Object from, Object to) { return new Range(from, to); } public static Range to(Object value) { return new Range(null, value); } @Override public Map body() { Map map = new HashMap(); if (from != null) { map.put("from", from); } if (to != null) { map.put("to", to); } return map; } protected final Object from; protected final Object to; private Range(Object from, Object to) { this.from = from; this.to = to; } }
923a27dfe0ec368976b3f0453301d001ca6c8d4b
2,575
java
Java
src/main/java/com/github/srgsf/simkl/model/SyncStatus.java
srgsf/simkl-client
ab7c1ff6c47da6e65b850b51beee3aa1b7d64746
[ "Unlicense" ]
null
null
null
src/main/java/com/github/srgsf/simkl/model/SyncStatus.java
srgsf/simkl-client
ab7c1ff6c47da6e65b850b51beee3aa1b7d64746
[ "Unlicense" ]
1
2020-08-26T16:30:21.000Z
2020-08-26T16:30:21.000Z
src/main/java/com/github/srgsf/simkl/model/SyncStatus.java
srgsf/simkl-client
ab7c1ff6c47da6e65b850b51beee3aa1b7d64746
[ "Unlicense" ]
null
null
null
28.296703
102
0.625243
999,092
/* * 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 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.github.srgsf.simkl.model; import com.squareup.moshi.Json; import java.util.ArrayList; import java.util.List; public class SyncStatus { @Json(name = "added") public final Counter added; @Json(name = "updated") public final Counter updated; @Json(name = "existing") public final Counter existing; @Json(name = "deleted") public final Counter deleted; @Json(name = "not_found") public final NotFound notFound; @SuppressWarnings("unused") SyncStatus(Counter added, Counter updated, Counter existing, Counter deleted, NotFound notFound) { this.added = added; this.updated = updated; this.existing = existing; this.deleted = deleted; this.notFound = notFound; } public static class Counter { @Json(name = "movies") public final Integer movies; @Json(name = "shows") public final Integer shows; @Json(name = "episodes") public final Integer episodes; @SuppressWarnings("unused") Counter(Integer movies, Integer shows, Integer episodes) { this.movies = movies; this.shows = shows; this.episodes = episodes; } } public static class NotFound { @Json(name = "movies") public final List<MediaObject> movies = new ArrayList<>(); @Json(name = "shows") public final List<MediaObject> shows = new ArrayList<>(); @Json(name = "seasons") public final List<MediaObject> seasons = new ArrayList<>(); @Json(name = "episodes") public final List<MediaObject> episodes = new ArrayList<>(); } public static class MediaObject { @Json(name = "title") public final String title; @Json(name = "year") public final Integer year; @Json(name = "ids") public final Ids ids; @SuppressWarnings("unused") MediaObject(String title, Integer year, Ids ids) { this.title = title; this.year = year; this.ids = ids; } } }
923a281d2eca27bb58b225d1d067d46e29f12721
5,962
java
Java
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/project/grantofferletter/builder/GrantOfferLetterIndustrialFinanceTableBuilder.java
adambirse/innovation-funding-service
db1c2bc5a25d3143df02bef9019aefd5261caf6f
[ "MIT" ]
null
null
null
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/project/grantofferletter/builder/GrantOfferLetterIndustrialFinanceTableBuilder.java
adambirse/innovation-funding-service
db1c2bc5a25d3143df02bef9019aefd5261caf6f
[ "MIT" ]
null
null
null
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/project/grantofferletter/builder/GrantOfferLetterIndustrialFinanceTableBuilder.java
adambirse/innovation-funding-service
db1c2bc5a25d3143df02bef9019aefd5261caf6f
[ "MIT" ]
null
null
null
49.683333
167
0.760148
999,093
package org.innovateuk.ifs.project.grantofferletter.builder; import org.innovateuk.ifs.BaseBuilder; import org.innovateuk.ifs.project.grantofferletter.model.GrantOfferLetterIndustrialFinanceTable; import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.setField; import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.uniqueIds; /** * Builder for GrantOfferLetterIndustrialFinanceTables. */ public class GrantOfferLetterIndustrialFinanceTableBuilder extends BaseBuilder<GrantOfferLetterIndustrialFinanceTable, GrantOfferLetterIndustrialFinanceTableBuilder> { private GrantOfferLetterIndustrialFinanceTableBuilder(List<BiConsumer<Integer, GrantOfferLetterIndustrialFinanceTable>> multiActions) { super(multiActions); } public static GrantOfferLetterIndustrialFinanceTableBuilder newGrantOfferLetterIndustrialFinanceTable() { return new GrantOfferLetterIndustrialFinanceTableBuilder(emptyList()); } @Override protected GrantOfferLetterIndustrialFinanceTableBuilder createNewBuilderWithActions(List<BiConsumer<Integer, GrantOfferLetterIndustrialFinanceTable>> actions) { return new GrantOfferLetterIndustrialFinanceTableBuilder(actions); } @Override protected GrantOfferLetterIndustrialFinanceTable createInitial() { String dummyOrgName = "Org"; BigDecimal dummyCost = BigDecimal.ZERO; Map<String, BigDecimal> dummyCosts = singletonMap(dummyOrgName, dummyCost); return new GrantOfferLetterIndustrialFinanceTable( dummyCosts, dummyCosts, dummyCosts, dummyCosts, dummyCosts, dummyCosts, dummyCosts, dummyCost, dummyCost, dummyCost, dummyCost, dummyCost, dummyCost, dummyCost, singletonList(dummyOrgName) ); } public GrantOfferLetterIndustrialFinanceTableBuilder withLabour(Map<String, BigDecimal>... labour) { return withArray((costs, industrialFinanceTable) -> setField("labour", costs, industrialFinanceTable), labour); } public GrantOfferLetterIndustrialFinanceTableBuilder withMaterials(Map<String, BigDecimal>... materials) { return withArray((costs, industrialFinanceTable) -> setField("materials", costs, industrialFinanceTable), materials); } public GrantOfferLetterIndustrialFinanceTableBuilder withOverheads(Map<String, BigDecimal>... overheads) { return withArray((costs, industrialFinanceTable) -> setField("overheads", costs, industrialFinanceTable), overheads); } public GrantOfferLetterIndustrialFinanceTableBuilder withCapitalUsage(Map<String, BigDecimal>... capitalUsage) { return withArray((costs, industrialFinanceTable) -> setField("capitalUsage", costs, industrialFinanceTable), capitalUsage); } public GrantOfferLetterIndustrialFinanceTableBuilder withSubcontract(Map<String, BigDecimal>... subcontract) { return withArray((costs, industrialFinanceTable) -> setField("subcontract", costs, industrialFinanceTable), subcontract); } public GrantOfferLetterIndustrialFinanceTableBuilder withTravel(Map<String, BigDecimal>... travel) { return withArray((costs, industrialFinanceTable) -> setField("travel", costs, industrialFinanceTable), travel); } public GrantOfferLetterIndustrialFinanceTableBuilder withOtherCosts(Map<String, BigDecimal>... otherCosts) { return withArray((costs, industrialFinanceTable) -> setField("otherCosts", costs, industrialFinanceTable), otherCosts); } public GrantOfferLetterIndustrialFinanceTableBuilder withLabourTotal(BigDecimal... labourTotal) { return withArray((total, industrialFinanceTable) -> setField("labourTotal", total, industrialFinanceTable), labourTotal); } public GrantOfferLetterIndustrialFinanceTableBuilder withMaterialsTotal(BigDecimal... materialsTotal) { return withArray((total, industrialFinanceTable) -> setField("materialsTotal", total, industrialFinanceTable), materialsTotal); } public GrantOfferLetterIndustrialFinanceTableBuilder withOverheadsTotal(BigDecimal... overheadsTotal) { return withArray((total, industrialFinanceTable) -> setField("overheadsTotal", total, industrialFinanceTable), overheadsTotal); } public GrantOfferLetterIndustrialFinanceTableBuilder withCapitalUsageTotal(BigDecimal... capitalUsageTotal) { return withArray((total, industrialFinanceTable) -> setField("capitalUsageTotal", total, industrialFinanceTable), capitalUsageTotal); } public GrantOfferLetterIndustrialFinanceTableBuilder withSubcontractTotal(BigDecimal... subcontractTotal) { return withArray((total, industrialFinanceTable) -> setField("subcontractTotal", total, industrialFinanceTable), subcontractTotal); } public GrantOfferLetterIndustrialFinanceTableBuilder withTravelTotal(BigDecimal... travelTotal) { return withArray((total, industrialFinanceTable) -> setField("travelTotal", total, industrialFinanceTable), travelTotal); } public GrantOfferLetterIndustrialFinanceTableBuilder withOtherCostsTotal(BigDecimal... otherCostsTotal) { return withArray((total, industrialFinanceTable) -> setField("otherCostsTotal", total, industrialFinanceTable), otherCostsTotal); } public GrantOfferLetterIndustrialFinanceTableBuilder withOrganisations(List<String>... organisations) { return withArray((orgs, industrialFinanceTable) -> setField("organisations", orgs, industrialFinanceTable), organisations); } }
923a2a728fbb2674c410355c22024a792b742c7b
428
java
Java
chapter_001/src/main/java/ru/job4j/array/Square.java
IgorAntov/job4j
6f9e96a4f64e422a6ca81be2f228d17e4a122bd1
[ "Apache-2.0" ]
null
null
null
chapter_001/src/main/java/ru/job4j/array/Square.java
IgorAntov/job4j
6f9e96a4f64e422a6ca81be2f228d17e4a122bd1
[ "Apache-2.0" ]
10
2020-03-04T23:12:00.000Z
2022-02-16T00:58:24.000Z
chapter_001/src/main/java/ru/job4j/array/Square.java
IgorAntov/job4j
6f9e96a4f64e422a6ca81be2f228d17e4a122bd1
[ "Apache-2.0" ]
null
null
null
17.833333
50
0.485981
999,094
package ru.job4j.array; /** * * @author Igor Antropov. * * @version $Id$. * * @since 0.1. */ public class Square { /** * Метод заполняет массив числами. * @return заполненный массив. */ public int[] calculate(int bound) { int[] rst = new int[bound]; for (int i = 0; i < rst.length; i++) { rst[i] = ((int) Math.pow((i + 1), 2)); } return rst; } }
923a2aaf4c75d9f9437509a19ed9d711e842d554
1,843
java
Java
src/main/java/com/newenv/communityFocus/domain/OperationLog.java
Silenburst/lazydemo
b0ae9e0ebc655491e7e2125f018b1671b1c12391
[ "MIT" ]
1
2017-06-16T07:30:06.000Z
2017-06-16T07:30:06.000Z
src/main/java/com/newenv/communityFocus/domain/OperationLog.java
Silenburst/lazydemo
b0ae9e0ebc655491e7e2125f018b1671b1c12391
[ "MIT" ]
null
null
null
src/main/java/com/newenv/communityFocus/domain/OperationLog.java
Silenburst/lazydemo
b0ae9e0ebc655491e7e2125f018b1671b1c12391
[ "MIT" ]
null
null
null
19.606383
61
0.709712
999,095
package com.newenv.communityFocus.domain; import java.util.Date; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Table; import com.newenv.communityFocus.security.SecurityUserHolder; @Table("lpjg_operation_log") public class OperationLog { @Id private long id;// private long fhid ;//房号id private int operatorid;// private int bmid;// private String ipaddress; private Date operateDate;// private String message ; private int mdid ; private int type ; public OperationLog(){ this.operatorid = SecurityUserHolder.getUserId(); this.bmid = SecurityUserHolder.getDeptId(); this.operateDate = new Date(); } public OperationLog(Integer userId,Integer deptId){ this.operatorid = userId; this.bmid = deptId; this.operateDate = new Date(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getFhid() { return fhid; } public void setFhid(long fhid) { this.fhid = fhid; } public int getOperatorid() { return operatorid; } public void setOperatorid(int operatorid) { this.operatorid = operatorid; } public int getBmid() { return bmid; } public void setBmid(int bmid) { this.bmid = bmid; } public String getIpaddress() { return ipaddress; } public void setIpaddress(String ipaddress) { this.ipaddress = ipaddress; } public java.util.Date getOperateDate() { return operateDate; } public void setOperateDate(java.util.Date operateDate) { this.operateDate = operateDate; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getMdid() { return mdid; } public void setMdid(int mdid) { this.mdid = mdid; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
923a2b5d51eedc6d0108ee37ba4a110e0034ff19
2,291
java
Java
app/src/main/java/com/spartahack/spartahack17/Activity/BaseActivity.java
SpartaHack/SpartaHack-Android-2016
cd985043b6b6dcf77828aa9cdb04f8bcaa1a384f
[ "MIT" ]
2
2015-09-17T17:32:52.000Z
2015-10-15T01:58:11.000Z
app/src/main/java/com/spartahack/spartahack17/Activity/BaseActivity.java
SpartaHack/SpartaHack-Android-2016
cd985043b6b6dcf77828aa9cdb04f8bcaa1a384f
[ "MIT" ]
65
2016-01-06T16:24:06.000Z
2016-02-24T07:29:09.000Z
app/src/main/java/com/spartahack/spartahack17/Activity/BaseActivity.java
SpartaHack/SpartaHack2016-Android
cd985043b6b6dcf77828aa9cdb04f8bcaa1a384f
[ "MIT" ]
1
2021-08-09T01:11:42.000Z
2021-08-09T01:11:42.000Z
29.371795
137
0.704059
999,096
package com.spartahack.spartahack17.Activity; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import butterknife.ButterKnife; import de.greenrobot.event.EventBus; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; /** * Created by ryan on 10/22/15 */ public abstract class BaseActivity extends AppCompatActivity { protected boolean registerEventBus = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // set transparent status bar if its kitkat or above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } @Override protected void onResume() { // register for event bus if (registerEventBus) EventBus.getDefault().register(this); super.onResume(); } @Override protected void onPause() { // unregister event bus if (registerEventBus) EventBus.getDefault().unregister(this); super.onPause(); } @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); ButterKnife.bind(this); } /** * Start an activity * @param activity class of the activity to start */ @SuppressWarnings("unused") protected void start(Class<? extends BaseActivity> activity) { startActivity(new Intent(this, activity)); } /** * Hide the soft keyboard * @param view to get window token */ @SuppressWarnings("unused") protected void hideKeyboard(View view){ // hide keyboard!!! fuck android InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } }
923a2bf8854b8a62c27372c887bbe644e7a91d85
154
java
Java
src/main/java/nl/ou/jabberpoint/domain/Direction.java
kaspercools/jabberpoint
3e2e23c607e7f5f0d70f551e87133695c85869da
[ "MIT" ]
null
null
null
src/main/java/nl/ou/jabberpoint/domain/Direction.java
kaspercools/jabberpoint
3e2e23c607e7f5f0d70f551e87133695c85869da
[ "MIT" ]
null
null
null
src/main/java/nl/ou/jabberpoint/domain/Direction.java
kaspercools/jabberpoint
3e2e23c607e7f5f0d70f551e87133695c85869da
[ "MIT" ]
null
null
null
13.166667
47
0.639241
999,097
package nl.ou.jabberpoint.domain; /** * @author Kasper Cools (dycjh@example.com) */ public enum Direction { Bottom, Left, Right, Top }
923a2d1efb5fd2e9afe2f315100fbd9df14b77b2
467
java
Java
css/css-core/src/boot/java/br/com/objectos/css/keyword/ThickKeyword.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
css/css-core/src/boot/java/br/com/objectos/css/keyword/ThickKeyword.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
css/css-core/src/boot/java/br/com/objectos/css/keyword/ThickKeyword.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
29.1875
102
0.783726
999,098
package br.com.objectos.css.keyword; import br.com.objectos.code.annotations.Generated; import br.com.objectos.css.type.LineWidthValue; import br.com.objectos.css.type.OutlineWidthValue; @Generated("br.com.objectos.css.boot.CssBoot") public final class ThickKeyword extends StandardKeyword implements LineWidthValue, OutlineWidthValue { static final ThickKeyword INSTANCE = new ThickKeyword(); private ThickKeyword() { super(252, "thick", "thick"); } }
923a2d7071c85a944d87fdd4e177855f97814ebf
4,745
java
Java
core/src/pl/lib2xy/gfx/g3d/simpleobject/ObjectPolyhedron.java
shadoq/lib.2xy.pl
ff7f1b380c34dabcce265c9834ddb320189994f5
[ "Apache-2.0" ]
null
null
null
core/src/pl/lib2xy/gfx/g3d/simpleobject/ObjectPolyhedron.java
shadoq/lib.2xy.pl
ff7f1b380c34dabcce265c9834ddb320189994f5
[ "Apache-2.0" ]
null
null
null
core/src/pl/lib2xy/gfx/g3d/simpleobject/ObjectPolyhedron.java
shadoq/lib.2xy.pl
ff7f1b380c34dabcce265c9834ddb320189994f5
[ "Apache-2.0" ]
null
null
null
26.21547
111
0.641307
999,099
/* * Copyright 2013-2015 See AUTHORS file. * * 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 pl.lib2xy.gfx.g3d.simpleobject; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; /** * @author Jarek */ public class ObjectPolyhedron extends ObjectMeshContainer{ private static Vector3 tmpVec3a = new Vector3(); private static Vector3 tmpVec3b = new Vector3(); private static Vector3 tmpVec3c = new Vector3(); private static Vector3 tmpVec3d = new Vector3(); private static Vector3 tmpNormalVec3a = new Vector3(); private static Vector3 tmpNormalVec3b = new Vector3(); private static Vector3 tmpNormalVec3c = new Vector3(); private static Vector3 tmpNormalVec3d = new Vector3(); /** * @param vertices * @param faces * @param radius * @param detail * @return */ protected static ObjectMesh polyhedron(Vector3[] vertices, int[][] faces, float radius, int detail){ init(); mesh.useIndicesIndex = false; int l = vertices.length; Vertex[] vertex = new Vertex[l]; for (int i = 0; i < l; i++){ vertex[i] = polyhedronPrepare(vertices[i]); vertex[i].position.scl(radius); } l = faces.length; for (int i = 0; i < l; i++){ polyhedronMake(vertex[faces[i][0]], vertex[faces[i][1]], vertex[faces[i][2]], detail); } return mesh; } /** * @param vector * @return */ protected static Vertex polyhedronPrepare(Vector3 vector){ Vertex vertex = new Vertex(); vertex.position = vector.nor().cpy(); float u = (float) (polyhedronAzimuth(vector) / 2 / Math.PI + 0.5); float v = (float) (polyhedronInclination(vector) / Math.PI + 0.5); vertex.uv = new Vector2(u, 1 - v); return vertex; } /** * Angle around the Y axis, counter-clockwise when looking from above. * * @param vector * @return */ protected static float polyhedronAzimuth(Vector3 vector){ return (float) Math.atan2(vector.z, -vector.x); } /** * Angle above the XZ plane. * * @param vector * @return */ protected static float polyhedronInclination(Vector3 vector){ return (float) Math.atan2(-vector.y, Math.sqrt((vector.x * vector.x) + (vector.z * vector.z))); } /** * @param v1 * @param v2 * @param v3 * @param detail */ protected static void polyhedronMake(Vertex v1, Vertex v2, Vertex v3, int detail){ if (detail < 1){ com.badlogic.gdx.math.Plane p1 = new com.badlogic.gdx.math.Plane(v1.position, v2.position, v3.position); v1.normal = p1.getNormal(); v2.normal = p1.getNormal(); v3.normal = p1.getNormal(); Vector3 azimut = new Vector3(v1.position); azimut.add(v2.position).add(v3.position).scl(1f / 3f); float azi = polyhedronAzimuth(azimut); v1.uv = polyhedronCorrectUV(v1.uv, v1.position, azi); v2.uv = polyhedronCorrectUV(v2.uv, v2.position, azi); v3.uv = polyhedronCorrectUV(v3.uv, v3.position, azi); mesh.addTrilange(v2, v3, v1); } else { detail--; // // top quadrant // polyhedronMake(v1, polyhedronMidpoint(v1, v2), polyhedronMidpoint(v1, v3), detail); // // left quadrant // polyhedronMake(polyhedronMidpoint(v1, v2), v2, polyhedronMidpoint(v2, v3), detail); // // right quadrant // polyhedronMake(polyhedronMidpoint(v1, v3), polyhedronMidpoint(v2, v3), v3, detail); // // center quadrant // polyhedronMake(polyhedronMidpoint(v1, v3), polyhedronMidpoint(v2, v3), polyhedronMidpoint(v1, v3), detail); } } /** * @param uv * @param vector * @param azimuth * @return */ protected static Vector2 polyhedronCorrectUV(Vector2 uv, Vector3 vector, float azimuth){ if ((azimuth < 0) && (uv.x == 1)){ uv = new Vector2(uv.x - 1, uv.y); } if ((vector.x == 0) && (vector.z == 0)){ uv = new Vector2((float) (azimuth / 2 / Math.PI + 0.5), uv.y); } return uv; } /** * @param v1 * @param v2 * @return */ protected static Vertex polyhedronMidpoint(Vertex v1, Vertex v2){ Vector3 m1 = v1.position; m1.add(v2.position).scl(1f / 2f); Vertex mid = polyhedronPrepare(m1); mid.position = m1; return mid; } }
923a2dd8c413aecdac2d4133e7f423595abba545
2,374
java
Java
src/main/java/io/github/metrics_matcher/core/Jdbc.java
metrics-matcher/metrics-matcher
7ddb2495ba3906aff0e2de81f703376f3928fac1
[ "MIT" ]
null
null
null
src/main/java/io/github/metrics_matcher/core/Jdbc.java
metrics-matcher/metrics-matcher
7ddb2495ba3906aff0e2de81f703376f3928fac1
[ "MIT" ]
1
2022-01-21T23:23:51.000Z
2022-01-21T23:23:51.000Z
src/main/java/io/github/metrics_matcher/core/Jdbc.java
metrics-matcher/metrics-matcher
7ddb2495ba3906aff0e2de81f703376f3928fac1
[ "MIT" ]
null
null
null
32.520548
98
0.57877
999,100
package io.github.metrics_matcher.core; import io.github.metrics_matcher.dto.DataSource; import lombok.extern.java.Log; import java.sql.*; import java.util.LinkedHashMap; import static java.lang.String.format; @Log public class Jdbc implements AutoCloseable { private Connection connection; public void connect(DataSource ds) throws SQLException { if (isOpenConnection()) { log.info("Closing existing JDBC connection"); connection.close(); } log.info(format("Opening JDBC connection [%s]", ds.getUrl())); DriverManager.setLoginTimeout(ds.getTimeout()); connection = DriverManager.getConnection(ds.getUrl(), ds.getUsername(), ds.getPassword()); connection.setReadOnly(true); if (ds.getSchema() != null) { connection.setSchema(ds.getSchema()); } } public JdbcResult execute(String sql) throws SQLException { try ( PreparedStatement statement = connection.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); ) { log.info(format("Executing [%s]", sql)); if (resultSet.next()) { ResultSetMetaData metaData = resultSet.getMetaData(); int columnsCount = metaData.getColumnCount(); LinkedHashMap<String, Object> data = new LinkedHashMap<>(); for (int i = 1; i <= columnsCount; i++) { data.put(metaData.getColumnLabel(i), resultSet.getObject(i)); } log.info(format("Received [%s]", data)); if (resultSet.next()) { log.warning("More than one row returned"); return new JdbcResult(JdbcResult.Error.MULTIPLE_ROWS); } else { return new JdbcResult(data); } } else { log.warning("Empty result"); return new JdbcResult(JdbcResult.Error.EMPTY_RESULT); } } } private boolean isOpenConnection() throws SQLException { return connection != null && !connection.isClosed(); } @Override public void close() throws SQLException { if (isOpenConnection()) { log.info("Closing JDBC connection"); connection.close(); } } }
923a2de137ff45b66c5af2391d0e6b92feb63318
6,064
java
Java
mylibrary/src/main/java/com/bcgtgjyb/huanwen/customview/mylibrary/WindowsLoad.java
songhaonangit/C3705_qx
ea0b560c5688ae46c6d9863b2ad7938a92679d65
[ "Apache-2.0" ]
217
2015-10-13T15:00:33.000Z
2022-01-06T03:20:31.000Z
mylibrary/src/main/java/com/bcgtgjyb/huanwen/customview/mylibrary/WindowsLoad.java
songhaonangit/C3705_qx
ea0b560c5688ae46c6d9863b2ad7938a92679d65
[ "Apache-2.0" ]
1
2015-09-10T10:37:50.000Z
2015-09-10T10:37:50.000Z
mylibrary/src/main/java/com/bcgtgjyb/huanwen/customview/mylibrary/WindowsLoad.java
songhaonangit/C3705_qx
ea0b560c5688ae46c6d9863b2ad7938a92679d65
[ "Apache-2.0" ]
85
2015-10-07T03:36:53.000Z
2022-03-29T23:26:07.000Z
35.255814
108
0.55343
999,101
package com.bcgtgjyb.huanwen.customview.mylibrary; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import android.view.animation.Interpolator; /** * Created by guohuanwen on 2015/10/5. */ public class WindowsLoad extends View { private float pi = (float) Math.PI; private String TAG = "WindowsLoad"; private Paint paint; private int R; private float circleR; private ValueAnimator circleAnimator1; private ValueAnimator circleAnimator2; private ValueAnimator circleAnimator3; private boolean init = true; float x1, x2, x3, y1, y2, y3; public WindowsLoad(Context context, AttributeSet attrs) { super(context, attrs); paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.parseColor("#ffff4444")); R = 10; } float[] circleCentre; float[] start1; float[] start2; float[] start3; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //初始化 if (init) { circleCentre = new float[]{getWidth() / 2, getHeight() / 2}; start1 = new float[]{getWidth() / 2, R}; start2 = onCiecleCoordinate(-0.5f, start1, circleCentre); start3 = onCiecleCoordinate(-0.5f, start2, circleCentre); init = false; loading(); } // canvas.drawCircle(start1[0], start1[1], R, paint); // Log.d(TAG, "onDraw() returned: "+ start1[0]+" "+start1[1] +" "+ start2[0]+" "+start2[1]); //第一个点初始位置 if (!circleAnimator1.isRunning()) { canvas.drawCircle(start1[0], start1[1], R, paint); } //第二个点初始位置 if (!circleAnimator2.isRunning()) { canvas.drawCircle(start2[0], start2[1], R, paint); } //第三个点初始位置 if (!circleAnimator3.isRunning()) { canvas.drawCircle(start3[0], start3[1], R, paint); } if (circleAnimator1.isRunning()) { x1 = (float) (circleCentre[0] + circleR * Math.cos((float) circleAnimator1.getAnimatedValue())); y1 = (float) (circleCentre[1] + circleR * Math.sin((float) circleAnimator1.getAnimatedValue())); canvas.drawCircle(x1, y1, R, paint); } if (circleAnimator2.isRunning()) { x2 = (float) (circleCentre[0] + circleR * Math.cos((float) circleAnimator2.getAnimatedValue())); y2 = (float) (circleCentre[1] + circleR * Math.sin((float) circleAnimator2.getAnimatedValue())); canvas.drawCircle(x2, y2, R, paint); } if (circleAnimator3.isRunning()) { x3 = (float) (circleCentre[0] + circleR * Math.cos((float) circleAnimator3.getAnimatedValue())); y3 = (float) (circleCentre[1] + circleR * Math.sin((float) circleAnimator3.getAnimatedValue())); canvas.drawCircle(x3, y3, R, paint); } if (circleAnimator1.isRunning() || circleAnimator2.isRunning() || circleAnimator3.isRunning()) { invalidate(); } } private void loading() { circleAnimator1 = getCircleData(start1, circleCentre, 0); circleAnimator1.start(); circleAnimator2 = getCircleData(start2, circleCentre, 300); circleAnimator2.start(); circleAnimator3 = getCircleData(start3, circleCentre, 600); circleAnimator3.start(); postDelayed(new Runnable() { @Override public void run() { loading(); invalidate(); } }, circleAnimator3.getDuration() + 600); } private SlowToQuick slowToQuick = new SlowToQuick(); private ValueAnimator getCircleData(float[] startCoordinate, float[] RCoordinate, int delay) { float x1 = startCoordinate[0]; float y1 = startCoordinate[1]; float x0 = RCoordinate[0]; float y0 = RCoordinate[1]; // Log.i(TAG, "getCircleData x y: " + x1+" ,"+y1+" x0 "+x0+ " y0 "+y0); circleR = (float) Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)); float param = (float) (Math.abs(y1 - y0) / circleR); if (param < -1.0) { param = -1.0f; } else if (param > 1.0) { param = 1.0f; } float a = (float) Math.asin(param); if (x1 >= x0 && y1 >= y0) { a = a; } else if (x1 < x0 && y1 >= y0) { a = pi - a; } else if (x1 < x0 && y1 < y0) { a = a + pi; } else { a = 2 * pi - a; } ValueAnimator circleAnimator = ValueAnimator.ofFloat(a, a + 2 * pi); circleAnimator.setDuration(1500); circleAnimator.setInterpolator(slowToQuick); circleAnimator.setStartDelay(delay); return circleAnimator; } //获取同一个圆上,间隔固定角度的点坐标 private float[] onCiecleCoordinate(float angle, float[] start, float[] center) { float x1 = start[0]; float y1 = start[1]; float x0 = center[0]; float y0 = center[1]; float R = (float) Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)); float param = (float) (Math.abs(y1 - y0) / R); if (param < -1.0) { param = -1.0f; } else if (param > 1.0) { param = 1.0f; } float a = (float) Math.asin(param); if (x1 >= x0 && y1 >= y0) { a = a; } else if (x1 < x0 && y1 >= y0) { a = pi - a; } else if (x1 < x0 && y1 < y0) { a = a + pi; } else { a = 2 * pi - a; } float x = (float) (center[0] + R * Math.cos(a + angle)); float y = (float) (center[1] + R * Math.sin(a + angle)); return new float[]{x, y}; } class SlowToQuick implements Interpolator { @Override public float getInterpolation(float input) { return input * input; } } }
923a2e374d1eb0af15236f5b5110ea6236f741bc
1,157
java
Java
src/main/java/de/imi/EBMJAVAUI/controller/OverviewController.java
stefanhgm/EBM-Java-UI
858359112de01196818bf9b02a7c9bb966d6e0a6
[ "MIT" ]
4
2021-10-11T13:30:37.000Z
2021-12-20T14:45:32.000Z
src/main/java/de/imi/EBMJAVAUI/controller/OverviewController.java
stefanhgm/EBM-Java-UI
858359112de01196818bf9b02a7c9bb966d6e0a6
[ "MIT" ]
null
null
null
src/main/java/de/imi/EBMJAVAUI/controller/OverviewController.java
stefanhgm/EBM-Java-UI
858359112de01196818bf9b02a7c9bb966d6e0a6
[ "MIT" ]
null
null
null
31.27027
91
0.784788
999,102
package de.imi.EBMJAVAUI.controller; import de.imi.EBMJAVAUI.dao.EBMJAVAUI.PredictionModelDao; import de.imi.EBMJAVAUI.model.EBMJAVAUI.PredictionModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; import java.util.Locale; /** * Overview of the all models (validated and non-validated). */ @Controller @RequestMapping("/overview") public class OverviewController { private static final Logger LOGGER = LoggerFactory.getLogger(OverviewController.class); private final PredictionModelDao predictionModelDao; public OverviewController(PredictionModelDao predictionModelDao) { this.predictionModelDao = predictionModelDao; } @GetMapping public String overview(Model model, Locale locale) { List<PredictionModel> predictionModels = predictionModelDao.getAllElements(); model.addAttribute("predictionModels", predictionModels); return "overview"; } }
923a2e3aa631a35a10bad3466f301277a610d228
296
java
Java
src/main/java/org/sidoh/reactor_simulator/simulator/TileEntityReactorControlRodSimulator.java
AlanGreene/reactor_simulator
25144cc19f1bf6b68b22f8ea3f329669d77a4539
[ "MIT" ]
null
null
null
src/main/java/org/sidoh/reactor_simulator/simulator/TileEntityReactorControlRodSimulator.java
AlanGreene/reactor_simulator
25144cc19f1bf6b68b22f8ea3f329669d77a4539
[ "MIT" ]
1
2019-04-23T17:49:36.000Z
2019-04-23T17:49:36.000Z
src/main/java/org/sidoh/reactor_simulator/simulator/TileEntityReactorControlRodSimulator.java
AlanGreene/reactor_simulator
25144cc19f1bf6b68b22f8ea3f329669d77a4539
[ "MIT" ]
null
null
null
26.909091
90
0.834459
999,103
package org.sidoh.reactor_simulator.simulator; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorControlRod; public class TileEntityReactorControlRodSimulator extends TileEntityReactorControlRod { @Override public boolean isConnected() { return true; } }
923a2e3d4cae953344b1c53394c8a12b56b4a33a
2,025
java
Java
A0-algorithms/x-leetcode-com/src/main/java/xyz/flysium/photon/algorithm/queueandstack/search/basic/T0200_NumberOfIslands.java
SvenAugustus/photon
1adf8fb7cfcc450fb04af5daaccc8513d46a16e8
[ "MIT" ]
2
2020-05-22T16:30:52.000Z
2021-05-10T13:40:04.000Z
A0-algorithms/x-leetcode-com/src/main/java/xyz/flysium/photon/algorithm/queueandstack/search/basic/T0200_NumberOfIslands.java
SvenAugustus/photon
1adf8fb7cfcc450fb04af5daaccc8513d46a16e8
[ "MIT" ]
4
2020-07-22T05:45:43.000Z
2022-02-02T13:04:12.000Z
A0-algorithms/x-leetcode-com/src/main/java/xyz/flysium/photon/algorithm/queueandstack/search/basic/T0200_NumberOfIslands.java
SvenAugustus/photon
1adf8fb7cfcc450fb04af5daaccc8513d46a16e8
[ "MIT" ]
3
2020-11-25T05:01:05.000Z
2021-11-21T13:05:59.000Z
24.695122
83
0.496296
999,104
package xyz.flysium.photon.algorithm.queueandstack.search.basic; import java.util.LinkedList; import java.util.Queue; /** * 200. 岛屿数量 * <p> * https://leetcode-cn.com/problems/number-of-islands/ * * @author zeno */ public interface T0200_NumberOfIslands { // 给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。 // //岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。 // //此外,你可以假设该网格的四条边均被水包围。 // 广度优先搜索 BFS: 为了求出岛屿的数量,我们可以扫描整个二维网格。 // 如果一个位置为 1,则将其加入队列,开始进行广度优先搜索。 // 在广度优先搜索的过程中,每个搜索到的 1 都会被重新标记为 0。直到队列为空,搜索结束。 // BFS class Solution { private static final char LAND = '1'; private static final char WATER = '0'; private static final int[] DPX = new int[]{0, -1, 1, 0}; private static final int[] DPY = new int[]{-1, 0, 0, 1}; public int numIslands(char[][] grid) { if (grid.length == 0) { return 0; } final int rows = grid.length; final int cols = grid[0].length; int numOfIslands = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j] == LAND) { numOfIslands++; bfs(grid, i, j, rows, cols); } } } return numOfIslands; } private void bfs(char[][] grid, int i, int j, final int rows, final int cols) { Queue<int[]> queue = new LinkedList<>(); queue.offer(new int[]{i, j}); while (!queue.isEmpty()) { int sz = queue.size(); for (int g = 0; g < sz; g++) { int[] e = queue.poll(); int x0 = e[0]; int y0 = e[1]; grid[x0][y0] = WATER; for (int k = 0; k < 4; k++) { int x = x0 + DPX[k]; int y = y0 + DPY[k]; if (x < 0 || x >= rows || y < 0 || y >= cols) { continue; } if (grid[x][y] == WATER) { continue; } grid[x][y] = WATER; queue.offer(new int[]{x, y}); } } } } } }
923a2e4e546231f26217e6597a063e7654e91554
1,485
java
Java
hoop-server/src/test/java/com/cloudera/lib/wsrs/TestJSONMapProvider.java
liangly/hoop
e97a7ab18f5a85cf3c0d7d57c3a5af760d498933
[ "Apache-2.0" ]
2
2019-09-02T10:17:14.000Z
2019-10-21T11:17:43.000Z
hoop-server/src/test/java/com/cloudera/lib/wsrs/TestJSONMapProvider.java
liangly/hoop
e97a7ab18f5a85cf3c0d7d57c3a5af760d498933
[ "Apache-2.0" ]
null
null
null
hoop-server/src/test/java/com/cloudera/lib/wsrs/TestJSONMapProvider.java
liangly/hoop
e97a7ab18f5a85cf3c0d7d57c3a5af760d498933
[ "Apache-2.0" ]
null
null
null
34.534884
80
0.719192
999,105
/* * Copyright (c) 2011, Cloudera, Inc. All Rights Reserved. * * Cloudera, Inc. 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 * * This software 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.cloudera.lib.wsrs; import com.cloudera.circus.test.XTest; import org.json.simple.JSONObject; import org.testng.Assert; import org.testng.annotations.Test; import java.io.ByteArrayOutputStream; import java.util.Map; public class TestJSONMapProvider extends XTest { @Test @SuppressWarnings("unchecked") public void test() throws Exception { JSONMapProvider p = new JSONMapProvider(); Assert.assertTrue(p.isWriteable(Map.class, null, null, null)); Assert.assertFalse(p.isWriteable(XTest.class, null, null, null)); Assert.assertEquals(p.getSize(null, null, null, null, null), -1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JSONObject json = new JSONObject(); json.put("a", "A"); p.writeTo(json, JSONObject.class, null, null, null, null, baos); baos.close(); Assert.assertEquals(new String(baos.toByteArray()).trim(), "{\"a\":\"A\"}"); } }
923a2e78c6c2a5e61441fc0dd896483a5eb375b6
10,295
java
Java
dbflute-runtime/src/main/java/org/dbflute/system/DBFluteSystem.java
dbflute/dbflute-core
06eea8fdb4a2fe489b717d035bfb8f92c7e1c8c1
[ "Apache-1.1" ]
23
2016-01-22T06:56:17.000Z
2022-03-13T23:20:27.000Z
dbflute-runtime/src/main/java/org/dbflute/system/DBFluteSystem.java
dbflute/dbflute-core
06eea8fdb4a2fe489b717d035bfb8f92c7e1c8c1
[ "Apache-1.1" ]
18
2015-03-04T07:48:13.000Z
2020-12-30T10:12:16.000Z
dbflute-runtime/src/main/java/org/dbflute/system/DBFluteSystem.java
dbflute/dbflute-core
06eea8fdb4a2fe489b717d035bfb8f92c7e1c8c1
[ "Apache-1.1" ]
20
2015-03-04T01:04:44.000Z
2020-02-09T06:42:45.000Z
39.903101
105
0.490724
999,106
/* * Copyright 2014-2021 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.dbflute.system; import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.dbflute.system.provider.DfCurrentDateProvider; import org.dbflute.system.provider.DfFinalLocaleProvider; import org.dbflute.system.provider.DfFinalTimeZoneProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author jflute */ public class DBFluteSystem { // =================================================================================== // Definition // ========== /** The logger instance for this class. (NotNull) */ private static final Logger _log = LoggerFactory.getLogger(DBFluteSystem.class); // =================================================================================== // Option Attribute // ================ /** * The provider of current date for DBFlute system. <br> * e.g. AccessContext might use this (actually, very very rare case) <br> * (NullAllowed: if null, server date might be used) */ protected static DfCurrentDateProvider _currentDateProvider; /** * The provider of final default locale for DBFlute system. <br> * e.g. DisplaySql, Date conversion, LocalDate mapping and so on... <br> * (NullAllowed: if null, server locale might be used) */ protected static DfFinalLocaleProvider _finalLocaleProvider; /** * The provider of final default time-zone for DBFlute system. <br> * e.g. DisplaySql, Date conversion, LocalDate mapping and so on... <br> * (NullAllowed: if null, server zone might be used) */ protected static DfFinalTimeZoneProvider _finalTimeZoneProvider; /** Is this system adjustment locked? */ protected static boolean _locked = true; // =================================================================================== // Current Time // ============ // #date_parade /** * Get current local date. (server date if no provider) * @return The new-created local date instance as current date. (NotNull) */ public static LocalDate currentLocalDate() { return currentZonedDateTime().toLocalDate(); } /** * Get current local date-time. (server date if no provider) * @return The new-created local date instance as current date. (NotNull) */ public static LocalDateTime currentLocalDateTime() { return currentZonedDateTime().toLocalDateTime(); } /** * Get current zoned date-time. (server date if no provider) * @return The new-created zoned date instance as current date. (NotNull) */ public static ZonedDateTime currentZonedDateTime() { final TimeZone timeZone = getFinalTimeZone(); return ZonedDateTime.ofInstant(currentDate().toInstant(), timeZone.toZoneId()); } /** * Get current date. (server date if no provider) * @return The new-created date instance as current date. (NotNull) */ public static Date currentDate() { return new Date(currentTimeMillis()); } /** * Get current time-stamp. (server date if no provider) * @return The new-created time-stamp instance as current date. (NotNull) */ public static Timestamp currentTimestamp() { return new Timestamp(currentTimeMillis()); } /** * Get current date as milliseconds. (server date if no provider) * @return The long value as milliseconds. */ public static long currentTimeMillis() { final long millis; if (_currentDateProvider != null) { millis = _currentDateProvider.currentTimeMillis(); } else { millis = System.currentTimeMillis(); } return millis; } // =================================================================================== // Final Locale // ============ /** * Get the final default locale for DBFlute system. <br> * basically for e.g. DisplaySql, Date conversion, LocalDate mapping and so on... * @return The final default locale for DBFlute system. (NotNull: if no provider, server locale) */ public static Locale getFinalLocale() { return _finalLocaleProvider != null ? _finalLocaleProvider.provide() : Locale.getDefault(); } // =================================================================================== // Final TimeZone // ============== /** * Get the final default time-zone for DBFlute system. <br> * basically for e.g. DisplaySql, Date conversion, LocalDate mapping and so on... * @return The final default time-zone for DBFlute system. (NotNull: if no provider, server zone) */ public static TimeZone getFinalTimeZone() { return _finalTimeZoneProvider != null ? _finalTimeZoneProvider.provide() : TimeZone.getDefault(); } // =================================================================================== // Line Separator // ============== /** * Get basic line separator for DBFlute process. * @return The string of line separator. (NotNull) */ public static String ln() { return "\n"; // LF is basic here // /- - - - - - - - - - - - - - - - - - - - - - - - - - - // The 'CR + LF' causes many trouble all over the world. // e.g. Oracle stored procedure // - - - - - - - - - -/ } // unused on DBFlute //public static String getSystemLn() { // return System.getProperty("line.separator"); //} // =================================================================================== // System Adjustment // ================= // ----------------------------------------------------- // Current Date // ------------ public static boolean hasCurrentDateProvider() { return _currentDateProvider != null; } public static void setCurrentDateProvider(DfCurrentDateProvider currentDateProvider) { assertUnlocked(); if (_log.isInfoEnabled()) { _log.info("...Setting currentDateProvider: " + currentDateProvider); } _currentDateProvider = currentDateProvider; lock(); // auto-lock here, because of deep world } // ----------------------------------------------------- // Final Locale // ------------ public static boolean hasFinalLocaleProvider() { return _finalTimeZoneProvider != null; } public static void setFinalLocaleProvider(DfFinalLocaleProvider finalLocaleProvider) { assertUnlocked(); if (_log.isInfoEnabled()) { _log.info("...Setting finalLocaleProvider: " + finalLocaleProvider); } _finalLocaleProvider = finalLocaleProvider; lock(); // auto-lock here, because of deep world } // ----------------------------------------------------- // Final TimeZone // -------------- public static boolean hasFinalTimeZoneProvider() { return _finalTimeZoneProvider != null; } public static void setFinalTimeZoneProvider(DfFinalTimeZoneProvider finalTimeZoneProvider) { assertUnlocked(); if (_log.isInfoEnabled()) { _log.info("...Setting finalTimeZoneProvider: " + finalTimeZoneProvider); } _finalTimeZoneProvider = finalTimeZoneProvider; lock(); // auto-lock here, because of deep world } // =================================================================================== // System Lock // =========== public static void lock() { if (_locked) { return; } if (_log.isInfoEnabled()) { _log.info("...Locking the DBFlute system"); } _locked = true; } public static void unlock() { if (!_locked) { return; } if (_log.isInfoEnabled()) { _log.info("...Unlocking the DBFlute system"); } _locked = false; } public static boolean isLocked() { return _locked; } protected static void assertUnlocked() { if (!isLocked()) { return; } throw new IllegalStateException("The DBFlute system is locked."); } }
923a3055f1ba2d7331d90a1c52fd2041308704c7
201
java
Java
leetcode/src/main/java/com/georgeisaev/faang/leetcode/alg/array/medium/combination/CombinationSum2.java
Georgich88/faang-data-sturctures-algorithms
eb008a7e28432b18b923cfe83911ac4d62ee5c2d
[ "Apache-2.0" ]
2
2022-03-15T16:23:00.000Z
2022-03-15T21:16:18.000Z
leetcode/src/main/java/com/georgeisaev/faang/leetcode/alg/array/medium/combination/CombinationSum2.java
Georgich88/faang-data-sturctures-algorithms
eb008a7e28432b18b923cfe83911ac4d62ee5c2d
[ "Apache-2.0" ]
4
2021-04-03T01:52:44.000Z
2022-03-28T01:45:58.000Z
leetcode/src/main/java/com/georgeisaev/faang/leetcode/alg/array/medium/combination/CombinationSum2.java
Georgich88/faang-data-sturctures-algorithms
eb008a7e28432b18b923cfe83911ac4d62ee5c2d
[ "Apache-2.0" ]
null
null
null
20.1
68
0.791045
999,108
package com.georgeisaev.faang.leetcode.alg.array.medium.combination; import java.util.List; public interface CombinationSum2 { List<List<Integer>> combinationSum2(int[] candidates, int target); }
923a30efc0301242a4d839b815aed766ebfe5bcb
4,621
java
Java
sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Devices.java
yaming116/sonic-server
30db079e03069b1f5a07d52c7f1b58a471901bc7
[ "MIT" ]
1,356
2021-12-11T15:05:46.000Z
2022-03-31T08:16:31.000Z
sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Devices.java
yaming116/sonic-server
30db079e03069b1f5a07d52c7f1b58a471901bc7
[ "MIT" ]
26
2021-12-14T06:31:22.000Z
2022-03-31T06:25:25.000Z
sonic-server-controller/src/main/java/org/cloud/sonic/controller/models/domain/Devices.java
yaming116/sonic-server
30db079e03069b1f5a07d52c7f1b58a471901bc7
[ "MIT" ]
198
2021-12-12T07:21:31.000Z
2022-03-31T10:54:20.000Z
29.246835
82
0.658299
999,109
/* * Copyright (C) [SonicCloudOrg] Sonic Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.cloud.sonic.controller.models.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.gitee.sunchenbin.mybatis.actable.annotation.*; import com.gitee.sunchenbin.mybatis.actable.constants.MySqlCharsetConstant; import com.gitee.sunchenbin.mybatis.actable.constants.MySqlEngineConstant; import org.cloud.sonic.controller.models.base.TypeConverter; import org.cloud.sonic.controller.models.dto.DevicesDTO; import io.swagger.annotations.ApiModel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; /** * @author JayWenStar * @since 2021-12-17 */ @ApiModel(value = "Devices对象", description = "") @Data @Accessors(chain = true) @Builder @NoArgsConstructor @AllArgsConstructor @TableName("devices") @TableComment("设备表") @TableCharset(MySqlCharsetConstant.DEFAULT) @TableEngine(MySqlEngineConstant.InnoDB) public class Devices implements Serializable, TypeConverter<Devices, DevicesDTO> { @TableId(value = "id", type = IdType.AUTO) @IsAutoIncrement private Integer id; @TableField @Column(value = "agent_id", isNull = false, comment = "所属agent的id") private Integer agentId; @TableField @Column(comment = "cpu架构", defaultValue = "") private String cpu; @TableField @Column(value = "img_url", comment = "手机封面", defaultValue = "") private String imgUrl; @TableField @Column(comment = "制造商", defaultValue = "") private String manufacturer; @TableField @Column(comment = "手机型号", defaultValue = "") private String model; @TableField @Column(comment = "设备名称", defaultValue = "") private String name; @TableField @Column(comment = "设备安装app的密码", defaultValue = "") private String password; @TableField @Column(isNull = false, comment = "系统类型 1:android 2:ios") private Integer platform; @TableField @Column(comment = "设备分辨率", defaultValue = "") private String size; @TableField @Column(comment = "设备状态", defaultValue = "") private String status; @TableField @Column(value = "ud_id", comment = "设备序列号", defaultValue = "") @Index(value = "IDX_UD_ID", columns = {"ud_id"}) private String udId; @TableField @Column(comment = "设备系统版本", defaultValue = "") private String version; @TableField @Column(value = "nick_name", comment = "设备备注", defaultValue = "") private String nickName; @TableField @Column(comment = "设备当前占用者", defaultValue = "") private String user; @TableField @Column(value = "chi_name", comment = "中文设备", defaultValue = "") String chiName; @TableField @Column(defaultValue = "0", comment = "设备温度") Integer temperature; @TableField @Column(defaultValue = "0", comment = "设备电量") Integer level; @TableField @Column(defaultValue = "0", comment = "Hub接口") Integer position; @TableField @Column(defaultValue = "0", comment = "Hub档位") Integer gear; public static Devices newDeletedDevice(int id) { String tips = "Device does not exist."; return new Devices() .setAgentId(0) .setStatus("DISCONNECTED") .setPlatform(0) .setId(id) .setVersion("unknown") .setSize("unknown") .setCpu("unknown") .setManufacturer("unknown") .setName(tips) .setModel(tips) .setChiName(tips) .setNickName(tips) .setName(tips) .setUser(tips) .setUdId(tips) .setTemperature(0) .setGear(0) .setPosition(0) .setLevel(0); } }
923a313cca58aabb14bb1b64347cbcb243c26dbe
1,333
java
Java
core/src/yio/tro/antiyoy/gameplay/game_view/RenderExclamationMarks.java
Don-Williams/Antiyoy-Class-Project
daf4c43b59a6f8a5cb8f3e74b6b80bf8891cbd74
[ "MIT" ]
null
null
null
core/src/yio/tro/antiyoy/gameplay/game_view/RenderExclamationMarks.java
Don-Williams/Antiyoy-Class-Project
daf4c43b59a6f8a5cb8f3e74b6b80bf8891cbd74
[ "MIT" ]
null
null
null
core/src/yio/tro/antiyoy/gameplay/game_view/RenderExclamationMarks.java
Don-Williams/Antiyoy-Class-Project
daf4c43b59a6f8a5cb8f3e74b6b80bf8891cbd74
[ "MIT" ]
null
null
null
26.66
97
0.631658
999,110
package yio.tro.antiyoy.gameplay.game_view; import yio.tro.antiyoy.gameplay.Hex; import yio.tro.antiyoy.gameplay.Province; import yio.tro.antiyoy.gameplay.rules.GameRules; import yio.tro.antiyoy.stuff.PointYio; public class RenderExclamationMarks extends GameRender{ public RenderExclamationMarks(GameRendersList gameRendersList) { super(gameRendersList); } @Override public void loadTextures() { } @Override public void render() { if (!gameController.isPlayerTurn()) return; for (Province province : gameController.fieldManager.provinces) { if (!gameController.isCurrentTurn(province.getFraction())) continue; if (province.money < GameRules.PRICE_UNIT) continue; Hex capitalHex = province.getCapital(); PointYio pos = capitalHex.getPos(); if (!isPosInViewFrame(pos, hexViewSize)) continue; batchMovable.draw( gameView.texturesManager.exclamationMarkTexture, pos.x - 0.5f * hexViewSize, pos.y + 0.3f * hexViewSize + gameController.jumperUnit.jumpPos * hexViewSize, 0.35f * hexViewSize, 0.6f * hexViewSize ); } } @Override public void disposeTextures() { } }
923a3217ce27c5f1a734aec775a0d6ccd856ff12
3,513
java
Java
CBP/android/desktop/fermat-cbp-android-desktop-sub-app-manager-bitdubai/src/main/java/com/bitdubai/desktop/sub_app_manager/provisory_classes/CbpInstalledSubApp.java
jorgeejgonzalez/fermat
d5f0f7c98510f19f485ac908501df46f24444190
[ "MIT" ]
3
2016-03-23T05:26:51.000Z
2016-03-24T14:33:05.000Z
CBP/android/desktop/fermat-cbp-android-desktop-sub-app-manager-bitdubai/src/main/java/com/bitdubai/desktop/sub_app_manager/provisory_classes/CbpInstalledSubApp.java
yalayn/fermat
f0a912adb66a439023ec4e70b821ba397e0f7760
[ "MIT" ]
17
2015-11-20T20:43:17.000Z
2016-07-25T20:35:49.000Z
CBP/android/desktop/fermat-cbp-android-desktop-sub-app-manager-bitdubai/src/main/java/com/bitdubai/desktop/sub_app_manager/provisory_classes/CbpInstalledSubApp.java
yalayn/fermat
f0a912adb66a439023ec4e70b821ba397e0f7760
[ "MIT" ]
26
2015-11-20T13:20:23.000Z
2022-03-11T07:50:06.000Z
27.661417
220
0.674637
999,111
package com.bitdubai.desktop.sub_app_manager.provisory_classes; import com.bitdubai.fermat_api.layer.all_definition.util.Version; import com.bitdubai.fermat_api.layer.dmp_engine.sub_app_runtime.enums.SubApps; import com.bitdubai.fermat_api.layer.dmp_module.sub_app_manager.InstalledSubApp; import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_manager.InstalledLanguage; import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_manager.InstalledSkin; import java.util.List; /** * Created by Matias Furszyfer on 2015.08.19.. */ public class CbpInstalledSubApp implements InstalledSubApp { private SubApps subApps; private List<InstalledSkin> skinsId; private List<InstalledLanguage> languajesId; private String walletIcon; private String walletName; private String publicKey; private String walletPlatformIdentifier; private Version version; public CbpInstalledSubApp(SubApps subApps, List<InstalledSkin> skinsId, List<InstalledLanguage> languajesId, String walletIcon, String walletName, String publicKey, String walletPlatformIdentifier, Version version) { this.subApps = subApps; this.skinsId = skinsId; this.languajesId = languajesId; this.walletIcon = walletIcon; this.walletName = walletName; this.publicKey = publicKey; this.walletPlatformIdentifier = walletPlatformIdentifier; this.version = version; } /** * InstalledWallet Interface implementation. */ /** * This method gives us the list of all the languages installed for this wallet * */ public List<InstalledLanguage> getLanguagesId(){ return languajesId; } /** * This method gives us the list of all the skins installed for this wallet * */ public List<InstalledSkin> getSkinsId(){ return skinsId; } /** * This method tell us the type of the subApp * * @return the subApp type */ @Override public SubApps getSubAppType() { return subApps; } /** * This method gives us a codification of the wallet identifier (the identifier is an enum that * registers the subApp) * * @return an string that is result of the method getCode of an enum that can be inferred by the * subApp */ @Override public String getSubAppPlatformIdentifier() { return "Method: getSubAppPlatformIdentifier - NO TIENE valor ASIGNADO para RETURN"; } /** * This method gives us the name of the wallet icon used to identify the image in the subApp resources plug-in * * @return the name of the said icon */ @Override public String getSubAppIcon() { return walletIcon; } /** * This method gives us the public key of the wallet in this device. It is used as identifier of * the wallet * * @return the public key represented as a string */ /** * This method gives us the subApp name * * @return the name of the subApp */ @Override public String getSubAppName() { return walletName; } /** * This method gives us the version of the subApp * * @return the version of the subApp */ @Override public Version getSubAppVersion() { return version; } @Override public String getAppName() { return subApps.getCode(); } @Override public String getAppPublicKey() { return publicKey; } }
923a3257796d3a2bd6b892982d6be7a786fe46a5
1,659
java
Java
src/main/java/hudson/plugins/accurev/util/BuildChooser.java
WiMills/accurev-scm-plugin
6e17cd4a3ca7d52aa89a9d846d10c53f35ebe2ce
[ "MIT" ]
1
2021-12-07T20:47:58.000Z
2021-12-07T20:47:58.000Z
src/main/java/hudson/plugins/accurev/util/BuildChooser.java
WiMills/accurev-scm-plugin
6e17cd4a3ca7d52aa89a9d846d10c53f35ebe2ce
[ "MIT" ]
1
2020-03-05T12:16:59.000Z
2020-03-05T12:16:59.000Z
src/main/java/hudson/plugins/accurev/util/BuildChooser.java
WiMills/accurev-scm-plugin
6e17cd4a3ca7d52aa89a9d846d10c53f35ebe2ce
[ "MIT" ]
1
2021-12-07T20:48:06.000Z
2021-12-07T20:48:06.000Z
40.463415
175
0.786618
999,112
package hudson.plugins.accurev.util; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.ExtensionPoint; import hudson.model.Describable; import hudson.model.TaskListener; import hudson.plugins.accurev.AccurevSCM; import jenkins.model.Jenkins; import jenkins.plugins.accurevclient.AccurevClient; import jenkins.plugins.accurevclient.model.AccurevTransaction; import java.io.Serializable; import java.util.Collection; public abstract class BuildChooser implements ExtensionPoint, Describable<BuildChooser>, Serializable { public transient AccurevSCM accurevSCM; /** * Short-hand to get to the display name. * @return display name of this build chooser */ public final String getDisplayName() { return getDescriptor().getDisplayName(); } public Collection<AccurevTransaction> getCandidateTransactions(boolean isPollCall, String streamSpec, AccurevClient ac, TaskListener listener, BuildData data){ throw new UnsupportedOperationException("getCandidateRevisions method must be overridden"); } public Collection<AccurevTransaction> getCandidateTransactions(boolean isPollCall, String streamSpec, AccurevClient ac, TaskListener listener, BuildData data, long bound){ throw new UnsupportedOperationException("getCandidateRevisions method must be overridden"); } @Override @SuppressFBWarnings(value="NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification="Jenkins.getInstance() is not null") public BuildChooserDescriptor getDescriptor() { return (BuildChooserDescriptor)Jenkins.getInstanceOrNull().getDescriptorOrDie(getClass()); } }
923a327aa3f1e38c7d97cce22e7d0359590e1d29
1,469
java
Java
Lecture 13/Question3.java
ankittojha/Codetantra-Programming-In-Java-Solution
07949084bf83ca85f4a864990544e774c839a6b1
[ "MIT" ]
1
2022-02-13T16:07:34.000Z
2022-02-13T16:07:34.000Z
Lecture 13/Question3.java
akaAkhiil/Codetantra-Programming-In-Java-Solution
ee801ab8d2d98eabf6fd6f5b6e2a369cffea7d92
[ "MIT" ]
1
2022-02-23T16:08:18.000Z
2022-02-23T16:08:18.000Z
Lecture 13/Question3.java
akaAkhiil/Codetantra-Programming-In-Java-Solution
ee801ab8d2d98eabf6fd6f5b6e2a369cffea7d92
[ "MIT" ]
2
2022-02-25T09:15:46.000Z
2022-03-06T12:33:36.000Z
33.386364
159
0.720218
999,113
A programmer can instruct the compiler to explicitly convert a value of one type to another using a typecast operator. When a typecast operator is explicitly used, the type conversion process is called explicit type conversion or type casting. The syntax for using a typecast operator is: (data_type) expression, Where the expression is converted to the target data_type enclosed within the parentheses. Here the expression may contains constants or variables and the data_type must be a primitive data type or void. For example, the expression (float)1 / 3 is evaluated as 1.0 / 3 yielding 0.333333, where as 1 / 3 yields 0. In the expression ((int)num)%2, if num is a float variable with value 5.5, then the expression evaluates to 1. Below is an example which demonstrates type casting: public class ExplicitConversion { public static void main(String[] args) { float x, y; x = 7 / 3; y = (float) 7 / 3; System.out.println("x = " + x + " y = " + y); } } In the above code, produces the output as x = 2.0 y = 2.3333333. See and retype the below code. Note: Please don't change the package name.' Answer package q10843; public class ExplicitConversion { public static void main(String[] args) { int i = (int)18.99f; System.out.println("int value = " + i); float f = i; System.out.println("after float widening : " + f); int big = 1234567890; float approx = big; System.out.println("The lose value = " + (big - (int)approx)); } }
923a32f1d3c754b049285cdb4e936bb15d15b588
1,200
java
Java
gmall-sms/src/main/java/com/atguigu/gmall/sms/entity/SkuLadderEntity.java
dxm11111/gmall-0805
03737fea394fece55a2f00ac8d0fdbf63d48df6a
[ "Apache-2.0" ]
null
null
null
gmall-sms/src/main/java/com/atguigu/gmall/sms/entity/SkuLadderEntity.java
dxm11111/gmall-0805
03737fea394fece55a2f00ac8d0fdbf63d48df6a
[ "Apache-2.0" ]
1
2021-04-22T17:03:03.000Z
2021-04-22T17:03:03.000Z
gmall-sms/src/main/java/com/atguigu/gmall/sms/entity/SkuLadderEntity.java
dxm11111/gmall-0805
03737fea394fece55a2f00ac8d0fdbf63d48df6a
[ "Apache-2.0" ]
null
null
null
20.655172
70
0.703673
999,114
package com.atguigu.gmall.sms.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 商品阶梯价格 * * @author duxuemei * @email anpch@example.com * @date 2020-01-07 21:10:27 */ @ApiModel @Data @TableName("sms_sku_ladder") public class SkuLadderEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId @ApiModelProperty(name = "id",value = "id") private Long id; /** * spu_id */ @ApiModelProperty(name = "skuId",value = "spu_id") private Long skuId; /** * 满几件 */ @ApiModelProperty(name = "fullCount",value = "满几件") private Integer fullCount; /** * 打几折 */ @ApiModelProperty(name = "discount",value = "打几折") private BigDecimal discount; /** * 折后价 */ @ApiModelProperty(name = "price",value = "折后价") private BigDecimal price; /** * 是否叠加其他优惠[0-不可叠加,1-可叠加] */ @ApiModelProperty(name = "addOther",value = "是否叠加其他优惠[0-不可叠加,1-可叠加]") private Integer addOther; }
923a338def47f395463367591d29c61463ed1cf6
978
java
Java
userservice/src/main/java/com/stackroute/userservice/seed/Seed.java
stackroute/ibm-wave3-plasma-hackathon
e6aca83d3292770107cc46e898e1a6bd9840bdda
[ "Apache-2.0" ]
null
null
null
userservice/src/main/java/com/stackroute/userservice/seed/Seed.java
stackroute/ibm-wave3-plasma-hackathon
e6aca83d3292770107cc46e898e1a6bd9840bdda
[ "Apache-2.0" ]
102
2019-02-22T11:08:04.000Z
2019-02-22T12:22:27.000Z
userservice/src/main/java/com/stackroute/userservice/seed/Seed.java
stackroute/ibm-wave3-plasma-hackathon
e6aca83d3292770107cc46e898e1a6bd9840bdda
[ "Apache-2.0" ]
null
null
null
37.538462
127
0.758197
999,115
package com.stackroute.userservice.seed; import com.stackroute.userservice.domain.User; import com.stackroute.userservice.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component public class Seed implements ApplicationListener<ContextRefreshedEvent> { UserRepository userRepository; @Autowired public Seed(UserRepository userRepository) { this.userRepository = userRepository; } @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { // userRepository.save(new User("1122","akhila","ak123","ak123", "upchh@example.com", "{("Movies"), ("TvShows")}", "F")); // userRepository.save(new User("2244","akhil","hello1","hello1", "upchh@example.com", {("Movies"), ("TvShows")},"M")); } }
923a33c6a33faa834c08d89603e51fb5a437a7d1
732
java
Java
src/main/java/org/pes/onecemulator/ui/view/expenserequestadmin/dialog/edit/ExpenseRequestPaidEditField.java
marker91/one-c-emulator
ebb3ebc385ff2ecc411150ed3706c104e1c44c27
[ "MIT" ]
null
null
null
src/main/java/org/pes/onecemulator/ui/view/expenserequestadmin/dialog/edit/ExpenseRequestPaidEditField.java
marker91/one-c-emulator
ebb3ebc385ff2ecc411150ed3706c104e1c44c27
[ "MIT" ]
7
2018-02-26T11:56:22.000Z
2018-12-09T08:03:38.000Z
src/main/java/org/pes/onecemulator/ui/view/expenserequestadmin/dialog/edit/ExpenseRequestPaidEditField.java
akorchaginn/one-c-emulator
ebb3ebc385ff2ecc411150ed3706c104e1c44c27
[ "MIT" ]
1
2017-10-06T10:49:56.000Z
2017-10-06T10:49:56.000Z
28.153846
115
0.718579
999,116
package org.pes.onecemulator.ui.view.expenserequestadmin.dialog.edit; import com.vaadin.data.BeanValidationBinder; import com.vaadin.ui.CheckBox; import org.pes.onecemulator.model.internal.ExpenseRequestModel; class ExpenseRequestPaidEditField extends CheckBox { final BeanValidationBinder<ExpenseRequestModel> binder = new BeanValidationBinder<>(ExpenseRequestModel.class); private final boolean origin; ExpenseRequestPaidEditField(final boolean origin) { this.origin = origin; setValue(origin); setCaption("Оплачено"); setSizeFull(); binder.bind(this, "paid"); } boolean hasChanges() { final boolean now = getValue(); return origin != now; } }
923a3508afda0419ae1d4373ad3a4ccffa6de02b
426
java
Java
app/src/main/java/com/example/admin/sjweather/util/HttpUtil.java
sunjingdev/coolweather
60773f1ecc9ddab8c7c4c34873e7b8b206be0b90
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/admin/sjweather/util/HttpUtil.java
sunjingdev/coolweather
60773f1ecc9ddab8c7c4c34873e7b8b206be0b90
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/admin/sjweather/util/HttpUtil.java
sunjingdev/coolweather
60773f1ecc9ddab8c7c4c34873e7b8b206be0b90
[ "Apache-2.0" ]
null
null
null
25.058824
83
0.713615
999,117
package com.example.admin.sjweather.util; import okhttp3.OkHttpClient; import okhttp3.Request; /** * Created by admin on 2020/2/2. */ public class HttpUtil { public static void sendOkHttpRequest(String address,okhttp3.Callback callback){ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); } }
923a352ac9bf19c78594849a1e68ae3b9b327e06
2,327
java
Java
pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStep.java
rottkit/pitest
2674985bdfcf2b6d2bc41ebcdbedaf5d4d9d2297
[ "Apache-2.0" ]
3
2018-04-18T06:45:31.000Z
2019-12-13T11:48:13.000Z
pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStep.java
rottkit/pitest
2674985bdfcf2b6d2bc41ebcdbedaf5d4d9d2297
[ "Apache-2.0" ]
4
2018-03-21T12:37:50.000Z
2018-04-05T19:38:28.000Z
pitest/src/test/java/org/pitest/simpletest/steps/NoArgsInstantiateStep.java
rottkit/pitest
2674985bdfcf2b6d2bc41ebcdbedaf5d4d9d2297
[ "Apache-2.0" ]
3
2018-02-15T22:04:59.000Z
2018-02-18T06:04:27.000Z
26.747126
101
0.666523
999,118
/* * Copyright 2010 Henry Coles * * 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.pitest.simpletest.steps; import java.lang.reflect.Modifier; import org.pitest.simpletest.CanNotCreateTestClassException; import org.pitest.simpletest.TestStep; import org.pitest.testapi.Description; /** * @author henry * */ public final class NoArgsInstantiateStep implements TestStep { private final Class<?> clazz; public static NoArgsInstantiateStep instantiate(final Class<?> clazz) { return new NoArgsInstantiateStep(clazz); } public NoArgsInstantiateStep(final Class<?> clazz) { this.clazz = clazz; } @Override public Object execute(final Description testDescription, final Object target) { try { final Class<?> c = this.clazz; if (Modifier.isAbstract(c.getModifiers())) { throw new CanNotCreateTestClassException( "Cannot instantiate the abstract class " + c.getName(), null); } else { return c.newInstance(); } } catch (final Throwable e) { e.printStackTrace(); throw new CanNotCreateTestClassException(e.getMessage(), e); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + ((this.clazz == null) ? 0 : this.clazz.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final NoArgsInstantiateStep other = (NoArgsInstantiateStep) obj; if (this.clazz == null) { if (other.clazz != null) { return false; } } else if (!this.clazz.equals(other.clazz)) { return false; } return true; } }
923a3573c4f8a1f8db79941b3b77a0472dd50cb2
1,417
java
Java
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/HealthCheckReferenceOrBuilder.java
googleapis/java-compute
28bd65d278b162538195e71b7dbb3d83d909514c
[ "Apache-2.0" ]
19
2020-01-28T12:32:27.000Z
2022-02-12T07:48:33.000Z
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/HealthCheckReferenceOrBuilder.java
googleapis/java-compute
28bd65d278b162538195e71b7dbb3d83d909514c
[ "Apache-2.0" ]
458
2019-11-04T22:32:18.000Z
2022-03-30T00:03:12.000Z
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/HealthCheckReferenceOrBuilder.java
googleapis/java-compute
28bd65d278b162538195e71b7dbb3d83d909514c
[ "Apache-2.0" ]
23
2019-10-31T21:05:28.000Z
2021-08-24T16:35:45.000Z
31.488889
95
0.722653
999,119
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; public interface HealthCheckReferenceOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.HealthCheckReference) com.google.protobuf.MessageOrBuilder { /** * <code>optional string health_check = 308876645;</code> * * @return Whether the healthCheck field is set. */ boolean hasHealthCheck(); /** * <code>optional string health_check = 308876645;</code> * * @return The healthCheck. */ java.lang.String getHealthCheck(); /** * <code>optional string health_check = 308876645;</code> * * @return The bytes for healthCheck. */ com.google.protobuf.ByteString getHealthCheckBytes(); }
923a35e52114e13a51c23e203b2e67eb30d2a35a
810
java
Java
RobotArdu/src/test/java/de/fhg/iais/roberta/ast/syntax/actors/DriveActionTest.java
nishanth1232/openroberta-lab
1e50ddebffe1f4769156ea3906f3a7cedfdba663
[ "Apache-2.0" ]
3
2020-01-24T18:29:16.000Z
2020-09-30T10:54:09.000Z
RobotArdu/src/test/java/de/fhg/iais/roberta/ast/syntax/actors/DriveActionTest.java
nishanth1232/openroberta-lab
1e50ddebffe1f4769156ea3906f3a7cedfdba663
[ "Apache-2.0" ]
24
2020-04-19T20:12:22.000Z
2020-08-02T09:13:04.000Z
RobotArdu/src/test/java/de/fhg/iais/roberta/ast/syntax/actors/DriveActionTest.java
nishanth1232/openroberta-lab
1e50ddebffe1f4769156ea3906f3a7cedfdba663
[ "Apache-2.0" ]
1
2021-02-06T18:51:03.000Z
2021-02-06T18:51:03.000Z
33.75
148
0.754321
999,120
package de.fhg.iais.roberta.ast.syntax.actors; import org.junit.Ignore; import org.junit.Test; import de.fhg.iais.roberta.ast.AstTest; import de.fhg.iais.roberta.util.test.UnitTestHelper; @Ignore public class DriveActionTest extends AstTest { @Test public void drive() throws Exception { final String a = "OnFwdReg(OUT_BC,50,OUT_REGMODE_SYNC)"; UnitTestHelper.checkGeneratedSourceEqualityWithProgramXmlAndSourceAsString(testFactory, a, "/ast/actions/action_MotorDiffOn.xml", false); } @Test public void driveFor() throws Exception { final String a = "\nRotateMotorEx(OUT_BC,50,Infinity*20,0,true,true)"; UnitTestHelper.checkGeneratedSourceEqualityWithProgramXmlAndSourceAsString(testFactory, a, "/ast/actions/action_MotorDiffOnFor.xml", false); } }
923a3623df70e574d1ee25124a6877beef694f48
9,270
java
Java
src/main/java/info/freelibrary/bagit/AbstractManifest.java
ksclarke/freelib-bagit
897f66b6cfc34451c87ae6211371c118d873e488
[ "BSD-3-Clause" ]
null
null
null
src/main/java/info/freelibrary/bagit/AbstractManifest.java
ksclarke/freelib-bagit
897f66b6cfc34451c87ae6211371c118d873e488
[ "BSD-3-Clause" ]
1
2018-06-17T18:12:34.000Z
2018-06-17T18:12:34.000Z
src/main/java/info/freelibrary/bagit/AbstractManifest.java
ksclarke/freelib-bagit
897f66b6cfc34451c87ae6211371c118d873e488
[ "BSD-3-Clause" ]
2
2019-01-12T06:15:03.000Z
2019-05-08T06:19:54.000Z
30.695364
102
0.591154
999,121
package info.freelibrary.bagit; import java.io.File; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import info.freelibrary.util.BufferedFileReader; import info.freelibrary.util.BufferedFileWriter; import info.freelibrary.util.FileUtils; import info.freelibrary.util.Logger; import info.freelibrary.util.RegexFileFilter; import info.freelibrary.util.StringUtils; /** * An abstract manifest class from which other specific manifests are implemented. */ abstract class AbstractManifest { private static final String DEFAULT_ALGORITHM = "md5"; private static final String HASH_PROP = "bagit_hash"; private static final String SPACE = " "; private final File myBagDir; private String myFileName; private String myHashAlgorithm; private final List<Entry> myHashes; private boolean myManifestsAreSortable; protected AbstractManifest(final File aBagDir) throws IOException { String pattern = StringUtils.format(getNamePattern(), "(.*)"); final File[] files = aBagDir.listFiles(new RegexFileFilter(pattern)); myHashes = new ArrayList<>(); myBagDir = aBagDir; // Bag can contain more than one manifest, but must not contain more // than one of the same algorithm type - TODO: handle 2+ algorithms? if (files.length > 0) { final String fileName = files[0].getName(); final Matcher matcher = Pattern.compile(pattern).matcher(fileName); BufferedFileReader reader = null; String line; try { reader = new BufferedFileReader(files[0]); if (getLogger().isDebugEnabled()) { getLogger().debug(MessageCodes.BAGIT_002, fileName); } matcher.find(); myHashAlgorithm = matcher.group(1); if (getLogger().isDebugEnabled()) { getLogger().debug(MessageCodes.BAGIT_001, myHashAlgorithm); } if (getLogger().isDebugEnabled()) { getLogger().debug(MessageCodes.BAGIT_034, files[0]); } while ((line = reader.readLine()) != null) { final String cleanedLine = line.replaceAll("[\\s|\\*]+", SPACE); final String[] parts = cleanedLine.split(SPACE); final File file = new File(aBagDir, parts[1]); final String relativePath = getRelativePath(file); if (getLogger().isDebugEnabled()) { getLogger().debug(MessageCodes.BAGIT_035, parts[0] + SPACE + relativePath); } myHashes.add(new Entry(file, parts[0])); } } finally { reader.close(); } } else { pattern = getNamePattern(); myHashAlgorithm = System.getProperty(HASH_PROP, DEFAULT_ALGORITHM); myFileName = StringUtils.format(pattern, myHashAlgorithm); if (getLogger().isDebugEnabled()) { getLogger().debug(MessageCodes.BAGIT_001, myHashAlgorithm); } myManifestsAreSortable = true; } } /** * Returns the hash algorithm used in the manifest file. * * @return The hash algorithm in the manifest file */ public String getHashAlgorithm() { return myHashAlgorithm; } /** * Returns the number of entries in the manifest file. * * @return The number of entries in the manifest file */ public int countEntries() { return myHashes.size(); } @Override public String toString() { final String eol = System.getProperty("line.separator"); final StringBuilder builder = new StringBuilder(50); final Iterator<Entry> iterator = myHashes.iterator(); while (iterator.hasNext()) { final Entry entry = iterator.next(); builder.append("<file name=\""); builder.append(getRelativePath(entry.myFile)).append("\" hash=\""); builder.append(entry.myHash).append("\" algorithm=\""); builder.append(myHashAlgorithm).append("\" />").append(eol); } return builder.toString(); } /** * Gets the path of the supplied <code>File</code>, relative to the BagIt working directory. * * @param aFile A file to get the relative path of (relative to the working directory) */ private String getRelativePath(final File aFile) { final int start = myBagDir.getAbsolutePath().length() + 1; return aFile.getAbsolutePath().substring(start); } protected abstract Logger getLogger(); protected abstract String getNamePattern(); File[] getFiles() { final ArrayList<File> files = new ArrayList<>(); final Iterator<Entry> entryIterator = myHashes.iterator(); while (entryIterator.hasNext()) { final Entry entry = entryIterator.next(); files.add(entry.myFile); } return files.toArray(new File[myHashes.size()]); } /** * Returns the hash associated with the supplied <code>File</code> or null if there isn't one yet. * * @param aFile * @return */ String getStoredHash(final File aFile) { final Iterator<Entry> entryIterator = myHashes.iterator(); while (entryIterator.hasNext()) { final Entry entry = entryIterator.next(); if (entry.myFile.getAbsolutePath().equals(aFile.getAbsolutePath())) { return entry.myHash; } } return null; } /** * Adds a new file to the manifest. * * @param aFile * @throws IOException * @throws NoSuchAlgorithmException */ void add(final File aFile) throws IOException, NoSuchAlgorithmException { myHashes.add(new Entry(aFile, FileUtils.hash(aFile, myHashAlgorithm))); } /** * Deletes the manifest file(s). * * @throws IOException If there is trouble deleting the manifest file(s) */ void delete() throws IOException { final String pattern = StringUtils.format("[.*]", getNamePattern()); final RegexFileFilter mFilter = new RegexFileFilter(pattern); // Remove the old payload file manifest if it exists for (final File manifest : myBagDir.listFiles(mFilter)) { if (getLogger().isDebugEnabled()) { getLogger().debug(MessageCodes.BAGIT_031, manifest); } if (!manifest.delete()) { throw new IOException(getLogger().getMessage(MessageCodes.BAGIT_006, manifest)); } } myHashes.clear(); } boolean remove(final File aFile) throws IOException, NoSuchAlgorithmException { final String algorithm = FileUtils.hash(aFile, myHashAlgorithm); return myHashes.remove(new Entry(aFile, algorithm)); } /** * Writes the contents of the manifest to a file in the BagIt working directory. * * @throws IOException If there is a problem writing the manifest file */ void writeToFile() throws IOException { final File manifestFile = new File(myBagDir, myFileName); final Iterator<Entry> iterator; BufferedFileWriter writer = null; if (myManifestsAreSortable) { Collections.sort(myHashes); } iterator = myHashes.iterator(); try { if (manifestFile.exists()) { manifestFile.delete(); } writer = new BufferedFileWriter(manifestFile); while (iterator.hasNext()) { final Entry entry = iterator.next(); writer.write(entry.myHash); writer.write(SPACE); writer.write(getRelativePath(entry.myFile)); writer.newLine(); } } finally { if (writer != null) { writer.close(); } } } private static final class Entry implements Comparable<Entry> { private final File myFile; private final String myHash; private Entry(final File aFile, final String aHash) { myFile = aFile; myHash = aHash; } @Override public int compareTo(final Entry aEntry) { if (aEntry == this) { return 0; } return myFile.getAbsolutePath().compareToIgnoreCase(aEntry.myFile.getAbsolutePath()); } @Override public boolean equals(final Object aObject) { if (aObject == this) { return true; } if (aObject instanceof Entry) { return myFile.getAbsolutePath().equals(((Entry) aObject).myFile.getAbsolutePath()); } return false; } @Override public int hashCode() { return myFile.getAbsolutePath().hashCode(); } } }
923a36e9e0939a14337740cd385ce7ad57489e10
3,818
java
Java
app/src/main/java/com/example/android/gwg_abnd18_home2mars_tour_guide_app/MuseumsFragment.java
home2mars/GWG_ABND18_home2mars_Tour_Guide_App
9e4a677fb8d1a5785757bf6f1bd2e37f0ae0f4d9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/gwg_abnd18_home2mars_tour_guide_app/MuseumsFragment.java
home2mars/GWG_ABND18_home2mars_Tour_Guide_App
9e4a677fb8d1a5785757bf6f1bd2e37f0ae0f4d9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/gwg_abnd18_home2mars_tour_guide_app/MuseumsFragment.java
home2mars/GWG_ABND18_home2mars_Tour_Guide_App
9e4a677fb8d1a5785757bf6f1bd2e37f0ae0f4d9
[ "Apache-2.0" ]
null
null
null
41.956044
108
0.660555
999,122
package com.example.android.gwg_abnd18_home2mars_tour_guide_app; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class MuseumsFragment extends Fragment { public MuseumsFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.place_list, container, false); // Create a list of places final ArrayList<Place> places = new ArrayList<Place>(); places.add(new Place(getString(R.string.mus_african_american_name), getString(R.string.mus_african_american_tagline), getString(R.string.mus_african_american_website), R.drawable.mus_african_american)); //10am-5:30pm places.add(new Place(getString(R.string.mus_galery_art_name), getString(R.string.mus_galery_art_tagline), getString(R.string.mus_galery_art_website), R.drawable.mus_galery_art)); //10am-5pm Mon-Sat, 11am-6pm Sun places.add(new Place(getString(R.string.mus_air_and_space_name), getString(R.string.mus_air_and_space_tagline), getString(R.string.mus_air_and_space_website), R.drawable.mus_air_and_space)); //10am-5:30pm places.add(new Place(getString(R.string.mus_lincoln_memorial_name), getString(R.string.mus_lincoln_memorial_tagline), getString(R.string.mus_lincoln_memorial_website), R.drawable.mus_lincoln_memorial)); //24 hrs // Create an {@link PlaceAdapter}, whose data source is a list of {@link Place}s. The // adapter knows how to create list items for each item in the list. PlaceAdapter adapter = new PlaceAdapter(getActivity(), places, R.color.category_museums); // Find the {@link ListView} object in the view hierarchy of the {@link Activity}. // There should be a {@link ListView} with the view ID called list, which is declared in the // place_list.xmll layout file. ListView listView = (ListView) rootView.findViewById(R.id.list); // Make the {@link ListView} use the {@link PlaceAdapter} we created above, so that the // {@link ListView} will display list items for each {@link Place} in the list. listView.setAdapter(adapter); // Set a click listener to open a browser to open the website of the list item is clicked on listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { // Get the {@link Place} object at the given position the user clicked on Place place = places.get(position); //this could be shortened but leave it here for clarity Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(place.getWebsite())); try { getContext().startActivity(intent); } catch (ActivityNotFoundException ex){ Toast.makeText(getContext(), R.string.no_browser_app_message, Toast.LENGTH_LONG).show(); } } }); return rootView; } }
923a374a4efd8308454d12fd938e85f51be135a4
1,566
java
Java
src/main/java/com/google/code/vaadin/mvp/eventhandling/SharedModelEventPublisher.java
sblommers/guice-vaadin-mvp
d90420f3242ad8336ab503563da0fc9b302666aa
[ "Apache-2.0" ]
null
null
null
src/main/java/com/google/code/vaadin/mvp/eventhandling/SharedModelEventPublisher.java
sblommers/guice-vaadin-mvp
d90420f3242ad8336ab503563da0fc9b302666aa
[ "Apache-2.0" ]
null
null
null
src/main/java/com/google/code/vaadin/mvp/eventhandling/SharedModelEventPublisher.java
sblommers/guice-vaadin-mvp
d90420f3242ad8336ab503563da0fc9b302666aa
[ "Apache-2.0" ]
null
null
null
40.153846
134
0.750958
999,123
/* * Copyright (C) 2013 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.code.vaadin.mvp.eventhandling; import com.google.code.vaadin.application.AbstractMVPApplicationModule; import com.google.code.vaadin.components.eventhandling.configuration.EventBusBinder; import com.google.inject.Scopes; /** * Event publisher for global (shared) Model-related events. * There is no default subscribers for this kind of events. * This publisher is application-scoped (singleton). * <p/> * NOTE: shared model EventBus is disabled by default. Use {@link EventBusBinder} and * {@link AbstractMVPApplicationModule#bindEventBuses(EventBusBinder)} to bind EventBus with {@link EventBusTypes#SHARED_MODEL} type. * * @author Alexey Krylov * @see Scopes#SINGLETON * @since 23.01.13 */ public interface SharedModelEventPublisher extends EventPublisher { }
923a37bebde3048f8ddaaff523a24c6b9b9ff984
559
java
Java
modules-test/src/main/java/com/itsherman/modulestest/ModulesTestApplication.java
yumiaoxia/spring-boot-demos
5690ddf5fc588b029731fc70bd94bd6520ba2c32
[ "Apache-2.0" ]
null
null
null
modules-test/src/main/java/com/itsherman/modulestest/ModulesTestApplication.java
yumiaoxia/spring-boot-demos
5690ddf5fc588b029731fc70bd94bd6520ba2c32
[ "Apache-2.0" ]
1
2022-03-31T20:42:26.000Z
2022-03-31T20:42:26.000Z
modules-test/src/main/java/com/itsherman/modulestest/ModulesTestApplication.java
yumiaoxia/spring-boot-demos
5690ddf5fc588b029731fc70bd94bd6520ba2c32
[ "Apache-2.0" ]
null
null
null
32.882353
94
0.812165
999,124
package com.itsherman.modulestest; import com.itsherman.dto.assembler.annotations.DtoMapping; import com.itsherman.dto.assembler.annotations.EnableDtoMapping; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @EnableDtoMapping(mappings = {@DtoMapping(basePackage = "com.itsherman.modulestest.web.dto")}) @SpringBootApplication public class ModulesTestApplication { public static void main(String[] args) { SpringApplication.run(ModulesTestApplication.class, args); } }
923a37c2379aeeb0a9e98a624025e23903c0542a
193
java
Java
kcp-netty/src/main/java/io/jpower/kcp/netty/internal/ReItrSet.java
l42111996/kcp-netty
f053810c5a265c181a8b37efc9de607fcb7a780f
[ "MIT" ]
234
2017-09-07T08:40:06.000Z
2022-03-15T07:49:55.000Z
kcp-netty/src/main/java/io/jpower/kcp/netty/internal/ReItrSet.java
l42111996/kcp-netty
f053810c5a265c181a8b37efc9de607fcb7a780f
[ "MIT" ]
29
2018-03-08T07:16:03.000Z
2022-02-10T02:33:47.000Z
kcp-netty/src/main/java/io/jpower/kcp/netty/internal/ReItrSet.java
l42111996/kcp-netty
f053810c5a265c181a8b37efc9de607fcb7a780f
[ "MIT" ]
73
2017-09-10T09:26:56.000Z
2022-01-18T07:53:54.000Z
17.454545
65
0.697917
999,125
package io.jpower.kcp.netty.internal; import java.util.Set; /** * @author <a href="mailto:upchh@example.com">szh</a> */ public interface ReItrSet<E> extends Set<E>, ReItrCollection<E> { }
923a3820234e2470f4b6784ae38f12821a55a411
1,305
java
Java
javaCodeTest/src/test/java/org/test/Hex16.java
shuxuecode/codeDemo
6368dca611802f5a39ee77cd11c99c14033d5cc0
[ "MIT" ]
null
null
null
javaCodeTest/src/test/java/org/test/Hex16.java
shuxuecode/codeDemo
6368dca611802f5a39ee77cd11c99c14033d5cc0
[ "MIT" ]
null
null
null
javaCodeTest/src/test/java/org/test/Hex16.java
shuxuecode/codeDemo
6368dca611802f5a39ee77cd11c99c14033d5cc0
[ "MIT" ]
null
null
null
22.5
111
0.528736
999,126
package org.test; import com.sun.javafx.scene.traversal.Algorithm; import java.nio.charset.StandardCharsets; import java.security.AlgorithmConstraints; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * todo * @author * @date 2022/4/12 */ public class Hex16 { static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; public static String encode(String str) { try { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(bytes); byte[] md = md5.digest(); int len = md.length; char[] chars = new char[len * 2]; int k = 0; for (int i = 0; i < len; i++) { byte b = md[i]; chars[k++] = hexDigits[b >>> 4 & 0xf]; chars[k++] = hexDigits[b & 0xf]; } return new String(chars); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { String str = "hello world"; String encode = encode(str); System.out.println(encode); } }
923a38ed4c231032d4414413214be94c76b34081
5,604
java
Java
src/main/java/com/tencentcloudapi/kms/v20190118/models/ListKeysRequest.java
TencentCloud/tencentcloud-sdk-java-intl-en
1c50ecf932a175ee06fa8b9568c2f20faf566d96
[ "Apache-2.0" ]
3
2020-04-07T03:13:05.000Z
2021-06-21T10:19:37.000Z
src/main/java/com/tencentcloudapi/kms/v20190118/models/ListKeysRequest.java
TencentCloud/tencentcloud-sdk-java-intl-en
1c50ecf932a175ee06fa8b9568c2f20faf566d96
[ "Apache-2.0" ]
3
2021-04-26T11:46:42.000Z
2022-01-19T01:07:07.000Z
src/main/java/com/tencentcloudapi/kms/v20190118/models/ListKeysRequest.java
TencentCloud/tencentcloud-sdk-java-intl-en
1c50ecf932a175ee06fa8b9568c2f20faf566d96
[ "Apache-2.0" ]
2
2020-04-07T03:13:11.000Z
2021-04-26T11:35:25.000Z
44.832
231
0.689329
999,127
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.kms.v20190118.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class ListKeysRequest extends AbstractModel{ /** * This parameter has the same meaning of the `Offset` in an SQL query, indicating that this acquisition starts from the "No. Offset value" element of the array arranged in a certain order. The default value is 0 */ @SerializedName("Offset") @Expose private Long Offset; /** * This parameter has the same meaning of the `Limit` in an SQL query, indicating that up to `Limit` value elements can be obtained in this request. The default value is 10 and the maximum value is 200 */ @SerializedName("Limit") @Expose private Long Limit; /** * Filter by creator role. 0 (default value): the CMK is created by the user; 1: the CMK is created automatically by an authorized Tencent Cloud service */ @SerializedName("Role") @Expose private Long Role; /** * Get This parameter has the same meaning of the `Offset` in an SQL query, indicating that this acquisition starts from the "No. Offset value" element of the array arranged in a certain order. The default value is 0 * @return Offset This parameter has the same meaning of the `Offset` in an SQL query, indicating that this acquisition starts from the "No. Offset value" element of the array arranged in a certain order. The default value is 0 */ public Long getOffset() { return this.Offset; } /** * Set This parameter has the same meaning of the `Offset` in an SQL query, indicating that this acquisition starts from the "No. Offset value" element of the array arranged in a certain order. The default value is 0 * @param Offset This parameter has the same meaning of the `Offset` in an SQL query, indicating that this acquisition starts from the "No. Offset value" element of the array arranged in a certain order. The default value is 0 */ public void setOffset(Long Offset) { this.Offset = Offset; } /** * Get This parameter has the same meaning of the `Limit` in an SQL query, indicating that up to `Limit` value elements can be obtained in this request. The default value is 10 and the maximum value is 200 * @return Limit This parameter has the same meaning of the `Limit` in an SQL query, indicating that up to `Limit` value elements can be obtained in this request. The default value is 10 and the maximum value is 200 */ public Long getLimit() { return this.Limit; } /** * Set This parameter has the same meaning of the `Limit` in an SQL query, indicating that up to `Limit` value elements can be obtained in this request. The default value is 10 and the maximum value is 200 * @param Limit This parameter has the same meaning of the `Limit` in an SQL query, indicating that up to `Limit` value elements can be obtained in this request. The default value is 10 and the maximum value is 200 */ public void setLimit(Long Limit) { this.Limit = Limit; } /** * Get Filter by creator role. 0 (default value): the CMK is created by the user; 1: the CMK is created automatically by an authorized Tencent Cloud service * @return Role Filter by creator role. 0 (default value): the CMK is created by the user; 1: the CMK is created automatically by an authorized Tencent Cloud service */ public Long getRole() { return this.Role; } /** * Set Filter by creator role. 0 (default value): the CMK is created by the user; 1: the CMK is created automatically by an authorized Tencent Cloud service * @param Role Filter by creator role. 0 (default value): the CMK is created by the user; 1: the CMK is created automatically by an authorized Tencent Cloud service */ public void setRole(Long Role) { this.Role = Role; } public ListKeysRequest() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public ListKeysRequest(ListKeysRequest source) { if (source.Offset != null) { this.Offset = new Long(source.Offset); } if (source.Limit != null) { this.Limit = new Long(source.Limit); } if (source.Role != null) { this.Role = new Long(source.Role); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "Offset", this.Offset); this.setParamSimple(map, prefix + "Limit", this.Limit); this.setParamSimple(map, prefix + "Role", this.Role); } }
923a395781f754a5acfe5e8744831032d677cd18
5,078
java
Java
dataprep-backend-common/src/main/java/org/talend/dataprep/api/preparation/Step.java
ddstest/ddsprep
0b16d8487288df6ed71cdbac9c334a88195360af
[ "Apache-2.0" ]
null
null
null
dataprep-backend-common/src/main/java/org/talend/dataprep/api/preparation/Step.java
ddstest/ddsprep
0b16d8487288df6ed71cdbac9c334a88195360af
[ "Apache-2.0" ]
null
null
null
dataprep-backend-common/src/main/java/org/talend/dataprep/api/preparation/Step.java
ddstest/ddsprep
0b16d8487288df6ed71cdbac9c334a88195360af
[ "Apache-2.0" ]
null
null
null
26.393782
126
0.585395
999,128
// ============================================================================ // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // https://github.com/Talend/data-prep/blob/master/LICENSE // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.dataprep.api.preparation; import static org.talend.dataprep.api.preparation.PreparationActions.ROOT_ACTIONS; import java.io.Serializable; import java.util.Objects; import java.util.UUID; import com.fasterxml.jackson.annotation.JsonProperty; /** * Represents one step of a {@link Preparation}. */ public class Step extends Identifiable implements Serializable { public static final Step ROOT_STEP = new Step("vqbpgud2ghvjgm1n5hdgjnn5818fzsf2"); /** Serialization UID. */ private static final long serialVersionUID = 1L; /** The parent step. */ private String parent = "vqbpgud2ghvjgm1n5hdgjnn5818fzsf2"; /** The default preparation actions is the root actions. */ private String preparationActions = ROOT_ACTIONS.id(); /** The app version. */ @JsonProperty("app-version") private String appVersion; /** The if there are any created column with this step. */ private StepDiff diff; /** The step row metadata. */ private String rowMetadata; static { ROOT_STEP.parent = null; } /** * Default empty constructor; */ public Step() { // needed for Serialization } /** * Private constructor with id. * * @param id the id to set. */ private Step(String id) { this.id = id; } /** * Constructor. * * @param parent the parent step. * @param content the step content. * @param appVersion the app version. */ public Step(final String parent, final String content, final String appVersion) { this(parent, content, appVersion, null); } /** * Constructor. * * @param parent the parent step. * @param content the action content. * @param appVersion the app version. * @param diff the step diff. */ public Step(final String parent, final String content, final String appVersion, final StepDiff diff) { this.id = UUID.randomUUID().toString(); this.parent = parent; this.preparationActions = content; this.appVersion = appVersion; this.diff = diff; } public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public StepDiff getDiff() { return diff; } public void setDiff(StepDiff diff) { this.diff = diff; } public String getAppVersion() { return appVersion; } @Override public String id() { return getId(); } @Override public String getId() { return id; } @Override public void setId(String id) { if (ROOT_STEP.id.equals(id)) { parent = null; } this.id = id; } public String getContent() { return preparationActions == null ? PreparationActions.ROOT_ACTIONS.id() : preparationActions; } public void setContent(String preparationActions) { if (Step.ROOT_STEP.id().equals(id) && !PreparationActions.ROOT_ACTIONS.id().equals(preparationActions)) { throw new IllegalArgumentException("Preparation action '" + preparationActions + "' is not valid for root step."); } this.preparationActions = preparationActions; } /** * @return The row metadata linked to this step. Might be <code>null</code> to indicate no row metadata is present. */ public String getRowMetadata() { return rowMetadata; } /** * Set the row metadata for this step. * * @param rowMetadata The row metadata to set for this step. */ public void setRowMetadata(String rowMetadata) { this.rowMetadata = rowMetadata; } @Override public String toString() { String result = "Step{parentId='"; if (parent != null) { result += parent; } else { result += "null"; } result += '\'' + // ", actions='" + preparationActions + '\'' + // ", appVersion='" + appVersion + '\'' + // ", diff=" + diff + // '}'; return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Step step = (Step) o; return Objects.equals(getId(), step.getId()); } @Override public int hashCode() { return Objects.hash(parent, preparationActions, rowMetadata, appVersion, diff); } }
923a39879e40c5c381e06fc475589c3c82ef99a1
10,581
java
Java
src/test/java/liquibase/ext/MongoLiquibaseIT.java
LawrenceMouarkach/liquibase-mongodb
165e81a30d3275e944f0ba77eb3bfd67f9bf4e5a
[ "Apache-2.0" ]
null
null
null
src/test/java/liquibase/ext/MongoLiquibaseIT.java
LawrenceMouarkach/liquibase-mongodb
165e81a30d3275e944f0ba77eb3bfd67f9bf4e5a
[ "Apache-2.0" ]
null
null
null
src/test/java/liquibase/ext/MongoLiquibaseIT.java
LawrenceMouarkach/liquibase-mongodb
165e81a30d3275e944f0ba77eb3bfd67f9bf4e5a
[ "Apache-2.0" ]
null
null
null
43.54321
152
0.662981
999,129
package liquibase.ext; /*- * #%L * Liquibase MongoDB Extension * %% * Copyright (C) 2019 Mastercard * %% * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import liquibase.Liquibase; import liquibase.change.CheckSum; import liquibase.exception.LiquibaseException; import liquibase.ext.mongodb.changelog.MongoRanChangeSet; import liquibase.ext.mongodb.changelog.MongoRanChangeSetToDocumentConverter; import liquibase.ext.mongodb.statement.FindAllStatement; import liquibase.resource.ClassLoaderResourceAccessor; import lombok.SneakyThrows; import org.bson.Document; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static liquibase.ext.mongodb.TestUtils.getCollections; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; class MongoLiquibaseIT extends AbstractMongoIntegrationTest { protected FindAllStatement findAll; protected MongoRanChangeSetToDocumentConverter converter = new MongoRanChangeSetToDocumentConverter(); @BeforeEach protected void setUpEach() { super.setUpEach(); findAll = new FindAllStatement(database.getDatabaseChangeLogTableName()); } protected Integer countCollections() { List<Object> list = new ArrayList<>(); connection.getDatabase().listCollectionNames().into(list); return list.size(); } // TODO: Check something @Test void testMongoLiquibase() throws LiquibaseException { Liquibase liquiBase = new Liquibase("liquibase/ext/changelog.insert-one.test.xml", new ClassLoaderResourceAccessor(), database); liquiBase.update(""); } @SneakyThrows @Test void testMongoClearChecksums() { final Liquibase liquibase = new Liquibase("liquibase/ext/changelog.insert-one.test.xml", new ClassLoaderResourceAccessor(), database); liquibase.update(""); List<MongoRanChangeSet> changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).hasSize(3) .extracting(MongoRanChangeSet::getId, MongoRanChangeSet::getOrderExecuted, MongoRanChangeSet::getLastCheckSum) .containsExactly( tuple("1", 1, CheckSum.parse("8:4e072f0d1a237e4e98b5edac60c3f335")), tuple("2", 2, CheckSum.parse("8:e504f1757d0460c82b54b702794b8cf7")), tuple("3", 3, CheckSum.parse("8:4eff4f9e1b017ccce8da57f3c8125f13"))); // Clear checksums liquibase.clearCheckSums(); changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).hasSize(3) .extracting(MongoRanChangeSet::getId, MongoRanChangeSet::getOrderExecuted, MongoRanChangeSet::getLastCheckSum) .containsExactly( tuple("1", 1, null), tuple("2", 2, null), tuple("3", 3, null)); // Replace null checkSums liquibase.update(""); changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).hasSize(3) .extracting(MongoRanChangeSet::getId, MongoRanChangeSet::getOrderExecuted, MongoRanChangeSet::getLastCheckSum) .containsExactly( tuple("1", 1, CheckSum.parse("8:4e072f0d1a237e4e98b5edac60c3f335")), tuple("2", 2, CheckSum.parse("8:e504f1757d0460c82b54b702794b8cf7")), tuple("3", 3, CheckSum.parse("8:4eff4f9e1b017ccce8da57f3c8125f13"))); } @SneakyThrows @Test void testMongoRollback() { final Liquibase liquibase = new Liquibase("liquibase/ext/changelog.rollback-insert-many.test.xml", new ClassLoaderResourceAccessor(), database); liquibase.update(""); List<MongoRanChangeSet> changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).hasSize(2) .extracting(MongoRanChangeSet::getId, MongoRanChangeSet::getOrderExecuted) .containsExactly( tuple("1", 1), tuple("2", 2)); FindAllStatement findAllInsertedRowsStatement = new FindAllStatement("insertManyRollback1"); List<Document> insertedRows = findAllInsertedRowsStatement.queryForList(connection); assertThat(insertedRows).hasSize(6) .extracting(d -> d.getInteger("id")) .containsExactlyInAnyOrder(1, 2, 3, 4, 5, 6); // Rollback one changeSet liquibase.rollback(1, ""); changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).hasSize(1) .extracting(MongoRanChangeSet::getId, MongoRanChangeSet::getOrderExecuted) .containsExactly( tuple("1", 1)); insertedRows = findAllInsertedRowsStatement.queryForList(connection); assertThat(insertedRows).hasSize(3) .extracting(d -> d.getInteger("id")) .containsExactlyInAnyOrder(1, 2, 3); // Rollback last changeSet liquibase.rollback(1, ""); changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).isEmpty(); insertedRows = findAllInsertedRowsStatement.queryForList(connection); assertThat(insertedRows).isEmpty(); // Re apply liquibase.update(""); changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).hasSize(2) .extracting(MongoRanChangeSet::getId, MongoRanChangeSet::getOrderExecuted) .containsExactly( tuple("1", 1), tuple("2", 2)); insertedRows = findAllInsertedRowsStatement.queryForList(connection); assertThat(insertedRows).hasSize(6) .extracting(d -> d.getInteger("id")) .containsExactlyInAnyOrder(1, 2, 3, 4, 5, 6); // Rollback both changeSet liquibase.rollback(2, ""); changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).isEmpty(); insertedRows = findAllInsertedRowsStatement.queryForList(connection); assertThat(insertedRows).isEmpty(); } @SneakyThrows @Test void testMongoImplicitRollback() { final Liquibase liquibase = new Liquibase("liquibase/ext/changelog.implicit-rollback.test.xml", new ClassLoaderResourceAccessor(), database); liquibase.update(""); List<MongoRanChangeSet> changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).hasSize(2) .extracting(MongoRanChangeSet::getId, MongoRanChangeSet::getOrderExecuted) .containsExactly( tuple("1", 1), tuple("2", 2)); assertThat(getCollections(connection)) .hasSize(4) .containsExactlyInAnyOrder("DATABASECHANGELOG", "DATABASECHANGELOGLOCK", "collection1", "collection2"); // Rollback one changeSet liquibase.rollback(1, ""); changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).hasSize(1) .extracting(MongoRanChangeSet::getId, MongoRanChangeSet::getOrderExecuted) .containsExactly( tuple("1", 1)); assertThat(getCollections(connection)) .hasSize(4) .containsExactlyInAnyOrder("DATABASECHANGELOG", "DATABASECHANGELOGLOCK", "collection1", "collection2"); // Rollback last changeSet liquibase.rollback(1, ""); changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).isEmpty(); assertThat(getCollections(connection)) .hasSize(2) .containsExactlyInAnyOrder("DATABASECHANGELOG", "DATABASECHANGELOGLOCK"); // Re apply liquibase.update(""); changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).hasSize(2) .extracting(MongoRanChangeSet::getId, MongoRanChangeSet::getOrderExecuted) .containsExactly( tuple("1", 1), tuple("2", 2)); assertThat(getCollections(connection)) .hasSize(4) .containsExactlyInAnyOrder("DATABASECHANGELOG", "DATABASECHANGELOGLOCK", "collection1", "collection2"); // Rollback both changeSet liquibase.rollback(2, ""); changeSets = findAll.queryForList(connection).stream().map(converter::fromDocument).collect(Collectors.toList()); assertThat(changeSets).isEmpty(); assertThat(getCollections(connection)) .hasSize(2) .containsExactlyInAnyOrder("DATABASECHANGELOG", "DATABASECHANGELOGLOCK"); } @Test void testMongoLiquibaseDropAll() throws LiquibaseException { Liquibase liquibase = new Liquibase("liquibase/ext/changelog.insert-one.test.xml", new ClassLoaderResourceAccessor(), database); liquibase.update(""); assertThat(countCollections()).isEqualTo(5); liquibase.dropAll(); assertThat(countCollections()).isEqualTo(0); } }
923a3b1a052d91c7015da8a3fe3a2aff1a53b2ad
830
java
Java
aws-ssm-document/src/test/java/com/amazonaws/ssm/document/CallbackContextTest.java
mgowtam/aws-cloudformation-resource-providers-ssm
e1f39ed1b6ad14d235cf3e19c7f64d830aeaa08d
[ "Apache-2.0" ]
23
2020-05-18T04:43:47.000Z
2022-02-23T04:50:52.000Z
aws-ssm-document/src/test/java/com/amazonaws/ssm/document/CallbackContextTest.java
mgowtam/aws-cloudformation-resource-providers-ssm
e1f39ed1b6ad14d235cf3e19c7f64d830aeaa08d
[ "Apache-2.0" ]
12
2020-07-20T21:16:03.000Z
2022-02-22T20:05:50.000Z
aws-ssm-document/src/test/java/com/amazonaws/ssm/document/CallbackContextTest.java
mgowtam/aws-cloudformation-resource-providers-ssm
e1f39ed1b6ad14d235cf3e19c7f64d830aeaa08d
[ "Apache-2.0" ]
24
2020-05-14T00:06:18.000Z
2022-03-24T17:28:30.000Z
34.583333
105
0.749398
999,130
package com.amazonaws.ssm.document; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class CallbackContextTest { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @Test public void testSerializeAndDeserialize() throws JsonProcessingException { final CallbackContext context = CallbackContext.builder() .stabilizationRetriesRemaining(30) .createDocumentStarted(false) .eventStarted(true) .build(); final String serializedText = OBJECT_MAPPER.writeValueAsString(context); Assertions.assertEquals(context, OBJECT_MAPPER.readValue(serializedText, CallbackContext.class)); } }
923a3b5e0ab1807a14f77b084b482d12e82c869d
1,842
java
Java
src/main/java/com/wwls/common/web/FileDownLoadWeb.java
sentimentes/base-server
a9b5b1bc769914f188a00682d647f5b1ec5a3367
[ "Apache-2.0" ]
6
2019-08-23T01:43:39.000Z
2020-09-16T08:09:35.000Z
src/main/java/com/wwls/common/web/FileDownLoadWeb.java
sentimentes/base-server
a9b5b1bc769914f188a00682d647f5b1ec5a3367
[ "Apache-2.0" ]
10
2019-11-13T11:50:16.000Z
2022-02-01T01:04:19.000Z
src/main/java/com/wwls/common/web/FileDownLoadWeb.java
sentimentes/base-server
a9b5b1bc769914f188a00682d647f5b1ec5a3367
[ "Apache-2.0" ]
null
null
null
32.315789
102
0.68241
999,131
package com.wwls.common.web; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.wwls.common.config.Global; @Controller @RequestMapping(value = "${adminPath}/common/FileDownLoadWeb") public class FileDownLoadWeb { @RequestMapping({"download"}) public void downloadFile(String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("UTF-8"); BufferedInputStream bis = null; BufferedOutputStream bos = null; String path = Global.getConfig("web.upload.path"); path = path + "/" + filePath; String file_name = filePath.substring(filePath.lastIndexOf("/") + 1); try { long fileLength = new File(path).length(); response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + file_name); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(path)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } }
923a3bcd0c7f72b9a9b4afeb6834f664eedd864d
443
java
Java
src/main/java/com/unascribed/legacycustompublish/LegacyCustomPublish.java
unascribed/LegacyCustomPublish
baf48db55de527930678a0fc95a6403b2db6f96a
[ "MIT" ]
3
2021-12-18T00:17:05.000Z
2021-12-18T00:17:20.000Z
src/main/java/com/unascribed/legacycustompublish/LegacyCustomPublish.java
unascribed/LegacyCustomPublish
baf48db55de527930678a0fc95a6403b2db6f96a
[ "MIT" ]
null
null
null
src/main/java/com/unascribed/legacycustompublish/LegacyCustomPublish.java
unascribed/LegacyCustomPublish
baf48db55de527930678a0fc95a6403b2db6f96a
[ "MIT" ]
null
null
null
26.058824
81
0.785553
999,132
package com.unascribed.legacycustompublish; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLServerStartingEvent; @Mod(modid="legacycustompublish", name="Legacy Custom Publish", useMetadata=true) public class LegacyCustomPublish { @Mod.ServerStarting public void onServerStarting(FMLServerStartingEvent e) { if (!e.getServer().isDedicatedServer()) { e.registerServerCommand(new CustomPublishCommand()); } } }
923a3d4aaf77a7ff6f9fa59a27106068e3b9ed59
384
java
Java
src/test/java/de/team33/test/provision/vX/LazySupplyCTest.java
akk-team33/lib-provision
543a9e2abc95307d108277cdde4a564b3e6f9174
[ "Apache-2.0" ]
null
null
null
src/test/java/de/team33/test/provision/vX/LazySupplyCTest.java
akk-team33/lib-provision
543a9e2abc95307d108277cdde4a564b3e6f9174
[ "Apache-2.0" ]
null
null
null
src/test/java/de/team33/test/provision/vX/LazySupplyCTest.java
akk-team33/lib-provision
543a9e2abc95307d108277cdde4a564b3e6f9174
[ "Apache-2.0" ]
null
null
null
25.6
83
0.763021
999,133
package de.team33.test.provision.vX; import de.team33.libs.provision.vX.LazySupply; import de.team33.libs.provision.vX.LazySupplyC; public class LazySupplyCTest extends LazySupplyTestBase { private final LazySupply<LazySupplyTestBase> subject = new LazySupplyC<>(this); @Override protected LazySupply<LazySupplyTestBase> getSubject() { return subject; } }
923a3ea6da046086ab8d8dd786b894f90336a3e2
962
java
Java
src/test/java/com/mattworzala/canary/internal/server/sandbox/testbuilder/TestTestBuilderController.java
mworzala/canary
d3684866876716367aecd10f9504e68a19b6c624
[ "MIT" ]
3
2021-11-21T21:39:24.000Z
2022-01-10T17:17:39.000Z
src/test/java/com/mattworzala/canary/internal/server/sandbox/testbuilder/TestTestBuilderController.java
mworzala/canary
d3684866876716367aecd10f9504e68a19b6c624
[ "MIT" ]
9
2021-09-14T21:14:36.000Z
2021-12-08T17:48:14.000Z
src/test/java/com/mattworzala/canary/internal/server/sandbox/testbuilder/TestTestBuilderController.java
mworzala/canary
d3684866876716367aecd10f9504e68a19b6c624
[ "MIT" ]
2
2022-02-23T18:57:50.000Z
2022-03-22T16:40:46.000Z
29.151515
102
0.732848
999,134
package com.mattworzala.canary.internal.server.sandbox.testbuilder; import net.minestom.server.MinecraftServer; import net.minestom.server.coordinate.Vec; import net.minestom.server.entity.Player; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; public class TestTestBuilderController { // @BeforeEach // public void init() { // MockitoAnnotations.openMocks(this); // } // @Test // public void testAddPlayer() { // MinecraftServer.init(); // TestBuilderController controller = new TestBuilderController("test-builder"); // // Player player = Mockito.mock(Player.class); // controller.addPlayer(player); // Mockito.verify(player).setInstance(eq(controller.getTestBuilderInstance()), any(Vec.class)); // } }
923a3fd0ddaa1e0cf6f672659e54b6c85467be65
12,472
java
Java
src/main/java/com/github/rysefoxx/fakenpc/other/RyseFakeEntity.java
Rysefoxx/PotPvP-RyseFakeEntity
164389007dcef257ddbec4b9601058100bfeb36c
[ "MIT" ]
1
2022-02-25T17:36:40.000Z
2022-02-25T17:36:40.000Z
src/main/java/com/github/rysefoxx/fakenpc/other/RyseFakeEntity.java
Rysefoxx/PotPvP-RyseFakeEntity
164389007dcef257ddbec4b9601058100bfeb36c
[ "MIT" ]
null
null
null
src/main/java/com/github/rysefoxx/fakenpc/other/RyseFakeEntity.java
Rysefoxx/PotPvP-RyseFakeEntity
164389007dcef257ddbec4b9601058100bfeb36c
[ "MIT" ]
null
null
null
39.468354
174
0.686899
999,135
/* * MIT License * * Copyright (c) 2021. Rysefoxx * * 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.github.rysefoxx.fakenpc.other; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.*; import com.github.rysefoxx.fakenpc.FakeNpc; import com.github.rysefoxx.fakenpc.util.*; import lombok.Getter; import lombok.Setter; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.mineskin.MineskinClient; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; /** * @author Rysefoxx | Rysefoxx#6772 * @since 12/23/2021 */ @Getter @Setter public class RyseFakeEntity { private final FakeNpc plugin; private final String name; private final int id; private final UUID uuid; private final int armorStandId; private String url; private String displayName; private Location location; private boolean toggled; private EntityType entityType; private boolean headRotation; private String value; private String signature; public RyseFakeEntity(@NotNull FakeNpc plugin, @NotNull String name, @NotNull EntityType entityType) { this.plugin = plugin; this.name = name; this.displayName = "§f" + this.name; this.id = Maths.randomInteger(1, Integer.MAX_VALUE); this.armorStandId = this.id + 1; this.entityType = entityType; this.location = WorldUtils.getWorldSpawn(); this.toggled = true; this.headRotation = true; this.uuid = UUID.randomUUID(); this.url = ""; this.value = ""; this.signature = ""; } public void showAll() { Bukkit.getOnlinePlayers().forEach(this::show); } public void hideAll() { Bukkit.getOnlinePlayers().forEach(this::hide); } public void updateEntityType(@NotNull EntityType entityType) { hideAll(); setEntityType(entityType); showAll(); } public void updateDisplayName(@NotNull String displayName) { hideAll(); setDisplayName(displayName); showAll(); } public void updateLocation(@NotNull Player player) { hideAll(); Location location = player.getLocation().clone(); location.setX(location.getBlockX() + 0.5); location.setZ(location.getBlockZ() + 0.5); setLocation(location); showAll(); } public void updateLocation(@NotNull Location location) { hideAll(); setLocation(location); showAll(); } public void hide(@NotNull Player player) { PacketContainer mainEntity = this.plugin.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY); PacketContainer armorStand = this.plugin.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY); if (Utils.isServerVersion("v1_17_R1")) { mainEntity.getIntegers().writeSafely(0, this.id); armorStand.getIntegers().writeSafely(0, this.armorStandId); } else { mainEntity.getIntegers().writeSafely(0, 1); mainEntity.getIntegerArrays().writeSafely(0, new int[]{this.id}); armorStand.getIntegers().writeSafely(0, 1); armorStand.getIntegerArrays().writeSafely(0, new int[]{this.armorStandId}); } try { this.plugin.getProtocolManager().sendServerPacket(player, mainEntity); this.plugin.getProtocolManager().sendServerPacket(player, armorStand); } catch (InvocationTargetException e) { e.printStackTrace(); } } public void show(@NotNull Player player) { loadMainEntity(player); editHeadRotation(player); loadArmorStand(player); attach(player); loadArmorStandLine(player); } private void loadMainEntity(@NotNull Player player) { if (this.entityType == EntityType.PLAYER && this.value != null && this.signature != null) { getPlayerInfo().sendPacket(player); getPlayerPosition().sendPacket(player); return; } PacketContainer packet = this.plugin.getProtocolManager().createPacket(PacketType.Play.Server.SPAWN_ENTITY); packet.getIntegers().write(0, this.id); packet.getUUIDs().write(0, UUID.randomUUID()); packet.getEntityTypeModifier().write(0, this.entityType); packet.getDoubles().write(0, this.location.getX()); packet.getDoubles().write(1, this.location.getY()); packet.getDoubles().write(2, this.location.getZ()); packet.getIntegers().write(3, 0); try { this.plugin.getProtocolManager().sendServerPacket(player, packet); } catch (InvocationTargetException e) { e.printStackTrace(); } } private @NotNull WrapperPlayServerNamedEntitySpawn getPlayerPosition() { WrapperPlayServerNamedEntitySpawn entityWrapper = new WrapperPlayServerNamedEntitySpawn(); entityWrapper.setEntityID(this.id); entityWrapper.setPlayerUUID(this.uuid); entityWrapper.setPosition(this.location.toVector()); return entityWrapper; } private @NotNull WrapperPlayServerPlayerInfo getPlayerInfo() { WrapperPlayServerPlayerInfo playerInfo = new WrapperPlayServerPlayerInfo(); playerInfo.setAction(EnumWrappers.PlayerInfoAction.ADD_PLAYER); WrappedGameProfile profile = new WrappedGameProfile(this.uuid, ""); profile.getProperties().put("textures", WrappedSignedProperty.fromValues("textures", this.value, this.signature)); PlayerInfoData data = new PlayerInfoData(profile, 1, EnumWrappers.NativeGameMode.CREATIVE, null); List<PlayerInfoData> dataList = new ArrayList<>(); dataList.add(data); playerInfo.setData(dataList); return playerInfo; } public void editHeadRotation(@NotNull Player player) { int yaw = (int) (this.location.getYaw() * 256.0F / 360.0F); int pitch = (int) (this.location.getPitch() * 256.0F / 360.0F); PacketContainer headPacket = this.plugin.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_HEAD_ROTATION); headPacket.getIntegers().write(0, this.id); headPacket.getBytes().write(0, (byte) yaw); PacketContainer headVerticalPacket = this.plugin.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_LOOK); headVerticalPacket.getIntegers().write(0, this.id); headVerticalPacket.getBytes().write(0, (byte) yaw); headVerticalPacket.getBytes().write(1, (byte) pitch); try { this.plugin.getProtocolManager().sendServerPacket(player, headPacket); this.plugin.getProtocolManager().sendServerPacket(player, headVerticalPacket); } catch (InvocationTargetException e) { e.printStackTrace(); } } public void editHeadRotationBasedPlayerLocation(@NotNull Player player) { Location location = player.getLocation().setDirection(player.getLocation().subtract(this.location).toVector()); int yaw = (int) (location.getYaw() * 256.0F / 360.0F); int pitch = (int) (location.getPitch() * 256.0F / 360.0F); PacketContainer headPacket = this.plugin.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_HEAD_ROTATION); headPacket.getIntegers().write(0, this.id); headPacket.getBytes().write(0, (byte) yaw); PacketContainer headVerticalPacket = this.plugin.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_LOOK); headVerticalPacket.getIntegers().write(0, this.id); headVerticalPacket.getBytes().write(0, (byte) yaw); headVerticalPacket.getBytes().write(1, (byte) pitch); try { this.plugin.getProtocolManager().sendServerPacket(player, headPacket); this.plugin.getProtocolManager().sendServerPacket(player, headVerticalPacket); } catch (InvocationTargetException e) { e.printStackTrace(); } } private void loadArmorStand(@NotNull Player player) { PacketContainer armorStandPacket = this.plugin.getProtocolManager().createPacket(PacketType.Play.Server.SPAWN_ENTITY); armorStandPacket.getIntegers().write(0, this.armorStandId); armorStandPacket.getUUIDs().write(0, UUID.randomUUID()); armorStandPacket.getEntityTypeModifier().write(0, EntityType.ARMOR_STAND); armorStandPacket.getDoubles().write(0, this.location.getX()); armorStandPacket.getDoubles().write(1, this.location.getY()); armorStandPacket.getDoubles().write(2, this.location.getZ()); armorStandPacket.getIntegers().write(3, 0); try { this.plugin.getProtocolManager().sendServerPacket(player, armorStandPacket); } catch (InvocationTargetException e) { e.printStackTrace(); } } private void attach(@NotNull Player player) { PacketContainer entityMountPacket = this.plugin.getProtocolManager().createPacket(PacketType.Play.Server.ATTACH_ENTITY); entityMountPacket.getIntegers().write(0, this.armorStandId); entityMountPacket.getIntegers().write(1, this.id); try { this.plugin.getProtocolManager().sendServerPacket(player, entityMountPacket); } catch (InvocationTargetException e) { e.printStackTrace(); } } private void loadArmorStandLine(@NotNull Player player) { WrappedDataWatcher watcher = new WrappedDataWatcher(); WrappedDataWatcher.Serializer booleanSerializer = WrappedDataWatcher.Registry.get(Boolean.class); Optional<?> opt = Optional.of(WrappedChatComponent.fromChatMessage(Utils.colorizedMessage(this.displayName != null ? this.displayName : "UNDEFINED"))[0].getHandle()); WrappedDataWatcher.WrappedDataWatcherObject isInvisibleIndex = new WrappedDataWatcher.WrappedDataWatcherObject(0, WrappedDataWatcher.Registry.get(Byte.class)); watcher.setObject(isInvisibleIndex, (byte) 0x20); watcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true)), opt); watcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, booleanSerializer), true); PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); packet.getIntegers().write(0, this.armorStandId); packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); try { this.plugin.getProtocolManager().sendServerPacket(player, packet); } catch (InvocationTargetException e) { e.printStackTrace(); } } public void updateSkin() { if (this.url.isEmpty()) return; MineskinClient client = new MineskinClient("MineSkin-JavaClient"); client.generateUrl(this.url).thenAccept(skin -> { String signature = skin.data.texture.signature; String value = skin.data.texture.value; hideAll(); this.signature = signature; this.value = value; showAll(); }); } }
923a405955f6065fbde7cf23778761268791e977
2,202
java
Java
random-beans/src/test/java/io/github/benas/randombeans/beans/TestData.java
rbenitez22/random-beans
09d84bfda927c05fdaaab45cfc03ed1a22d06742
[ "MIT" ]
6
2020-08-04T13:29:13.000Z
2022-02-14T03:37:14.000Z
random-beans/src/test/java/io/github/benas/randombeans/beans/TestData.java
fishwasser/random-beans
87ba0e678b32e047c367c7d2d6b9c43064f5edea
[ "MIT" ]
null
null
null
random-beans/src/test/java/io/github/benas/randombeans/beans/TestData.java
fishwasser/random-beans
87ba0e678b32e047c367c7d2d6b9c43064f5edea
[ "MIT" ]
2
2020-11-12T18:56:18.000Z
2021-11-20T01:52:53.000Z
38.842105
82
0.714544
999,136
/** * The MIT License * * Copyright (c) 2017, Mahmoud Ben Hassine (lyhxr@example.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.github.benas.randombeans.beans; import io.github.benas.randombeans.annotation.Randomizer; import io.github.benas.randombeans.annotation.RandomizerArgument; import io.github.benas.randombeans.randomizers.range.DateRangeRandomizer; import io.github.benas.randombeans.randomizers.range.IntegerRangeRandomizer; import java.util.Date; public class TestData { public TestData() { } @Randomizer(value = DateRangeRandomizer.class, args = { @RandomizerArgument(value = "2016-01-10 00:00:00", type = Date.class), @RandomizerArgument(value = "2016-01-30 23:59:59", type = Date.class) }) private Date date; @Randomizer(value = IntegerRangeRandomizer.class, args = { @RandomizerArgument(value = "200", type = Integer.class), @RandomizerArgument(value = "500", type = Integer.class) }) private int price; public Date getDate() { return date; } public int getPrice() { return price; } }
923a41215e979af928cad7acd7ff221c2459dc98
968
java
Java
electric/src/main/java/com/example/administrator/powerpayment/activity/mvp/contract/payment/PaymentMainContract.java
fengxiaozheng/electric
8ba056344e73a1f37eba63e6587d0b884ef8fa63
[ "Apache-2.0" ]
null
null
null
electric/src/main/java/com/example/administrator/powerpayment/activity/mvp/contract/payment/PaymentMainContract.java
fengxiaozheng/electric
8ba056344e73a1f37eba63e6587d0b884ef8fa63
[ "Apache-2.0" ]
null
null
null
electric/src/main/java/com/example/administrator/powerpayment/activity/mvp/contract/payment/PaymentMainContract.java
fengxiaozheng/electric
8ba056344e73a1f37eba63e6587d0b884ef8fa63
[ "Apache-2.0" ]
null
null
null
30.25
102
0.780992
999,137
package com.example.administrator.powerpayment.activity.mvp.contract.payment; import android.app.Activity; import com.jess.arms.mvp.IModel; import com.jess.arms.mvp.IView; import com.mingle.widget.LoadingView; import com.example.administrator.powerpayment.activity.mvp.model.entity.paymentEntity.PaymentMainRes; import com.example.administrator.powerpayment.activity.mvp.model.entity.paymentEntity.RewriteInputRes; import com.example.administrator.powerpayment.activity.mvp.ui.adapter.MainFragmentClickListener; import io.reactivex.Observable; /** * Created by fengxiaozheng * on 2018/6/26. */ public interface PaymentMainContract { interface View extends IView { MainFragmentClickListener getListener(); LoadingView getLoadingView(); Activity getActivity(); } interface Model extends IModel { Observable<PaymentMainRes> getPaymentMainFragmentItem(); Observable<RewriteInputRes> getTermPassword(); } }
923a41ca55cad6b892bbee7cc6f7ae2f9214bee5
14,120
java
Java
jdbreport-rt/src/main/java/jdbreport/grid/ReportPrintable.java
andreikh/jdbreport
bbf699dbc46534f745386de16d6c258488384490
[ "Apache-2.0" ]
null
null
null
jdbreport-rt/src/main/java/jdbreport/grid/ReportPrintable.java
andreikh/jdbreport
bbf699dbc46534f745386de16d6c258488384490
[ "Apache-2.0" ]
1
2021-09-14T13:07:42.000Z
2021-09-14T13:07:42.000Z
jdbreport-rt/src/main/java/jdbreport/grid/ReportPrintable.java
andreikh/jdbreport
bbf699dbc46534f745386de16d6c258488384490
[ "Apache-2.0" ]
null
null
null
23.338843
93
0.659136
999,138
/* * JDBReport Generator * * Copyright (C) 2006-2014 Andrey Kholmanskih * * 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 jdbreport.grid; import java.awt.ComponentOrientation; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.swing.JTable; import javax.swing.JTable.PrintMode; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import jdbreport.model.DetailGroup; import jdbreport.model.Group; import jdbreport.model.ReportModel; import jdbreport.model.TableRow; import jdbreport.model.TableRowModel; import jdbreport.util.GraphicUtil; /** * @version 3.0 13.12.2014 * @author Andrey Kholmanskih * */ public class ReportPrintable implements Printable { /** The table to print. */ private JReportGrid table; /** For quick reference to the table's column model. */ private TableColumnModel colModel; /** To save multiple calculations of total column width. */ private int totalColWidth; /** The printing mode of this printable. */ private JTable.PrintMode printMode; /** The most recent page index asked to print. */ private int last = -1; /** The next row to print. */ private int row = 0; /** The next column to print. */ private int col = 0; /** Used to store an area of the table to be printed. */ private final Rectangle clip = new Rectangle(0, 0, 0, 0); /** Used to store an area of the page header to be printed. */ private final Rectangle hclip = new Rectangle(0, 0, 0, 0); /** Used to store an area of the page footer to be printed. */ private final Rectangle fclip = new Rectangle(0, 0, 0, 0); /** Saves the creation of multiple rectangles. */ private final Rectangle tempRect = new Rectangle(0, 0, 0, 0); private Map<Integer, PageClip> pageClips = null; private int endCol; private int currentCol; private int endRow; private int currentRow; private ReportModel tableModel; private boolean ltr; public ReportPrintable(JReportGrid table, JTable.PrintMode printMode) { this(table, printMode, false); } /** * Creates a new <code>TablePrintable<code> for the given * <code>JTable</code>. Header and footer text can be specified using the * two <code>MessageFormat</code> parameters. When called upon to provide a * String, each format is given the current page number. * * @param table * the table to print * @param printMode * the printing mode for this printable * @param isPreview * - if true, report will be preview * @throws IllegalArgumentException * if passed an invalid print mode */ public ReportPrintable(JReportGrid table, JTable.PrintMode printMode, boolean isPreview) { this.table = table; this.printMode = printMode; ltr = table.getComponentOrientation().isLeftToRight(); tableModel = table.getReportModel(); if (isPreview) { pageClips = new HashMap<>(); } init(); } public ReportPrintable(ReportModel model) { ltr = ComponentOrientation.getOrientation(Locale.getDefault()) .isLeftToRight(); tableModel = model; this.printMode = tableModel.getReportPage().isShrinkWidth() ? PrintMode.FIT_WIDTH : PrintMode.NORMAL; pageClips = new HashMap<>(); init(); } private void init() { /* For quick reference to the page header. */ Group pageHeader = tableModel.getRowModel().getRootGroup() .getGroup(Group.ROW_PAGE_HEADER); if (pageHeader != null && pageHeader.getChildCount() == 0) pageHeader = null; /* For quick reference to the page footer. */ Group pageFooter = tableModel.getRowModel().getRootGroup() .getGroup(Group.ROW_PAGE_FOOTER); if (pageFooter != null && pageFooter.getChildCount() == 0) pageFooter = null; colModel = tableModel.getColumnModel(); totalColWidth = colModel.getTotalColumnWidth(); if (pageHeader != null) { hclip.height = pageHeader.getHeight(); } if (pageFooter != null) { fclip.height = pageFooter.getHeight(); } } public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { boolean showGrid = table.isShowGrid(); double oldScaleX = GraphicUtil.getScaleX(); double oldScaleY = GraphicUtil.getScaleY(); try { table.setShowGrid(false); GraphicUtil.setScaleX(1); GraphicUtil.setScaleY(1); final int imgWidth = (int) pageFormat.getImageableWidth(); final int imgHeight = (int) pageFormat.getImageableHeight(); if (imgWidth <= 0) { throw new PrinterException( Messages.getString("ReportPrintable.0")); //$NON-NLS-1$ } if (imgHeight <= 0) { throw new PrinterException( Messages.getString("ReportPrintable.1")); //$NON-NLS-1$ } double sf = getScaleFactor(imgWidth); int scaledWidth = (int) (imgWidth / sf); int scaledHeight = (int) (imgHeight / sf); if (pageClips != null && pageClips.containsKey(pageIndex)) { PageClip pc = pageClips.get(pageIndex); col = pc.rightCol; row = pc.bottomRow; clip.x = pc.clip.x; clip.y = pc.clip.y; clip.height = pc.clip.height; clip.width = pc.clip.width; } else { if (tableModel.isPrintLeftToRight()) { if (!fromLeftToRight(scaledWidth, scaledHeight, pageIndex)) { return NO_SUCH_PAGE; } } else { if (!fromTopToDown(scaledWidth, scaledHeight, pageIndex)) { return NO_SUCH_PAGE; } } } Graphics2D g2d = (Graphics2D) graphics; int x = (int) pageFormat.getImageableX(); int y = (int) pageFormat.getImageableY(); g2d.translate(x, y); tempRect.x = 0; tempRect.y = 0; tempRect.width = imgWidth; tempRect.height = imgHeight; g2d.clip(tempRect); if (sf != 1.0D) { g2d.scale(sf, sf); } AffineTransform oldTrans = g2d.getTransform(); Shape oldClip = g2d.getClip(); table.setState(JReportGrid.PRINT); try { g2d.translate(-clip.x + 1, -clip.y + 1); g2d.clip(clip); table.print(g2d); } finally { table.setState(JReportGrid.PAINT); g2d.setTransform(oldTrans); g2d.setClip(oldClip); } return PAGE_EXISTS; } finally { GraphicUtil.setScaleX(oldScaleX); GraphicUtil.setScaleY(oldScaleY); table.setShowGrid(showGrid); } } private boolean fromTopToDown(int scaledWidth, int scaledHeight, int pageIndex) { while (last < pageIndex) { if (row == 0 && col >= colModel.getColumnCount()) { return false; } last++; findNextTDClip(scaledWidth, scaledHeight, last); } return true; } private boolean fromLeftToRight(int scaledWidth, int scaledHeight, int pageIndex) { while (last < pageIndex) { if (col == 0 && row >= tableModel.getRowCount()) { return false; } last++; findNextLRClip(scaledWidth, scaledHeight, last); } return true; } private double getScaleFactor(final int imgWidth) { double sf = 1.0D; if (printMode == JTable.PrintMode.FIT_WIDTH && totalColWidth > imgWidth) { assert imgWidth > 0; assert totalColWidth > 1; sf = (double) imgWidth / (double) totalColWidth; assert sf > 0; } return sf; } /** * Calculate the area of the table to be printed for the next page. This * should only be called if there are rows and columns left to print. * * To avoid an infinite loop in printing, this will always put at least one * cell on each page. * * @param pw * the width of the area to print in * @param ph * the height of the area to print in */ private void findNextTDClip(int pw, int ph, int pageIndex) { if (row == 0) { clip.y = 0; clip.height = 0; currentCol = endCol; if (ltr) { clip.x += clip.width; } else clip.x -= clip.width; } col = currentCol; int frow = row; int fcol = col; if (col == 0) { if (ltr) { clip.x = 0; } else { clip.x = totalColWidth; } clip.width = 0; } clip.y += clip.height; clip.height = 0; int rowCount = tableModel.getRowCount(); int rowHeight = tableModel.getRowHeight(row); do { clip.height += rowHeight; if (++row >= rowCount) { row = 0; break; } if (isEndPage()) break; rowHeight = tableModel.getRowHeight(row); } while (clip.height + rowHeight <= ph); if (printMode == JTable.PrintMode.FIT_WIDTH) { clip.x = 0; clip.width = totalColWidth; col = colModel.getColumnCount(); return; } clip.width = 0; int colCount = colModel.getColumnCount(); TableColumn column = colModel.getColumn(col); double colWidth = column.getWidth(); do { clip.width += colWidth; if (++col >= colCount) { break; } if (tableModel.isColumnBreak(col - 1)) { break; } colWidth = colModel.getColumn(col).getWidth(); } while (clip.width + colWidth <= pw); endCol = col; if (pageClips != null) { pageClips.put(pageIndex, new PageClip(frow, fcol, row == 0 ? rowCount : row, col, clip)); } } /** * Calculate the area of the table to be printed for the next page. This * should only be called if there are rows and columns left to print. * * To avoid an infinite loop in printing, this will always put at least one * cell on each page. * * @param pw * the width of the area to print in * @param ph * the height of the area to print in */ private void findNextLRClip(int pw, int ph, int pageIndex) { if (col == 0) { currentRow = endRow; if (ltr) { clip.x = 0; } else { clip.x = totalColWidth; } clip.width = 0; clip.y += clip.height; } row = currentRow; int frow = row; int fcol = col; if (row == 0) { clip.y = 0; } clip.height = 0; int rowCount = tableModel.getRowCount(); int rowHeight = tableModel.getRowHeight(row); do { clip.height += rowHeight; if (++row >= rowCount) { break; } if (isEndPage()) break; rowHeight = tableModel.getRowHeight(row); } while (clip.height + rowHeight <= ph); if (printMode == JTable.PrintMode.FIT_WIDTH) { clip.x = 0; clip.width = totalColWidth; col = colModel.getColumnCount(); return; } if (ltr) { clip.x += clip.width; } else clip.x -= clip.width; clip.width = 0; int colCount = colModel.getColumnCount(); TableColumn column = colModel.getColumn(col); double colWidth = column.getWidth(); do { clip.width += colWidth; if (++col >= colCount) { col = 0; break; } if (tableModel.isColumnBreak(col - 1)) { break; } colWidth = colModel.getColumn(col).getWidth(); } while (clip.width + colWidth <= pw); endRow = row; if (pageClips != null) { pageClips.put(pageIndex, new PageClip(frow, fcol, row, col == 0 ? colCount : col, clip)); } } private boolean isEndPage() { TableRowModel rowModel = tableModel.getRowModel(); TableRow tableRow = rowModel.getRow(row - 1); if (tableRow.isPageBreak()) { return true; } if (rowModel.isCanUpdatePages()) { TableRow tableRow0 = rowModel.getRow(row); Group group_1 = rowModel.getGroup(row - 1); Group group = rowModel.getGroup(row); if (group.getType() == Group.ROW_PAGE_HEADER && group_1.getType() != Group.ROW_PAGE_HEADER && group_1.getType() != Group.ROW_TITLE && !tableRow.isPageHeader() && tableRow0.isPageHeader()) { return true; } if (group.getType() == Group.ROW_GROUP_HEADER && ((DetailGroup) group.getParent()).isRepeateHeader() && group_1.getParent() == group.getParent() && !tableRow.isPageHeader() && tableRow0.isPageHeader()) { return true; } if (group_1.getType() == Group.ROW_PAGE_FOOTER && group.getType() != Group.ROW_FOOTER && group.getType() != Group.ROW_PAGE_FOOTER) { return true; } } return false; } public int calcCountPage(PageFormat pageFormat) { double oldScaleX = GraphicUtil.getScaleX(); double oldScaleY = GraphicUtil.getScaleY(); int pageIndex = 0; try { GraphicUtil.setScaleX(1); GraphicUtil.setScaleY(1); final int imgWidth = (int) pageFormat.getImageableWidth(); final int imgHeight = (int) pageFormat.getImageableHeight(); double sf = getScaleFactor(imgWidth); int scaledWidth = (int) (imgWidth / sf); int scaledHeight = (int) (imgHeight / sf); if (tableModel.isPrintLeftToRight()) { while (true) { if (col == 0 && row >= tableModel.getRowCount()) { return pageIndex; } findNextLRClip(scaledWidth, scaledHeight, pageIndex); pageIndex++; } } else { while (true) { if (row == 0 && col >= colModel.getColumnCount()) { return pageIndex; } findNextTDClip(scaledWidth, scaledHeight, pageIndex); pageIndex++; } } } finally { GraphicUtil.setScaleX(oldScaleX); GraphicUtil.setScaleY(oldScaleY); } } public Map<Integer, PageClip> getPageClips() { return pageClips; } public static class PageClip { int bottomRow; int rightCol; int topRow; int leftCol; Rectangle clip; public PageClip(int frow, int fcol, int row, int col, Rectangle clip) { this.topRow = frow; this.leftCol = fcol; this.bottomRow = row; this.rightCol = col; this.clip = (Rectangle) clip.clone(); } public int getTopRow() { return topRow; } public int getLeftCol() { return leftCol; } public int getBottomRow() { return bottomRow; } public int getRightCol() { return rightCol; } } }
923a42d2b4b1f27a4e61e4b6c7b5fcf79c502370
234
java
Java
vertx-gaia/vertx-co/src/main/java/io/vertx/zero/eon/Tpl.java
linsirui/vertx-zero
a08058ac3552574703e0c9c4f81e0ffb5f62dbfb
[ "Apache-2.0" ]
null
null
null
vertx-gaia/vertx-co/src/main/java/io/vertx/zero/eon/Tpl.java
linsirui/vertx-zero
a08058ac3552574703e0c9c4f81e0ffb5f62dbfb
[ "Apache-2.0" ]
null
null
null
vertx-gaia/vertx-co/src/main/java/io/vertx/zero/eon/Tpl.java
linsirui/vertx-zero
a08058ac3552574703e0c9c4f81e0ffb5f62dbfb
[ "Apache-2.0" ]
null
null
null
18
67
0.5
999,139
package io.vertx.zero.eon; public interface Tpl { /** * */ String ZERO_ERROR = "[ERR{0}] ({1}) ZeroException occus: {2}."; /** * */ String WEB_ERROR = "[ERR{0}] ({1}) Web Exception occus: {2}."; }
923a42e6b7e769eb1cd879996bf6a2af8dbf113a
6,577
java
Java
sdk/mysql/azure-resourcemanager-mysql/src/main/java/com/azure/resourcemanager/mysql/fluent/models/RecommendationActionProperties.java
liukun2634/azure-sdk-for-java
a42ba097eef284333c9befba180eea3cfed41312
[ "MIT" ]
1
2022-02-21T12:26:20.000Z
2022-02-21T12:26:20.000Z
sdk/mysql/azure-resourcemanager-mysql/src/main/java/com/azure/resourcemanager/mysql/fluent/models/RecommendationActionProperties.java
liukun2634/azure-sdk-for-java
a42ba097eef284333c9befba180eea3cfed41312
[ "MIT" ]
null
null
null
sdk/mysql/azure-resourcemanager-mysql/src/main/java/com/azure/resourcemanager/mysql/fluent/models/RecommendationActionProperties.java
liukun2634/azure-sdk-for-java
a42ba097eef284333c9befba180eea3cfed41312
[ "MIT" ]
null
null
null
27.751055
107
0.667326
999,140
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.mysql.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; import java.util.Map; /** The properties of a recommendation action. */ @Fluent public final class RecommendationActionProperties { @JsonIgnore private final ClientLogger logger = new ClientLogger(RecommendationActionProperties.class); /* * Advisor name. */ @JsonProperty(value = "advisorName") private String advisorName; /* * Recommendation action session identifier. */ @JsonProperty(value = "sessionId") private String sessionId; /* * Recommendation action identifier. */ @JsonProperty(value = "actionId") private Integer actionId; /* * Recommendation action creation time. */ @JsonProperty(value = "createdTime") private OffsetDateTime createdTime; /* * Recommendation action expiration time. */ @JsonProperty(value = "expirationTime") private OffsetDateTime expirationTime; /* * Recommendation action reason. */ @JsonProperty(value = "reason") private String reason; /* * Recommendation action type. */ @JsonProperty(value = "recommendationType") private String recommendationType; /* * Recommendation action details. */ @JsonProperty(value = "details") @JsonInclude(value = JsonInclude.Include.NON_NULL, content = JsonInclude.Include.ALWAYS) private Map<String, String> details; /** * Get the advisorName property: Advisor name. * * @return the advisorName value. */ public String advisorName() { return this.advisorName; } /** * Set the advisorName property: Advisor name. * * @param advisorName the advisorName value to set. * @return the RecommendationActionProperties object itself. */ public RecommendationActionProperties withAdvisorName(String advisorName) { this.advisorName = advisorName; return this; } /** * Get the sessionId property: Recommendation action session identifier. * * @return the sessionId value. */ public String sessionId() { return this.sessionId; } /** * Set the sessionId property: Recommendation action session identifier. * * @param sessionId the sessionId value to set. * @return the RecommendationActionProperties object itself. */ public RecommendationActionProperties withSessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Get the actionId property: Recommendation action identifier. * * @return the actionId value. */ public Integer actionId() { return this.actionId; } /** * Set the actionId property: Recommendation action identifier. * * @param actionId the actionId value to set. * @return the RecommendationActionProperties object itself. */ public RecommendationActionProperties withActionId(Integer actionId) { this.actionId = actionId; return this; } /** * Get the createdTime property: Recommendation action creation time. * * @return the createdTime value. */ public OffsetDateTime createdTime() { return this.createdTime; } /** * Set the createdTime property: Recommendation action creation time. * * @param createdTime the createdTime value to set. * @return the RecommendationActionProperties object itself. */ public RecommendationActionProperties withCreatedTime(OffsetDateTime createdTime) { this.createdTime = createdTime; return this; } /** * Get the expirationTime property: Recommendation action expiration time. * * @return the expirationTime value. */ public OffsetDateTime expirationTime() { return this.expirationTime; } /** * Set the expirationTime property: Recommendation action expiration time. * * @param expirationTime the expirationTime value to set. * @return the RecommendationActionProperties object itself. */ public RecommendationActionProperties withExpirationTime(OffsetDateTime expirationTime) { this.expirationTime = expirationTime; return this; } /** * Get the reason property: Recommendation action reason. * * @return the reason value. */ public String reason() { return this.reason; } /** * Set the reason property: Recommendation action reason. * * @param reason the reason value to set. * @return the RecommendationActionProperties object itself. */ public RecommendationActionProperties withReason(String reason) { this.reason = reason; return this; } /** * Get the recommendationType property: Recommendation action type. * * @return the recommendationType value. */ public String recommendationType() { return this.recommendationType; } /** * Set the recommendationType property: Recommendation action type. * * @param recommendationType the recommendationType value to set. * @return the RecommendationActionProperties object itself. */ public RecommendationActionProperties withRecommendationType(String recommendationType) { this.recommendationType = recommendationType; return this; } /** * Get the details property: Recommendation action details. * * @return the details value. */ public Map<String, String> details() { return this.details; } /** * Set the details property: Recommendation action details. * * @param details the details value to set. * @return the RecommendationActionProperties object itself. */ public RecommendationActionProperties withDetails(Map<String, String> details) { this.details = details; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
923a436754c5dd7249042de740784cdf115e9a5f
2,292
java
Java
proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/SharedProto.java
suraj-qlogic/java-dataproc
f63ddd1088cdc4c87c52f31f467f423b0f6df999
[ "Apache-2.0" ]
null
null
null
proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/SharedProto.java
suraj-qlogic/java-dataproc
f63ddd1088cdc4c87c52f31f467f423b0f6df999
[ "Apache-2.0" ]
null
null
null
proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/SharedProto.java
suraj-qlogic/java-dataproc
f63ddd1088cdc4c87c52f31f467f423b0f6df999
[ "Apache-2.0" ]
null
null
null
39.338983
100
0.717794
999,141
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataproc/v1/shared.proto package com.google.cloud.dataproc.v1; public final class SharedProto { private SharedProto() {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n%google/cloud/dataproc/v1/shared.proto\022" + "\030google.cloud.dataproc.v1\032\034google/api/an" + "notations.proto*|\n\tComponent\022\031\n\025COMPONEN" + "T_UNSPECIFIED\020\000\022\014\n\010ANACONDA\020\005\022\020\n\014HIVE_WE" + "BHCAT\020\003\022\013\n\007JUPYTER\020\001\022\n\n\006PRESTO\020\006\022\014\n\010ZEPP" + "ELIN\020\004\022\r\n\tZOOKEEPER\020\010Bo\n\034com.google.clou" + "dycjh@example.com" + "ang.org/genproto/googleapis/cloud/datapr" + "oc/v1;dataprocb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.AnnotationsProto.getDescriptor(), }); com.google.api.AnnotationsProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
923a438d6bb8af45e50800a9438c7b2d39cb92ed
1,785
java
Java
src/main/java/com/chess/backend/restController/objects/ExecutedMoveObject.java
ccd-course/chess_controller
b7100c348b0c89974791f7c8541ac2f04d92ecc2
[ "MIT" ]
3
2021-11-28T15:50:37.000Z
2021-12-09T21:16:57.000Z
src/main/java/com/chess/backend/restController/objects/ExecutedMoveObject.java
ccd-course/chess_backend
b7100c348b0c89974791f7c8541ac2f04d92ecc2
[ "MIT" ]
121
2021-11-27T09:43:14.000Z
2022-01-31T09:57:48.000Z
src/main/java/com/chess/backend/restController/objects/ExecutedMoveObject.java
ccd-course/chess_backend
b7100c348b0c89974791f7c8541ac2f04d92ecc2
[ "MIT" ]
null
null
null
29.262295
116
0.678431
999,142
package com.chess.backend.restController.objects; import com.chess.backend.restController.controller.ExecutedMoveController; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** * This class is received from the API-Call of the {@link ExecutedMoveController}. * * @author Hannes Stuetzer */ @Data public class ExecutedMoveObject { /** * the id of the current game. */ private int gameID; /** * the old position of the chess piece. */ private int[] previousPiecePosition; /** * the new position of the chess piece. */ private int[] newPiecePosition; public ExecutedMoveObject(int gameID, int[] previousPiecePosition, int[] newPiecePosition) { this.gameID = gameID; this.previousPiecePosition = previousPiecePosition; this.newPiecePosition = newPiecePosition; } @Schema(description = "Game ID", example = "2") public int getGameID() { return gameID; } public void setGameID(int gameID) { this.gameID = gameID; } @ArraySchema(schema = @Schema(description = "Piece position [x, y]", example = "0"), minItems = 2, maxItems = 2) public int[] getPreviousPiecePosition() { return previousPiecePosition; } public void setPreviousPiecePosition(int[] previousPiecePosition) { this.previousPiecePosition = previousPiecePosition; } @ArraySchema(schema = @Schema(description = "Piece position [x, y]", example = "0"), minItems = 2, maxItems = 2) public int[] getNewPiecePosition() { return newPiecePosition; } public void setNewPiecePosition(int[] newPiecePosition) { this.newPiecePosition = newPiecePosition; } }
923a4435ce6ae21876b88b308c540b18dc558bac
22,204
java
Java
gumshoe-probes/src/main/java/com/dell/gumshoe/network/IoTraceSelectorProvider.java
worstcase/gumshoe
0f480e1ca1d6f9eff06aaae2d7cd8c1c174469c6
[ "Apache-2.0" ]
171
2017-02-23T06:50:06.000Z
2021-11-15T08:11:28.000Z
gumshoe-probes/src/main/java/com/dell/gumshoe/network/IoTraceSelectorProvider.java
cybernetics/gumshoe
0f480e1ca1d6f9eff06aaae2d7cd8c1c174469c6
[ "Apache-2.0" ]
1
2017-05-29T07:50:59.000Z
2017-05-29T07:50:59.000Z
gumshoe-probes/src/main/java/com/dell/gumshoe/network/IoTraceSelectorProvider.java
cybernetics/gumshoe
0f480e1ca1d6f9eff06aaae2d7cd8c1c174469c6
[ "Apache-2.0" ]
66
2017-03-03T07:51:41.000Z
2021-09-18T02:46:42.000Z
42.212928
165
0.665916
999,143
package com.dell.gumshoe.network; import com.dell.gumshoe.hook.IoTraceHandler; import java.io.IOException; import java.lang.reflect.Method; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ProtocolFamily; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketOption; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.DatagramChannel; import java.nio.channels.FileChannel; import java.nio.channels.MembershipKey; import java.nio.channels.Pipe; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.spi.AbstractSelectableChannel; import java.nio.channels.spi.AbstractSelector; import java.nio.channels.spi.SelectorProvider; import java.util.Iterator; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; /** to support NIO monitoring, set system property: * <tt>java.nio.channels.spi.SelectorProvider</tt> * to the name of this class */ public class IoTraceSelectorProvider extends sun.nio.ch.SelectorProviderImpl { // if false, use wrapper; if true, leave unmonitored private static boolean usePlainServerSocketChannel = true; private static boolean usePlainSocketChannel = true; private static boolean usePlainDatagramChannel = true; public static void setSocketTraceEnabled(boolean enabled) { usePlainServerSocketChannel = false; usePlainSocketChannel = false; } public static boolean isSocketTraceEnabled() { if(usePlainServerSocketChannel!=usePlainSocketChannel) { throw new IllegalStateException("IoTraceSelectorProvider socket and ServerSocket are inconsistent"); } return usePlainServerSocketChannel; } public static void setDatagramTraceEnabled(boolean enabled) { usePlainDatagramChannel = false; } public static boolean isDatagramTraceEnabled() { return usePlainDatagramChannel; } private final SelectorProvider delegate; private final Method closeChannelMethod; private final Method closeSelectorMethod; private final Method configureBlockingMethod; private final Method registerMethod; public IoTraceSelectorProvider() throws Exception { // choose delegate that would have been used if gumshoe wasn't here final SelectorProvider providerAsService = getProviderAsService(); this.delegate = providerAsService==null ? sun.nio.ch.DefaultSelectorProvider.create() : providerAsService; closeChannelMethod = AbstractSelectableChannel.class.getDeclaredMethod("implCloseSelectableChannel"); closeChannelMethod.setAccessible(true); closeSelectorMethod = AbstractSelector.class.getDeclaredMethod("implCloseSelector"); closeSelectorMethod.setAccessible(true); configureBlockingMethod = AbstractSelectableChannel.class.getDeclaredMethod("implConfigureBlocking", Boolean.TYPE); configureBlockingMethod.setAccessible(true); registerMethod = AbstractSelector.class.getDeclaredMethod("register", AbstractSelectableChannel.class, Integer.TYPE, Object.class); registerMethod.setAccessible(true); } /** check service definitions from jars, if there is one and it isn't gumshoe * * adapted from SelectorProvider.loadProviderAsService jdk6 */ private static SelectorProvider getProviderAsService() { ServiceLoader<SelectorProvider> sl = ServiceLoader.load(SelectorProvider.class, ClassLoader.getSystemClassLoader()); Iterator<SelectorProvider> i = sl.iterator(); for (;;) { try { if( ! i.hasNext()) return null; SelectorProvider candidate = i.next(); if( ! (candidate instanceof IoTraceSelectorProvider)) { return candidate; } } catch (ServiceConfigurationError sce) { if (sce.getCause() instanceof SecurityException) { // Ignore the security exception, try the next provider continue; } throw sce; } } } ///// pass directly to delegate @Override public int hashCode() { return delegate.hashCode(); } @Override public boolean equals(Object obj) { return delegate.equals(obj); } @Override public Pipe openPipe() throws IOException { return delegate.openPipe(); } @Override public String toString() { return delegate.toString(); } ///// wrap value from delegate to call IoTrace private AbstractSelector wrap(AbstractSelector orig) { return orig instanceof Wrapper ? orig : new SelectorWrapper(orig); } private DatagramChannel wrap(DatagramChannel orig) { return(usePlainDatagramChannel || orig instanceof Wrapper) ? orig : new DatagramChannelWrapper(orig); } private ServerSocketChannel wrap(ServerSocketChannel orig) { return (usePlainServerSocketChannel || orig instanceof Wrapper) ? orig : new ServerSocketChannelWrapper(orig); } private SocketChannel wrap(SocketChannel orig) { return (usePlainSocketChannel || orig instanceof Wrapper) ? orig : new SocketChannelWrapper(orig); } private DatagramSocket wrap(DatagramSocket orig) { return orig; } private <T> T unwrap(T orig) { return (T) (orig instanceof Wrapper ? ((Wrapper)orig).unwrap() : orig); } ///// @Override public AbstractSelector openSelector() throws IOException { return wrap(delegate.openSelector()); } @Override public DatagramChannel openDatagramChannel() throws IOException { return wrap(delegate.openDatagramChannel()); } @Override public DatagramChannel openDatagramChannel(ProtocolFamily family) throws IOException { return wrap(delegate.openDatagramChannel(family)); } @Override public ServerSocketChannel openServerSocketChannel() throws IOException { return wrap(delegate.openServerSocketChannel()); } @Override public SocketChannel openSocketChannel() throws IOException { return wrap(delegate.openSocketChannel()); } @Override public Channel inheritedChannel() throws IOException { final Channel orig = delegate.inheritedChannel(); if(orig instanceof Wrapper) { return orig; } if(orig instanceof FileChannel) { return orig; } if(orig instanceof SocketChannel) { return wrap((SocketChannel)orig); } if(orig instanceof DatagramChannel) { return wrap((DatagramChannel)orig); } // gumshoe I/O reporting not (yet?) supported for pipes, sctpsocket, others... return orig; } ///// wrappers invoke IoTrace in situations where original class does not private interface Wrapper<T> { T unwrap(); } private void reflectCloseSelectableChannel(AbstractSelectableChannel target) throws IOException { try { closeChannelMethod.invoke(target); } catch (Exception e) { if(e instanceof IOException) { throw (IOException) e; } if(e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } if(e instanceof RuntimeException) { throw (RuntimeException) e; } if(e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException("exception invoking implCloseSelectableChannel " + target, e); } } private void reflectCloseSelector(AbstractSelector target) throws IOException { try { closeSelectorMethod.invoke(target); } catch (Exception e) { if(e instanceof IOException) { throw (IOException) e; } if(e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } if(e instanceof RuntimeException) { throw (RuntimeException) e; } if(e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException("exception invoking implCloseSelector " + target, e); } } private void reflectConfigureBlocking(AbstractSelectableChannel target, boolean arg) throws IOException { try { configureBlockingMethod.invoke(target, arg); } catch (Exception e) { if(e instanceof IOException) { throw (IOException) e; } if(e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } if(e instanceof RuntimeException) { throw (RuntimeException) e; } if(e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException("exception invoking implConfigureBlocking " + target, e); } } private SelectionKey reflectRegister(AbstractSelector target, AbstractSelectableChannel ch, int ops, Object att) { try { return (SelectionKey) registerMethod.invoke(target, ch, ops, att); } catch (Exception e) { if(e instanceof RuntimeException) { throw (RuntimeException) e; } if(e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException("exception invoking register " + target, e); } } /** wrap DatagramChannel * most calls are just passed directly to delegate * others wrap return value * others invoke IoTrace */ private class DatagramChannelWrapper extends DatagramChannel implements Wrapper<DatagramChannel> { private final DatagramChannel delegate; public DatagramChannelWrapper(DatagramChannel delegate) { super(IoTraceSelectorProvider.this); this.delegate = delegate; } public DatagramChannel unwrap() { return delegate; } ///// directly invoke delegate public int hashCode() { return delegate.hashCode(); } public SocketAddress getLocalAddress() throws IOException { return delegate.getLocalAddress(); } public boolean equals(Object obj) { return delegate.equals(obj); } public <T> T getOption(SocketOption<T> name) throws IOException { return delegate.getOption(name); } public Set<SocketOption<?>> supportedOptions() { return delegate.supportedOptions(); } public MembershipKey join(InetAddress group, NetworkInterface interf) throws IOException { return delegate.join(group, interf); } public MembershipKey join(InetAddress group, NetworkInterface interf, InetAddress source) throws IOException { return delegate.join(group, interf, source); } public boolean isConnected() { return delegate.isConnected(); } public String toString() { return delegate.toString(); } public SocketAddress getRemoteAddress() throws IOException { return delegate.getRemoteAddress(); } ///// invoke delegate using reflection protected void implCloseSelectableChannel() throws IOException { reflectCloseSelectableChannel(delegate); } protected void implConfigureBlocking(boolean block) throws IOException { reflectConfigureBlocking(delegate, block); } ///// factory should handle correct impl public DatagramSocket socket() { return wrap(delegate.socket()); } ///// wrap results public DatagramChannel bind(SocketAddress local) throws IOException { return wrap(delegate.bind(local)); } public <T> DatagramChannel setOption(SocketOption<T> name, T value) throws IOException { return wrap(delegate.setOption(name, value)); } public DatagramChannel connect(SocketAddress remote) throws IOException { return wrap(delegate.connect(remote)); } public DatagramChannel disconnect() throws IOException { return wrap(delegate.disconnect()); } ///// invoke IoTrace public SocketAddress receive(ByteBuffer dst) throws IOException { final int positionBefore = dst==null ? 0 : dst.position(); final Object context = IoTraceHandler.datagramReadBegin(); final SocketAddress address = delegate.receive(dst); if(address!=null) { final int bytes = dst.position() - positionBefore; IoTraceHandler.datagramReadEnd(context, address, bytes); } return address; } public int send(ByteBuffer src, SocketAddress address) throws IOException { final Object context = IoTraceHandler.datagramWriteBegin(); final int bytes = delegate.send(src, address); if(bytes>0) { IoTraceHandler.datagramWriteEnd(context, address, bytes); } return bytes; } public int read(ByteBuffer dst) throws IOException { final Object context = IoTraceHandler.datagramReadBegin(); final int bytes = delegate.read(dst); if(bytes>0) { IoTraceHandler.datagramReadEnd(context, getRemoteAddress(), bytes); } return bytes; } public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { final Object context = IoTraceHandler.datagramReadBegin(); final long bytes = delegate.read(dsts, offset, length); if(bytes>0) { IoTraceHandler.datagramReadEnd(context, getRemoteAddress(), bytes); } return bytes; } public int write(ByteBuffer src) throws IOException { final Object context = IoTraceHandler.datagramWriteBegin(); final int bytes = delegate.write(src); if(bytes>0) { IoTraceHandler.datagramWriteEnd(context, getRemoteAddress(), bytes); } return bytes; } public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { final Object context = IoTraceHandler.datagramWriteBegin(); final long bytes = delegate.write(srcs, offset, length); if(bytes>0) { IoTraceHandler.datagramWriteEnd(context, getRemoteAddress(), bytes); } return bytes; } } private class ServerSocketChannelWrapper extends ServerSocketChannel implements Wrapper<ServerSocketChannel> { private final ServerSocketChannel delegate; public ServerSocketChannelWrapper(ServerSocketChannel delegate) { super(IoTraceSelectorProvider.this); this.delegate = delegate; } public ServerSocketChannel unwrap() { return delegate; } ///// directly invoke delegate public int hashCode() { return delegate.hashCode(); } public SocketAddress getLocalAddress() throws IOException { return delegate.getLocalAddress(); } public boolean equals(Object obj) { return delegate.equals(obj); } public <T> T getOption(SocketOption<T> name) throws IOException { return delegate.getOption(name); } public Set<SocketOption<?>> supportedOptions() { return delegate.supportedOptions(); } public String toString() { return delegate.toString(); } ///// factory should handle correct impl public ServerSocket socket() { return delegate.socket(); } ///// invoke delegate using reflection protected void implCloseSelectableChannel() throws IOException { reflectCloseSelectableChannel(delegate); } protected void implConfigureBlocking(boolean block) throws IOException { reflectConfigureBlocking(delegate, block); } ///// wrap results public ServerSocketChannel bind(SocketAddress local, int backlog) throws IOException { return delegate.bind(local, backlog); } public <T> ServerSocketChannel setOption(SocketOption<T> name, T value) throws IOException { return wrap(delegate.setOption(name, value)); } public SocketChannel accept() throws IOException { return wrap(delegate.accept()); } } private class SocketChannelWrapper extends SocketChannel implements Wrapper<SocketChannel> { private final SocketChannel delegate; public SocketChannelWrapper(SocketChannel delegate) { super(IoTraceSelectorProvider.this); this.delegate = delegate; } public SocketChannel unwrap() { return delegate; } ///// directly invoke delegate public int hashCode() { return delegate.hashCode(); } public SocketAddress getLocalAddress() throws IOException { return delegate.getLocalAddress(); } public boolean equals(Object obj) { return delegate.equals(obj); } public <T> T getOption(SocketOption<T> name) throws IOException { return delegate.getOption(name); } public Set<SocketOption<?>> supportedOptions() { return delegate.supportedOptions(); } public String toString() { return delegate.toString(); } public boolean isConnected() { return delegate.isConnected(); } public boolean isConnectionPending() { return delegate.isConnectionPending(); } public boolean connect(SocketAddress remote) throws IOException { return delegate.connect(remote); } public boolean finishConnect() throws IOException { return delegate.finishConnect(); } public SocketAddress getRemoteAddress() throws IOException { return delegate.getRemoteAddress(); } ///// invoke delegate using reflection protected void implCloseSelectableChannel() throws IOException { reflectCloseSelectableChannel(delegate); } protected void implConfigureBlocking(boolean block) throws IOException { reflectConfigureBlocking(delegate, block); } ///// wrap results public SocketChannel bind(SocketAddress local) throws IOException { return wrap(delegate.bind(local)); } public <T> SocketChannel setOption(SocketOption<T> name, T value) throws IOException { return wrap(delegate.setOption(name, value)); } public SocketChannel shutdownInput() throws IOException { return wrap(delegate.shutdownInput()); } public SocketChannel shutdownOutput() throws IOException { return wrap(delegate.shutdownOutput()); } ///// factory should handle correct impl public Socket socket() { return delegate.socket(); } ///// invoke IoTrace private boolean hasReadTrace() { return isBlocking(); // for SocketChannelImpl, others may vary } private boolean hasWriteTrace() { return true; // for SocketChannelImpl, others may vary } public int read(ByteBuffer dst) throws IOException { final Object context = hasReadTrace() ? null : IoTraceHandler.socketReadBegin(); final int bytes = delegate.read(dst); if(bytes>0) { IoTraceHandler.socketReadEnd(context, getRemoteAddress(), bytes); } return bytes; } public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { final Object context = hasReadTrace() ? null : IoTraceHandler.socketReadBegin(); final long bytes = delegate.read(dsts, offset, length); if(bytes>0) { IoTraceHandler.socketReadEnd(context, getRemoteAddress(), bytes); } return bytes; } public int write(ByteBuffer src) throws IOException { final Object context = hasWriteTrace() ? null : IoTraceHandler.socketWriteBegin(); final int bytes = delegate.write(src); if(bytes>0) { IoTraceHandler.socketWriteEnd(context, getRemoteAddress(), bytes); } return bytes; } public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { final Object context = hasWriteTrace() ? null : IoTraceHandler.socketWriteBegin(); final long bytes = delegate.write(srcs, offset, length); if(bytes>0) { IoTraceHandler.socketWriteEnd(context, getRemoteAddress(), bytes); } return bytes; } } private class SelectorWrapper extends AbstractSelector implements Wrapper<AbstractSelector> { private AbstractSelector delegate; public SelectorWrapper(AbstractSelector delegate) { super(IoTraceSelectorProvider.this); this.delegate = delegate; } public AbstractSelector unwrap() { return delegate; } public int hashCode() { return delegate.hashCode(); } public boolean equals(Object obj) { return delegate.equals(obj); } public Set<SelectionKey> keys() { return delegate.keys(); } public String toString() { return delegate.toString(); } public Set<SelectionKey> selectedKeys() { return delegate.selectedKeys(); } public int selectNow() throws IOException { return delegate.selectNow(); } public int select(long timeout) throws IOException { return delegate.select(timeout); } public int select() throws IOException { return delegate.select(); } public Selector wakeup() { return delegate.wakeup(); } ///// invoke delegate using reflection @Override protected void implCloseSelector() throws IOException { reflectCloseSelector(delegate); } @Override protected SelectionKey register(AbstractSelectableChannel ch, int ops, Object att) { AbstractSelectableChannel unwrapped = IoTraceSelectorProvider.this.unwrap(ch); return reflectRegister(delegate, unwrapped, ops, att); } } }
923a44e339ddfabf3dc0ef83a55769d57fb682ac
6,683
java
Java
redisson/src/main/java/org/redisson/connection/RedisClientEntry.java
amohtashami12307/redisson
4b5a221685304851bafe6c24120ae98c6e11b13f
[ "Apache-2.0" ]
4
2019-10-17T02:45:50.000Z
2020-09-18T07:34:15.000Z
redisson/src/main/java/org/redisson/connection/RedisClientEntry.java
amohtashami12307/redisson
4b5a221685304851bafe6c24120ae98c6e11b13f
[ "Apache-2.0" ]
11
2020-02-28T01:25:59.000Z
2022-01-21T23:30:34.000Z
redisson/src/main/java/org/redisson/connection/RedisClientEntry.java
amohtashami12307/redisson
4b5a221685304851bafe6c24120ae98c6e11b13f
[ "Apache-2.0" ]
9
2019-11-20T14:44:06.000Z
2022-01-08T04:25:20.000Z
35.547872
137
0.666018
999,144
/** * Copyright (c) 2013-2019 Nikita Koksharov * * 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.redisson.connection; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.TimeUnit; import org.redisson.api.ClusterNode; import org.redisson.api.NodeType; import org.redisson.api.RFuture; import org.redisson.client.RedisClient; import org.redisson.client.RedisTimeoutException; import org.redisson.client.codec.LongCodec; import org.redisson.client.codec.StringCodec; import org.redisson.client.protocol.RedisCommands; import org.redisson.client.protocol.Time; import org.redisson.command.CommandSyncService; import org.redisson.misc.RPromise; import org.redisson.misc.RedissonPromise; /** * * @author Nikita Koksharov * */ public class RedisClientEntry implements ClusterNode { private final RedisClient client; private final CommandSyncService commandExecutor; private final NodeType type; public RedisClientEntry(RedisClient client, CommandSyncService commandExecutor, NodeType type) { super(); this.client = client; this.commandExecutor = commandExecutor; this.type = type; } @Override public NodeType getType() { return type; } public RedisClient getClient() { return client; } @Override public InetSocketAddress getAddr() { return client.getAddr(); } @Override public RFuture<Boolean> pingAsync() { return pingAsync(1, TimeUnit.SECONDS); } @Override public RFuture<Boolean> pingAsync(long timeout, TimeUnit timeUnit) { RPromise<Boolean> result = new RedissonPromise<>(); RFuture<Boolean> f = commandExecutor.readAsync(client, null, RedisCommands.PING_BOOL); f.onComplete((res, e) -> { if (e != null) { result.trySuccess(false); return; } result.trySuccess(res); }); commandExecutor.getConnectionManager().newTimeout(t -> { RedisTimeoutException ex = new RedisTimeoutException("Command execution timeout for command: PING, Redis client: " + client); result.tryFailure(ex); }, timeout, timeUnit); return result; } @Override public boolean ping() { return commandExecutor.get(pingAsync()); } @Override public boolean ping(long timeout, TimeUnit timeUnit) { return commandExecutor.get(pingAsync(timeout, timeUnit)); } @Override @SuppressWarnings("AvoidInlineConditionals") public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((client == null) ? 0 : client.getAddr().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RedisClientEntry other = (RedisClientEntry) obj; if (client == null) { if (other.client != null) return false; } else if (!client.getAddr().equals(other.client.getAddr())) return false; return true; } @Override public RFuture<Time> timeAsync() { return commandExecutor.readAsync(client, LongCodec.INSTANCE, RedisCommands.TIME); } @Override public Time time() { return commandExecutor.get(timeAsync()); } @Override public RFuture<Map<String, String>> clusterInfoAsync() { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.CLUSTER_INFO); } @Override public Map<String, String> clusterInfo() { return commandExecutor.get(clusterInfoAsync()); } @Override public Map<String, String> info(InfoSection section) { return commandExecutor.get(infoAsync(section)); } @Override public RFuture<Map<String, String>> infoAsync(InfoSection section) { if (section == InfoSection.ALL) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_ALL); } else if (section == InfoSection.DEFAULT) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_DEFAULT); } else if (section == InfoSection.SERVER) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_SERVER); } else if (section == InfoSection.CLIENTS) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_CLIENTS); } else if (section == InfoSection.MEMORY) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_MEMORY); } else if (section == InfoSection.PERSISTENCE) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_PERSISTENCE); } else if (section == InfoSection.STATS) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_STATS); } else if (section == InfoSection.REPLICATION) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_REPLICATION); } else if (section == InfoSection.CPU) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_CPU); } else if (section == InfoSection.COMMANDSTATS) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_COMMANDSTATS); } else if (section == InfoSection.CLUSTER) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_CLUSTER); } else if (section == InfoSection.KEYSPACE) { return commandExecutor.readAsync(client, StringCodec.INSTANCE, RedisCommands.INFO_KEYSPACE); } throw new IllegalStateException(); } @Override public String toString() { return "RedisClientEntry [client=" + client + ", type=" + type + "]"; } }
923a466d8ec64b34b6aecbfaffbf3c1c17e9cf58
3,682
java
Java
core/src/main/java/org/elasticsearch/rest/action/document/RestMultiGetAction.java
kurtado/elasticsearch
dc86b4c2ed09eadd5f517f3e178ac7f302066532
[ "Apache-2.0" ]
1,125
2016-09-11T17:27:35.000Z
2022-03-29T13:41:58.000Z
core/src/main/java/org/elasticsearch/rest/action/document/RestMultiGetAction.java
albertzaharovits/elasticsearch
206208dc43c62e4cb4f9019fe3a8d4ba2adc2423
[ "Apache-2.0" ]
346
2016-12-03T18:37:07.000Z
2022-03-29T08:33:04.000Z
core/src/main/java/org/elasticsearch/rest/action/document/RestMultiGetAction.java
albertzaharovits/elasticsearch
206208dc43c62e4cb4f9019fe3a8d4ba2adc2423
[ "Apache-2.0" ]
190
2016-12-15T13:46:19.000Z
2022-03-04T05:17:11.000Z
43.833333
120
0.736285
999,145
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.rest.action.document; import org.elasticsearch.action.get.MultiGetRequest; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.action.RestToXContentListener; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.POST; public class RestMultiGetAction extends BaseRestHandler { private final boolean allowExplicitIndex; public RestMultiGetAction(Settings settings, RestController controller) { super(settings); controller.registerHandler(GET, "/_mget", this); controller.registerHandler(POST, "/_mget", this); controller.registerHandler(GET, "/{index}/_mget", this); controller.registerHandler(POST, "/{index}/_mget", this); controller.registerHandler(GET, "/{index}/{type}/_mget", this); controller.registerHandler(POST, "/{index}/{type}/_mget", this); this.allowExplicitIndex = MULTI_ALLOW_EXPLICIT_INDEX.get(settings); } @Override public String getName() { return "document_mget_action"; } @Override public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException { MultiGetRequest multiGetRequest = new MultiGetRequest(); multiGetRequest.refresh(request.paramAsBoolean("refresh", multiGetRequest.refresh())); multiGetRequest.preference(request.param("preference")); multiGetRequest.realtime(request.paramAsBoolean("realtime", multiGetRequest.realtime())); if (request.param("fields") != null) { throw new IllegalArgumentException("The parameter [fields] is no longer supported, " + "please use [stored_fields] to retrieve stored fields or _source filtering if the field is not stored"); } String[] sFields = null; String sField = request.param("stored_fields"); if (sField != null) { sFields = Strings.splitStringByCommaToArray(sField); } FetchSourceContext defaultFetchSource = FetchSourceContext.parseFromRestRequest(request); try (XContentParser parser = request.contentOrSourceParamParser()) { multiGetRequest.add(request.param("index"), request.param("type"), sFields, defaultFetchSource, request.param("routing"), parser, allowExplicitIndex); } return channel -> client.multiGet(multiGetRequest, new RestToXContentListener<>(channel)); } }
923a468ea8a0358a2647c6887eb10ca3c16be6ec
320
java
Java
src/main/java/com/xiaoping/cmdtest/TimeTest.java
xiaop1ng/PlayWithSpringBoot
9dd09ebfd09217919dfd4441ad0eef03a8bef86d
[ "Apache-2.0" ]
46
2018-07-25T05:54:12.000Z
2021-06-06T07:43:15.000Z
src/main/java/com/xiaoping/cmdtest/TimeTest.java
xiaop1ng/PlayWithSpringBoot
9dd09ebfd09217919dfd4441ad0eef03a8bef86d
[ "Apache-2.0" ]
2
2019-11-27T08:13:15.000Z
2020-06-09T08:36:45.000Z
src/main/java/com/xiaoping/cmdtest/TimeTest.java
xiaop1ng/PlayWithSpringBoot
9dd09ebfd09217919dfd4441ad0eef03a8bef86d
[ "Apache-2.0" ]
29
2018-10-23T03:49:53.000Z
2021-06-06T07:43:16.000Z
24.615385
69
0.65625
999,146
package com.xiaoping.cmdtest; import java.util.Date; public class TimeTest { public static void main(String[] args) { Date expireTime = new Date(); System.out.println(expireTime); expireTime.setTime(expireTime.getTime() + 1000*60*30); // 半小时 System.out.println(expireTime); } }
923a4840c5628196e39498af93a54aa857fbe728
1,972
java
Java
src/java/org/ajwcc/pduUtils/test/integration/ReadMessages.java
zhang13/smslib-v3
22ad83f909b7840978f843c3ec885bc7940a976b
[ "Apache-2.0" ]
43
2016-03-23T02:01:13.000Z
2022-03-27T09:22:11.000Z
src/java/org/ajwcc/pduUtils/test/integration/ReadMessages.java
zhang13/smslib-v3
22ad83f909b7840978f843c3ec885bc7940a976b
[ "Apache-2.0" ]
7
2016-03-26T15:18:58.000Z
2016-03-26T15:18:59.000Z
src/java/org/ajwcc/pduUtils/test/integration/ReadMessages.java
zhang13/smslib-v3
22ad83f909b7840978f843c3ec885bc7940a976b
[ "Apache-2.0" ]
84
2016-03-26T03:21:49.000Z
2022-03-09T08:34:50.000Z
27.388889
87
0.712475
999,147
// ReadMessages.java - Sample application. // // This application shows you the basic procedure needed for reading // SMS messages from your GSM modem, in synchronous mode. // // Operation description: // The application setup the necessary objects and connects to the phone. // As a first step, it reads all messages found in the phone. // Then, it goes to sleep, allowing the asynchronous callback handlers to // be called. Furthermore, for callback demonstration purposes, it responds // to each received message with a "Got It!" reply. // // Tasks: // 1) Setup Service object. // 2) Setup one or more Gateway objects. // 3) Attach Gateway objects to Service object. // 4) Setup callback notifications. // 5) Run package org.ajwcc.pduUtils.test.integration; import java.util.*; import org.smslib.*; import org.smslib.InboundMessage.*; public class ReadMessages extends AbstractTester { @Override public void test() throws Exception { List<InboundMessage> msgList; try { // Read Messages. The reading is done via the Service object and // affects all Gateway objects defined. This can also be more directed to a specific // Gateway - look the JavaDocs for information on the Service method calls. msgList = new ArrayList<InboundMessage>(); Service.getInstance().readMessages(msgList, MessageClasses.ALL); for (InboundMessage msg : msgList) { System.out.println(msg); } // Sleep now. Emulate real world situation and give a chance to the notifications // methods to be called in the event of message or voice call reception. System.out.println("Now Sleeping - Hit <enter> to terminate."); System.in.read(); } catch (Exception e) { e.printStackTrace(); } finally { Service.getInstance().stopService(); } } public static void main(String args[]) { ReadMessages app = new ReadMessages(); try { app.initModem(); app.test(); } catch (Exception e) { e.printStackTrace(); } } }
923a488990fe2754431aa37f796c5d9cb583ea9b
10,888
java
Java
archive/FILE/Compiler/java_GJC1.42_src/src/com/sun/tools/javac/v8/comp/TransTypes.java
nileshpatelksy/hello-pod-cast
a2efa652735687ece13fd4297ceb0891289dc10b
[ "Apache-2.0" ]
null
null
null
archive/FILE/Compiler/java_GJC1.42_src/src/com/sun/tools/javac/v8/comp/TransTypes.java
nileshpatelksy/hello-pod-cast
a2efa652735687ece13fd4297ceb0891289dc10b
[ "Apache-2.0" ]
null
null
null
archive/FILE/Compiler/java_GJC1.42_src/src/com/sun/tools/javac/v8/comp/TransTypes.java
nileshpatelksy/hello-pod-cast
a2efa652735687ece13fd4297ceb0891289dc10b
[ "Apache-2.0" ]
null
null
null
26.110312
87
0.669269
999,148
/** * @(#)TransTypes.java 1.39 03/01/23 * * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.sun.tools.javac.v8.comp; import com.sun.tools.javac.v8.util.*; import com.sun.tools.javac.v8.code.*; import com.sun.tools.javac.v8.tree.*; import com.sun.tools.javac.v8.code.Symbol.*; import com.sun.tools.javac.v8.tree.Tree.*; import com.sun.tools.javac.v8.code.Type.*; /** * This pass translates Generic Java to conventional Java. */ public class TransTypes extends TreeTranslator implements Flags, Kinds, TypeTags { /** * The context key for the TransTypes phase. */ private static final Context.Key transTypesKey = new Context.Key(); /** * Get the instance for this context. */ public static TransTypes instance(Context context) { TransTypes instance = (TransTypes) context.get(transTypesKey); if (instance == null) instance = new TransTypes(context); return instance; } private Name.Table names; private Log log; private Symtab syms; private TreeMaker make; private TransTypes(Context context) { super(); context.put(transTypesKey, this); names = Name.Table.instance(context); log = Log.instance(context); syms = Symtab.instance(context); } /** * A hashtable mapping bridge methods to the methods they override after * type erasure. */ Hashtable overridden; /** * Construct an attributed tree for a cast of expression to target type, * unless it already has precisely that type. * * @param tree * The expression tree. * @param target * The target type. */ Tree cast(Tree tree, Type target) { int oldpos = make.pos; make.at(tree.pos); if (!tree.type.isSameType(target)) { tree = make.TypeCast(make.Type(target), tree).setType(target); } make.pos = oldpos; return tree; } /** * Construct an attributed tree to coerce an expression to some erased * target type, unless the expression is already assignable to that type. If * target type is a constant type, use its base type instead. * * @param tree * The expression tree. * @param target * The target type. */ Tree coerce(Tree tree, Type target) { Type btarget = target.baseType(); return tree.type.isAssignable(btarget) ? tree : cast(tree, btarget); } /** * Given an erased reference type, assume this type as the tree's type. * Then, coerce to some given target type unless target type is null. This * operation is used in situations like the following: * * class Cell<A> { A value; } ... Cell<Integer> cell; Integer x = * cell.value; * * Since the erasure of Cell.value is Object, but the type of cell.value in * the assignment is Integer, we need to adjust the original type of * cell.value to Object, and insert a cast to Integer. That is, the last * assignment becomes: * * Integer x = (Integer)cell.value; * * @param tree * The expression tree whose type might need adjustment. * @param erasedType * The expression's type after erasure. * @param target * The target type, which is usually the erasure of the * expression's original type. */ Tree retype(Tree tree, Type erasedType, Type target) { if (erasedType.tag > lastBaseTag) { tree.type = erasedType; if (target != null) return coerce(tree, target); } return tree; } /** * Translate method argument list, casting each argument to its * corresponding type in a list of target types. * * @param trees * The method argument list. * @param targets * The list of target types. */ List translateArgs(List trees, List targets) { for (List l = trees; l.nonEmpty(); l = l.tail) { l.head = translate((Tree) l.head, (Type) targets.head); targets = targets.tail; } return trees; } /** * Visitor argument: proto-type. */ private Type pt; /** * Visitor method: perform a type translation on tree. */ public Tree translate(Tree tree, Type pt) { Type prevPt = this.pt; try { this.pt = pt; if (tree == null) result = null; else tree.accept(this); } finally { this.pt = prevPt; } return result; } /** * Visitor method: perform a type translation on list of trees. */ public List translate(List trees, Type pt) { Type prevPt = this.pt; List res; try { this.pt = pt; res = translate(trees); } finally { this.pt = prevPt; } return res; } public void visitClassDef(ClassDef tree) { tree.typarams = TypeParameter.emptyList; super.visitClassDef(tree); make.at(tree.pos); tree.type = tree.type.erasure(); result = tree; } public void visitMethodDef(MethodDef tree) { tree.restype = translate(tree.restype, null); tree.typarams = TypeParameter.emptyList; tree.params = translateVarDefs(tree.params); tree.thrown = translate(tree.thrown, null); tree.body = (Block) translate(tree.body, tree.sym.erasure().restype()); tree.type = tree.type.erasure(); result = tree; for (Scope.Entry e = tree.sym.owner.members().lookup(tree.name); e.sym != null; e = e .next()) { if (e.sym != tree.sym && e.sym.type.erasure().isSameType(tree.type)) { log.error(tree.pos, "name.clash.same.erasure", tree.sym .toJava(), e.sym.toJava()); return; } } } public void visitVarDef(VarDef tree) { tree.vartype = translate(tree.vartype, null); tree.init = translate(tree.init, tree.sym.erasure()); tree.type = tree.type.erasure(); result = tree; } public void visitDoLoop(DoLoop tree) { tree.body = translate(tree.body); tree.cond = translate(tree.cond, null); result = tree; } public void visitWhileLoop(WhileLoop tree) { tree.cond = translate(tree.cond, null); tree.body = translate(tree.body); result = tree; } public void visitForLoop(ForLoop tree) { tree.init = translate(tree.init, null); tree.cond = translate(tree.cond, null); tree.step = translate(tree.step, null); tree.body = translate(tree.body); result = tree; } public void visitSwitch(Switch tree) { tree.selector = translate(tree.selector, null); tree.cases = translateCases(tree.cases); result = tree; } public void visitCase(Case tree) { tree.pat = translate(tree.pat, null); tree.stats = translate(tree.stats); result = tree; } public void visitSynchronized(Synchronized tree) { tree.lock = translate(tree.lock, null); tree.body = translate(tree.body); result = tree; } public void visitConditional(Conditional tree) { tree.cond = translate(tree.cond, null); tree.truepart = translate(tree.truepart, tree.type.erasure()); tree.falsepart = translate(tree.falsepart, tree.type.erasure()); result = tree; } public void visitIf(If tree) { tree.cond = translate(tree.cond, null); tree.thenpart = translate(tree.thenpart); tree.elsepart = translate(tree.elsepart); result = tree; } public void visitExec(Exec tree) { tree.expr = translate(tree.expr, null); result = tree; } public void visitReturn(Return tree) { tree.expr = translate(tree.expr); result = tree; } public void visitThrow(Throw tree) { tree.expr = translate(tree.expr, tree.expr.type.erasure()); result = tree; } public void visitAssert(Assert tree) { tree.cond = translate(tree.cond, null); if (tree.detail != null) tree.detail = translate(tree.detail, null); result = tree; } public void visitApply(Apply tree) { tree.meth = translate(tree.meth, null); Type mt = TreeInfo.symbol(tree.meth).erasure(); tree.args = translateArgs(tree.args, mt.argtypes()); result = retype(tree, mt.restype(), pt); } public void visitNewClass(NewClass tree) { if (tree.encl != null) tree.encl = translate(tree.encl, tree.encl.type.erasure()); tree.clazz = translate(tree.clazz, null); tree.args = translateArgs(tree.args, tree.constructor.erasure() .argtypes()); tree.def = (ClassDef) translate(tree.def, null); tree.type = tree.type.erasure(); result = tree; } public void visitNewArray(NewArray tree) { tree.elemtype = translate(tree.elemtype, null); tree.dims = translate(tree.dims, null); tree.elems = translate(tree.elems, tree.type.elemtype().erasure()); tree.type = tree.type.erasure(); result = tree; } public void visitParens(Parens tree) { tree.expr = translate(tree.expr, null); tree.type = tree.type.erasure(); result = tree; } public void visitAssign(Assign tree) { tree.lhs = translate(tree.lhs, null); tree.rhs = translate(tree.rhs, tree.lhs.type.erasure()); tree.type = tree.type.erasure(); result = tree; } public void visitAssignop(Assignop tree) { tree.lhs = translate(tree.lhs, null); tree.rhs = translate(tree.rhs, null); tree.type = tree.type.erasure(); result = tree; } public void visitUnary(Unary tree) { tree.arg = translate(tree.arg, (Type) tree.operator.type.argtypes().head); result = tree; } public void visitBinary(Binary tree) { tree.lhs = translate(tree.lhs, (Type) tree.operator.type.argtypes().head); tree.rhs = translate(tree.rhs, (Type) tree.operator.type.argtypes().tail.head); result = tree; } public void visitTypeCast(TypeCast tree) { tree.clazz = translate(tree.clazz, null); tree.expr = translate(tree.expr, null); tree.type = tree.type.erasure(); result = tree; } public void visitTypeTest(TypeTest tree) { tree.expr = translate(tree.expr, null); tree.clazz = translate(tree.clazz, null); result = tree; } public void visitIndexed(Indexed tree) { tree.indexed = translate(tree.indexed, tree.indexed.type.erasure()); tree.index = translate(tree.index, null); result = retype(tree, tree.indexed.type.elemtype(), pt); } public void visitIdent(Ident tree) { Type et = tree.sym.erasure(); if (tree.type.constValue != null) { result = tree; } else if (tree.sym.kind == VAR) { result = retype(tree, et, pt); } else { tree.type = tree.type.erasure(); result = tree; } } public void visitSelect(Select tree) { Type t = tree.selected.type; tree.selected = translate(tree.selected, t.erasure()); if (tree.type.constValue != null) { result = tree; } else if (tree.sym.kind == VAR) { result = retype(tree, tree.sym.erasure(), pt); } else { tree.type = tree.type.erasure(); result = tree; } } public void visitTypeArray(TypeArray tree) { tree.elemtype = translate(tree.elemtype, null); tree.type = tree.type.erasure(); result = tree; } /** * Translate a toplevel class definition. * * @param cdef * The definition to be translated. */ public Tree translateTopLevelClass(Tree cdef, TreeMaker make) { try { this.make = make; overridden = Hashtable.make(); pt = null; return translate(cdef, null); } finally { this.make = null; overridden = null; pt = null; } } }
923a48ee58de624c533767ef23ce3d1063ebfb9e
4,201
java
Java
bboss-core-entity/src/org/frameworkset/util/ESAnnoInfo.java
bbossgroups/bboss
09c505a2d14943aa28463da9403f222419711e20
[ "Apache-2.0" ]
246
2015-10-29T03:02:48.000Z
2022-03-31T03:58:17.000Z
bboss-core-entity/src/org/frameworkset/util/ESAnnoInfo.java
bbossgroups/bboss
09c505a2d14943aa28463da9403f222419711e20
[ "Apache-2.0" ]
4
2016-11-17T08:27:47.000Z
2021-07-28T09:31:56.000Z
bboss-core-entity/src/org/frameworkset/util/ESAnnoInfo.java
bbossgroups/bboss
09c505a2d14943aa28463da9403f222419711e20
[ "Apache-2.0" ]
148
2015-01-19T06:35:15.000Z
2022-01-07T04:53:04.000Z
26.093168
84
0.738634
999,149
package org.frameworkset.util; /** * Copyright 2008 biaoping.yin * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * <p>Description: Elasticsearch 注解信息封装类</p> * <p></p> * <p>Copyright (c) 2018</p> * @Date 2019/8/26 11:10 * @author biaoping.yin * @version 1.0 */ public class ESAnnoInfo { /** * es控制参数 */ // private boolean persistentESId; // private boolean esIdReadSet; // private boolean persistentESParentId; // private boolean esParentIdReadSet; // private boolean persistentESVersion; // private boolean esVersionReadSet; // private boolean persistentESVersionType; // private boolean persistentESRetryOnConflict; // private boolean persistentESRouting; // private boolean esRoutingReadSet; // private boolean persistentESDocAsUpsert; // private boolean persistentESSource; private boolean persistent; private boolean readSet; // /** // * es检索元数据参数 // */ // // // public boolean isPersistentESId() { // return persistentESId; // } // // public void setPersistentESId(boolean persistentESId) { // this.persistentESId = persistentESId; // } // // public boolean isEsIdReadSet() { // return esIdReadSet; // } // // public void setEsIdReadSet(boolean esIdReadSet) { // this.esIdReadSet = esIdReadSet; // } // // public boolean isPersistentESParentId() { // return persistentESParentId; // } // // public void setPersistentESParentId(boolean persistentESParentId) { // this.persistentESParentId = persistentESParentId; // } // // public boolean isEsParentIdReadSet() { // return esParentIdReadSet; // } // // public void setEsParentIdReadSet(boolean esParentIdReadSet) { // this.esParentIdReadSet = esParentIdReadSet; // } // // public boolean isPersistentESVersion() { // return persistentESVersion; // } // // public void setPersistentESVersion(boolean persistentESVersion) { // this.persistentESVersion = persistentESVersion; // } // // public boolean isPersistentESVersionType() { // return persistentESVersionType; // } // // public void setPersistentESVersionType(boolean persistentESVersionType) { // this.persistentESVersionType = persistentESVersionType; // } // // public boolean isPersistentESRetryOnConflict() { // return persistentESRetryOnConflict; // } // // public void setPersistentESRetryOnConflict(boolean persistentESRetryOnConflict) { // this.persistentESRetryOnConflict = persistentESRetryOnConflict; // } // // public boolean isPersistentESRouting() { // return persistentESRouting; // } // // public void setPersistentESRouting(boolean persistentESRouting) { // this.persistentESRouting = persistentESRouting; // } // // public boolean isPersistentESDocAsUpsert() { // return persistentESDocAsUpsert; // } // // public void setPersistentESDocAsUpsert(boolean persistentESDocAsUpsert) { // this.persistentESDocAsUpsert = persistentESDocAsUpsert; // } // // public boolean isPersistentESSource() { // return persistentESSource; // } // // public void setPersistentESSource(boolean persistentESSource) { // this.persistentESSource = persistentESSource; // } // // public boolean isEsVersionReadSet() { // return esVersionReadSet; // } // // public void setEsVersionReadSet(boolean esVersionReadSet) { // this.esVersionReadSet = esVersionReadSet; // } // // public boolean isEsRoutingReadSet() { // return esRoutingReadSet; // } // // public void setEsRoutingReadSet(boolean esRoutingReadSet) { // this.esRoutingReadSet = esRoutingReadSet; // } public boolean isPersistent() { return persistent; } public void setPersistent(boolean persistent) { this.persistent = persistent; } public boolean isReadSet() { return readSet; } public void setReadSet(boolean readSet) { this.readSet = readSet; } }
923a491a746624a800943992a65f686dc07b9a91
1,261
java
Java
424. Longest Repeating Character Replacement.java
andy-sheng/leetcode
1fa070036f31d0bd18a9a11a5c771641f3cd9a03
[ "MIT" ]
null
null
null
424. Longest Repeating Character Replacement.java
andy-sheng/leetcode
1fa070036f31d0bd18a9a11a5c771641f3cd9a03
[ "MIT" ]
null
null
null
424. Longest Repeating Character Replacement.java
andy-sheng/leetcode
1fa070036f31d0bd18a9a11a5c771641f3cd9a03
[ "MIT" ]
null
null
null
39.40625
103
0.535289
999,150
public class Solution { private int getMajorityLetter(int []hashMap) { int result = hashMap.length - 1; for (int i = hashMap.length - 2; i >-1; --i) { if (hashMap[i] > hashMap[result]) result = i; } return result; } public int characterReplacement(String s, int k) { int []hashMap = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int result = 0; int majorityLetter = -1; int windowLeft = -1, windowRight = 0; // slide window for(; windowRight < s.length(); ++windowRight) { // window grow int letter = s.charAt(windowRight) - 'A'; ++hashMap[letter]; if (majorityLetter == -1 || hashMap[letter] > hashMap[majorityLetter]) { majorityLetter = letter; } while ((windowRight - windowLeft) - hashMap[majorityLetter] > k) { // window need to shrunk ++windowLeft; --hashMap[s.charAt(windowLeft) - 'A']; majorityLetter = this.getMajorityLetter(hashMap); // select a new majority letter } if (windowRight - windowLeft > result) result = windowRight - windowLeft; } return result; } }
923a4ba6770176a82b0d150e2a64b665c088cbd0
578
java
Java
src/main/java/com/snowalker/shardingjdbc/snowalker/demo/entity/TUser.java
Taoei/snowalker-shardingjdbc-demo
ae4f661b0c596b3077d3f39a132d6077bd301595
[ "Apache-2.0" ]
null
null
null
src/main/java/com/snowalker/shardingjdbc/snowalker/demo/entity/TUser.java
Taoei/snowalker-shardingjdbc-demo
ae4f661b0c596b3077d3f39a132d6077bd301595
[ "Apache-2.0" ]
null
null
null
src/main/java/com/snowalker/shardingjdbc/snowalker/demo/entity/TUser.java
Taoei/snowalker-shardingjdbc-demo
ae4f661b0c596b3077d3f39a132d6077bd301595
[ "Apache-2.0" ]
null
null
null
19.266667
78
0.714533
999,151
package com.snowalker.shardingjdbc.snowalker.demo.entity; import lombok.Data; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; /** * @author taowei * @version 1.0.0 * @date 2020/9/24 5:43 下午 * @description **/ @Data public class TUser implements Serializable { private Integer id; private Integer userId; private String userName; private Integer regionId; private Date createTime; public String getCreateTimeDesc() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTime); } }
923a4c45404c1a1cfbc2562f765a753c861fb4df
2,387
java
Java
RestClient/src/org/rest/client/task/TasksCallback.java
spoole/ARC
c5134fd39c7d9584c066757066cf192b3e9789e7
[ "Apache-2.0" ]
null
null
null
RestClient/src/org/rest/client/task/TasksCallback.java
spoole/ARC
c5134fd39c7d9584c066757066cf192b3e9789e7
[ "Apache-2.0" ]
null
null
null
RestClient/src/org/rest/client/task/TasksCallback.java
spoole/ARC
c5134fd39c7d9584c066757066cf192b3e9789e7
[ "Apache-2.0" ]
null
null
null
25.393617
80
0.650607
999,152
package org.rest.client.task; /** * The primary interface a caller must implement to receive a response from a * {@link LoadTask}. * * <p> * If an task is successful, then {@link #onSuccess()} is called, otherwise * {@link #onFailure()} is called. * </p> * * <p> * Note: {@link #onInnerTaskFinished()} should be called at least once. If * {@link LoadTask} has more than one inner task this should be call after each * inner task finish it's job. * </p> * <p> * A call with a typical use of <code>TasksCallback</code> might look like this: * * <pre class="code"> * task.run(new TasksCallback() { * public void onSuccess() { * TasksLoader.processNext(); * } * * public void onFailure(int finished) { * if (tryOnFailure) { * TasksLoader.tryAgainOrDie(); * } else { * taskFinished += task.getTasksCount() - finished; * TasksLoader.notifyUIabautTaskFinish(); * } * } * * public void onInnerTaskFinished() { * // increase loader only * TasksLoader.notifyUIabautTaskFinish(); * } * * }); * </pre> * * </p> * * @author jarrod * */ public interface TasksCallback { /** * Called when an task call fails to complete normally. * <p> * {@link TasksLoader} should than try to run task one more time. If task * fails to complete again than {@link TasksLoader} remove task from tasks * que and continue. * </p> * */ void onFailure(int tasksExecutedCount); /** * Should be called when task is unable to complete it's work and this is * fatal error. * <p> * Application can't run without this task and should display error message * only. * </p> * * @param message * Message to display to user. */ void onFatalError(String message); /** * Called when an task call completes successfully. * <p> * After this call {@link TasksLoader} remove task from tasks que and * continue with next task. * </p> * <p> * There is no way (yet) to implement fatal error about task. You can't * notify user about something go wrong. If that widgets should handle * errors by themselfs. * </p> */ void onSuccess(); /** * Called when each inner task is finished. If task has only one inner task its * should be executed before {@link #onSuccess()} is called. * @param taskFinished number of task finished. */ void onInnerTaskFinished(int taskFinished); }
923a4cbb526c06e958fcb673338541b0ee0ab8c0
1,747
java
Java
src/main/java/br/com/fws/contact_app_backend/model/PerfilSocial.java
feh-wilinando/contact-app-backend
f488117a69fe2fc1a3d937df3fdccedc2f6e0c2d
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/fws/contact_app_backend/model/PerfilSocial.java
feh-wilinando/contact-app-backend
f488117a69fe2fc1a3d937df3fdccedc2f6e0c2d
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/fws/contact_app_backend/model/PerfilSocial.java
feh-wilinando/contact-app-backend
f488117a69fe2fc1a3d937df3fdccedc2f6e0c2d
[ "Apache-2.0" ]
null
null
null
20.08046
79
0.68403
999,153
package br.com.fws.contact_app_backend.model; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class PerfilSocial { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String perfil; @Enumerated(EnumType.STRING) private RedeSocial redeSocial; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPerfil() { return perfil; } public void setPerfil(String perfil) { this.perfil = perfil; } public RedeSocial getRedeSocial() { return redeSocial; } public void setRedeSocial(RedeSocial redeSocial) { this.redeSocial = redeSocial; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((perfil == null) ? 0 : perfil.hashCode()); result = prime * result + ((redeSocial == null) ? 0 : redeSocial.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PerfilSocial other = (PerfilSocial) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (perfil == null) { if (other.perfil != null) return false; } else if (!perfil.equals(other.perfil)) return false; if (redeSocial != other.redeSocial) return false; return true; } enum RedeSocial { TWITTER,INSTAGRAM,GOOGLE_PLUS,FACEBOOK; } }
923a4e41f262ec31525c76a62e85b9f5796eb3a7
1,242
java
Java
lightcrafts/src/com/lightcrafts/image/export/ResolutionOption.java
mr-c/LightZone
acf5501fdda8e1077770cf6937879824a759ec93
[ "BSD-3-Clause" ]
303
2015-01-28T12:03:10.000Z
2022-03-21T12:14:56.000Z
lightcrafts/src/com/lightcrafts/image/export/ResolutionOption.java
mr-c/LightZone
acf5501fdda8e1077770cf6937879824a759ec93
[ "BSD-3-Clause" ]
127
2015-01-04T12:14:22.000Z
2022-03-29T01:48:30.000Z
lightcrafts/src/com/lightcrafts/image/export/ResolutionOption.java
mr-c/LightZone
acf5501fdda8e1077770cf6937879824a759ec93
[ "BSD-3-Clause" ]
51
2015-03-19T22:18:08.000Z
2022-01-28T15:42:19.000Z
26.425532
78
0.650564
999,154
/* Copyright (C) 2005-2011 Fabio Riccardi */ package com.lightcrafts.image.export; /** * A <code>ResolutionOption</code> is-an {@link IntegerExportOption} for * storing the number of pixels per unit measurment for an image. * * @author Paul J. Lucas [paul@lightcrafts.com] */ public final class ResolutionOption extends IntegerExportOption { public static final int DEFAULT_VALUE = 300; public static final String NAME = ResolutionOption.class.getName(); /** * Construct a <code>ResolutionOption</code>. * * @param options The {@link ImageExportOptions} of which this option is a * member. */ public ResolutionOption( ImageExportOptions options ) { this( DEFAULT_VALUE, options ); } /** * Construct a <code>ResolutionOption</code>. * * @param defaultValue The default value. * @param options The {@link ImageExportOptions} of which this option is a * member. */ public ResolutionOption( int defaultValue, ImageExportOptions options ) { super( NAME, defaultValue, options ); } /** * {@inheritDoc} */ public boolean isLegalValue( int value ) { return value > 0; } } /* vim:set et sw=4 ts=4: */
923a4eb8e0fd4b63ca691e02d67cbda04f9260d5
1,940
java
Java
src/model/java/org/ubjson/model/BigIntegerHugeValue.java
rkalla/universal-binary-json-java
46a0ebc7a9fb222bbaa6d84a25995defdd9319bb
[ "Apache-2.0" ]
9
2016-12-06T11:21:16.000Z
2020-09-18T14:24:00.000Z
src/model/java/org/ubjson/model/BigIntegerHugeValue.java
Acidburn0zzz/universal-binary-json-java
46a0ebc7a9fb222bbaa6d84a25995defdd9319bb
[ "Apache-2.0" ]
1
2021-08-31T20:35:30.000Z
2022-02-19T22:43:53.000Z
src/model/java/org/ubjson/model/BigIntegerHugeValue.java
Acidburn0zzz/universal-binary-json-java
46a0ebc7a9fb222bbaa6d84a25995defdd9319bb
[ "Apache-2.0" ]
3
2017-12-11T12:55:09.000Z
2020-08-07T00:49:26.000Z
29.393939
77
0.729897
999,155
/** * Copyright 2011 The Buzz Media, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ubjson.model; import static org.ubjson.io.IUBJTypeMarker.HUGE; import static org.ubjson.io.IUBJTypeMarker.HUGE_COMPACT; import java.io.IOException; import java.math.BigInteger; import org.ubjson.io.UBJFormatException; import org.ubjson.io.UBJInputStreamParser; import org.ubjson.io.UBJOutputStream; public class BigIntegerHugeValue extends AbstractValue<BigInteger> { protected int length = -1; public BigIntegerHugeValue(BigInteger value) throws IllegalArgumentException { super(value); } public BigIntegerHugeValue(UBJInputStreamParser in) throws IllegalArgumentException, IOException, UBJFormatException { super(in); } @Override public byte getType() { if (length == -1) length = value.toString().length(); return (length < 255 ? HUGE_COMPACT : HUGE); } @Override public void serialize(UBJOutputStream out) throws IllegalArgumentException, IOException { if (out == null) throw new IllegalArgumentException("out cannot be null"); out.writeHuge(value); } @Override public void deserialize(UBJInputStreamParser in) throws IllegalArgumentException, IOException, UBJFormatException { if (in == null) throw new IllegalArgumentException("in cannot be null"); value = (BigInteger) in.readHuge(); } }
923a4f6eab4340e7116e51f7c183a769b570e7b3
986
java
Java
src/main/java/io/fusionauth/domain/api/APIKeyResponse.java
zhengchengyang/fusionauth-java-client
ef81ec8d45de225165197ff35435f4ce3461dd12
[ "Apache-2.0" ]
5
2019-05-23T07:11:07.000Z
2021-03-04T03:16:17.000Z
src/main/java/io/fusionauth/domain/api/APIKeyResponse.java
zhengchengyang/fusionauth-java-client
ef81ec8d45de225165197ff35435f4ce3461dd12
[ "Apache-2.0" ]
14
2019-04-03T11:00:22.000Z
2022-03-31T23:24:14.000Z
src/main/java/io/fusionauth/domain/api/APIKeyResponse.java
zhengchengyang/fusionauth-java-client
ef81ec8d45de225165197ff35435f4ce3461dd12
[ "Apache-2.0" ]
3
2019-11-06T12:17:55.000Z
2022-03-12T10:19:50.000Z
27.388889
68
0.737323
999,156
/* * Copyright (c) 2021, FusionAuth, All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package io.fusionauth.domain.api; import com.inversoft.json.JacksonConstructor; import io.fusionauth.domain.APIKey; /** * Authentication key response object. * * @author Sanjay */ public class APIKeyResponse { public APIKey apiKey; @JacksonConstructor public APIKeyResponse() { } public APIKeyResponse(APIKey apiKey) { this.apiKey = apiKey; } }
923a4fd54f27ce4748be147b20939ed73a6728dd
1,498
java
Java
controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOSubscriberInfo.java
onapdemo/EXFO-policy
8ea919531f069a47b19d800c2d5db1a9b06c25bc
[ "Apache-2.0" ]
1
2018-08-20T13:14:45.000Z
2018-08-20T13:14:45.000Z
controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOSubscriberInfo.java
onapdemo/vfmoduledelete-policy
8ea919531f069a47b19d800c2d5db1a9b06c25bc
[ "Apache-2.0" ]
null
null
null
controlloop/common/model-impl/so/src/main/java/org/onap/policy/so/SOSubscriberInfo.java
onapdemo/vfmoduledelete-policy
8ea919531f069a47b19d800c2d5db1a9b06c25bc
[ "Apache-2.0" ]
null
null
null
31.208333
83
0.602136
999,157
/*- * ============LICENSE_START======================================================= * mso * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.policy.so; import java.io.Serializable; import com.google.gson.annotations.SerializedName; public class SOSubscriberInfo implements Serializable { /** * */ private static final long serialVersionUID = -3283942659786236032L; @SerializedName("globalSubscriberId") public String globalSubscriberId; @SerializedName("subscriberCommonSiteId") public String subscriberCommonSiteId; @SerializedName("subscriberName") public String subscriberName; public SOSubscriberInfo() { } }
923a504757a4d0f080b8148375b229db4f459d41
1,597
java
Java
games/src/test/java/com/jtbdevelopment/games/factory/gameinitializers/PlayerStateInitializerTest.java
jtbdevelopment/core-games
df74d52e944e892ee797ca87e6b4ad1798b6c1d8
[ "MIT" ]
null
null
null
games/src/test/java/com/jtbdevelopment/games/factory/gameinitializers/PlayerStateInitializerTest.java
jtbdevelopment/core-games
df74d52e944e892ee797ca87e6b4ad1798b6c1d8
[ "MIT" ]
5
2015-01-06T00:03:27.000Z
2015-03-06T16:35:41.000Z
games/src/test/java/com/jtbdevelopment/games/factory/gameinitializers/PlayerStateInitializerTest.java
jtbdevelopment/core-games
df74d52e944e892ee797ca87e6b4ad1798b6c1d8
[ "MIT" ]
null
null
null
35.488889
91
0.785222
999,158
package com.jtbdevelopment.games.factory.gameinitializers; import static com.jtbdevelopment.games.GameCoreTestCase.PFOUR; import static com.jtbdevelopment.games.GameCoreTestCase.PONE; import static com.jtbdevelopment.games.GameCoreTestCase.PTHREE; import static com.jtbdevelopment.games.GameCoreTestCase.PTWO; import com.jtbdevelopment.games.players.Player; import com.jtbdevelopment.games.state.PlayerState; import com.jtbdevelopment.games.stringimpl.StringMPGame; import com.jtbdevelopment.games.stringimpl.StringSPGame; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; /** * Date: 4/4/2015 Time: 8:21 PM */ public class PlayerStateInitializerTest { private PlayerStateInitializer playerStateInitializer = new PlayerStateInitializer(); @Test public void testInitializesAllPlayersToPendingAcceptingInitiatingPlayer() { final StringMPGame game = new StringMPGame(); List<Player<String>> players = Arrays.asList(PONE, PTWO, PTHREE, PFOUR); game.setPlayers(players); game.setInitiatingPlayer(PTHREE.getId()); playerStateInitializer.initializeGame(game); TestCase.assertEquals(4, game.getPlayerStates().size()); players.forEach(p -> { PlayerState expected = PTHREE.equals(p) ? PlayerState.Accepted : PlayerState.Pending; Assert.assertEquals(expected, game.getPlayerStates().get(p.getId())); }); } @Test public void testIgnoresInitializesSingePlayerGame() { StringSPGame game = new StringSPGame(); playerStateInitializer.initializeGame(game); } }
923a50cc2ad60e3273f8dca7b39c5c58d4fa96aa
6,457
java
Java
app/src/main/java/com/savor/savorphone/widget/CustomWebView.java
SavorGit/Hotspot-master-devp
e35f32e80c46ff22932e140e89ec7cf03af0acf1
[ "Apache-2.0" ]
3
2017-08-23T01:39:02.000Z
2020-08-06T14:05:25.000Z
app/src/main/java/com/savor/savorphone/widget/CustomWebView.java
SavorGit/Hotspot-master-devp
e35f32e80c46ff22932e140e89ec7cf03af0acf1
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/savor/savorphone/widget/CustomWebView.java
SavorGit/Hotspot-master-devp
e35f32e80c46ff22932e140e89ec7cf03af0acf1
[ "Apache-2.0" ]
null
null
null
31.807882
120
0.636519
999,159
package com.savor.savorphone.widget; import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.ProgressBar; import com.common.api.utils.AppUtils; import com.common.api.utils.LogUtils; import com.savor.savorphone.R; import com.savor.savorphone.activity.VideoPlayVODNotHotelActivity.UpdateProgressListener; import com.savor.savorphone.utils.ConstantValues; import java.util.HashMap; /** * 自定义webview加载网页 * Created by wmm on 16/11/21. */ public class CustomWebView extends FrameLayout implements MyWebView.OnScrollBottomListener { private MyWebView mWebView; private ProgressBar mProgressBar; private UpdateProgressListener updateProgressListener; private boolean isLoadError; public CustomWebView(Context context) { this(context, null); } public CustomWebView(Context context, AttributeSet attrs) { super(context, attrs); initViews(); } private void initViews() { LayoutInflater.from(getContext()).inflate(R.layout.view_webview, this, true); mWebView = (MyWebView) findViewById(R.id.webview); mProgressBar = (ProgressBar) findViewById(R.id.progressbar); mWebView.setWebViewClient(new MyClient()); // mWebView.setWebChromeClient(new MyWebChromeClient()); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } webSettings.setBlockNetworkImage(true); mWebView.setOnScrollBottomListener(this); webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); } /** * 滚动监听 */ public MyWebView.OnScrollBottomListener mListener; public void setOnScrollBottomListener(MyWebView.OnScrollBottomListener listener) { this.mListener = listener; } @Override public void onScrollBottom() { if(mListener!=null) { mListener.onScrollBottom(); } } public void resumeTimers() { mWebView.resumeTimers(); } // private class MyWebChromeClient extends WebChromeClient { // @Override // public void onProgressChanged(WebView view, int newProgress) { // super.onProgressChanged(view, newProgress); // //// if(newProgress >= 80&&!isLoadError &&AppUtils.isNetworkAvailable(getContext())){ //// if (mProgressBar.getVisibility() == VISIBLE){ //// //// } //// if (updateProgressListener!=null){ //// updateProgressListener.loadFinish(); //// LogUtils.d(ConstantValues.LOG_WEBVIEWmProgressBar.setVisibility(GONE);_PREFIX+" 加载超过80%"); //// } //// } // } // // } public void goBack(){ mWebView.goBack(); } public boolean canGoBack(){ return mWebView.canGoBack(); } private class MyClient extends WebViewClient{ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mWebView.getSettings().setBlockNetworkImage(false); // mProgressBar.setVisibility(VISIBLE); } @Override public void onPageFinished(WebView view, String url) { if (updateProgressListener!=null&&!isLoadError){ updateProgressListener.loadFinish(); mProgressBar.setVisibility(GONE); // LogUtils.d(ConstantValues.LOG_WEBVIEW_PREFIX+" 加载超过80%"); } LogUtils.d(ConstantValues.LOG_WEBVIEW_PREFIX+" 加载完成"); } // @Override // public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { // super.doUpdateVisitedHistory(view, url, isReload); // if (needClearHistory) { // needClearHistory = false; // mWebView.clearHistory();//清除历史记录 // } // } // @Override // public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { // super.onReceivedHttpError(view, request, errorResponse); // if (updateProgressListener!=null){ // updateProgressListener.loadHttpError(); // } // } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { LogUtils.d("savor:webview "+error.getDescription()); isLoadError = true; if (updateProgressListener!=null){ updateProgressListener.loadHttpError(); } } } public void loadUrl(String url, HashMap<String, String> headMap) { if (!TextUtils.isEmpty(url)) { if (headMap != null) { mWebView.loadUrl(url, headMap); } else { mWebView.loadUrl(url); } } } public String getUrl(){ return mWebView.getUrl(); } public void clearHistory(){ mWebView.clearCache(false); mWebView.clearHistory(); // mWebView.destroy(); } public void loadUrl(String url, HashMap<String, String> headMap , UpdateProgressListener updateAnimListener) { isLoadError = false; if (!TextUtils.isEmpty(url)) { if (headMap != null) { mWebView.loadUrl(url, headMap); } else { mWebView.loadUrl(url); } } this.updateProgressListener = updateAnimListener; } public void onDestroy() { if(mWebView!=null) { mWebView.pauseTimers(); mWebView.clearCache(true); mWebView.destroyDrawingCache(); mWebView.destroy(); mWebView = null; } } }
923a50dc9e2057abbb4904ad9604fffe520301ea
10,166
java
Java
src/org/cocos2d/tests/AtlasTest.java
Arrowofdarkness/cocos2d-android
3a62785eb212cf1fbc54fa6505c0ebdbd335e04a
[ "BSD-2-Clause-FreeBSD" ]
30
2015-09-10T10:47:44.000Z
2021-11-08T11:50:12.000Z
src/org/cocos2d/tests/AtlasTest.java
Arrowofdarkness/cocos2d-android
3a62785eb212cf1fbc54fa6505c0ebdbd335e04a
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/org/cocos2d/tests/AtlasTest.java
Arrowofdarkness/cocos2d-android
3a62785eb212cf1fbc54fa6505c0ebdbd335e04a
[ "BSD-2-Clause-FreeBSD" ]
16
2015-11-24T06:35:14.000Z
2021-06-10T08:29:27.000Z
28.880682
106
0.565709
999,160
package org.cocos2d.tests; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.view.WindowManager; import org.cocos2d.actions.interval.IntervalAction; import org.cocos2d.actions.interval.MoveBy; import org.cocos2d.actions.interval.ScaleBy; import org.cocos2d.actions.interval.Sequence; import org.cocos2d.layers.Layer; import org.cocos2d.menus.Menu; import org.cocos2d.menus.MenuItemImage; import org.cocos2d.nodes.*; import org.cocos2d.opengl.CCGLSurfaceView; import org.cocos2d.opengl.Texture2D; import org.cocos2d.opengl.TextureAtlas; import org.cocos2d.types.*; import org.cocos2d.utils.CCFormatter; import javax.microedition.khronos.opengles.GL10; public class AtlasTest extends Activity { private static final String LOG_TAG = AtlasTest.class.getSimpleName(); private CCGLSurfaceView mGLSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); mGLSurfaceView = new CCGLSurfaceView(this); setContentView(mGLSurfaceView); } static int sceneIdx = -1; static Class transitions[] = { Atlas1.class, Atlas2.class, Atlas3.class, Atlas4.class, }; @Override public void onStart() { super.onStart(); // attach the OpenGL view to a window Director.sharedDirector().attachInView(mGLSurfaceView); // set landscape mode Director.sharedDirector().setLandscape(false); // show FPS Director.sharedDirector().setDisplayFPS(true); // frames per second Director.sharedDirector().setAnimationInterval(1.0f / 60); Scene scene = Scene.node(); scene.addChild(nextAction()); // Make the Scene active Director.sharedDirector().runWithScene(scene); } @Override public void onPause() { super.onPause(); Director.sharedDirector().pause(); } @Override public void onResume() { super.onResume(); Director.sharedDirector().resume(); } @Override public void onDestroy() { super.onDestroy(); TextureManager.sharedTextureManager().removeAllTextures(); } public static final int kTagTileMap = 1; public static final int kTagSpriteManager = 1; public static final int kTagAnimation1 = 1; enum TagSprites { kTagSprite1, kTagSprite2, kTagSprite3, kTagSprite4, kTagSprite5, kTagSprite6, kTagSprite7, kTagSprite8, } static Layer nextAction() { sceneIdx++; sceneIdx = sceneIdx % transitions.length; return restartAction(); } static Layer backAction() { sceneIdx--; int total = transitions.length; if (sceneIdx < 0) sceneIdx += total; return restartAction(); } static Layer restartAction() { try { Class c = transitions[sceneIdx]; return (Layer) c.newInstance(); } catch (Exception e) { return null; } } static abstract class AtlasDemo extends Layer { TextureAtlas atlas; public AtlasDemo() { float x, y; CCSize s = Director.sharedDirector().winSize(); Label label = Label.label(title(), "DroidSans", 32); addChild(label, 1); label.setPosition(s.width / 2, s.height / 2); MenuItemImage item1 = MenuItemImage.item("b1.png", "b2.png", this, "backCallback"); MenuItemImage item2 = MenuItemImage.item("r1.png", "r2.png", this, "restartCallback"); MenuItemImage item3 = MenuItemImage.item("f1.png", "f2.png", this, "nextCallback"); Menu menu = Menu.menu(item1, item2, item3); menu.setPosition(0, 0); item1.setPosition(s.width / 2 - 100, 30); item2.setPosition(s.width / 2, 30); item3.setPosition(s.width / 2 + 100, 30); addChild(menu, 1); } public static void restartCallback() { Scene s = Scene.node(); s.addChild(restartAction()); Director.sharedDirector().replaceScene(s); } public void nextCallback() { Scene s = Scene.node(); s.addChild(nextAction()); Director.sharedDirector().replaceScene(s); } public void backCallback() { Scene s = Scene.node(); s.addChild(backAction()); Director.sharedDirector().replaceScene(s); } public abstract String title(); } static class Atlas1 extends AtlasDemo { TextureAtlas textureAtlas; public Atlas1() { textureAtlas = new TextureAtlas("atlastest.png", 3); CCQuad2 texCoords[] = new CCQuad2[]{ new CCQuad2(0.0f, 0.2f, 0.5f, 0.2f, 0.0f, 0.0f, 0.5f, 0.0f), new CCQuad2(0.2f, 0.6f, 0.6f, 0.6f, 0.2f, 0.2f, 0.6f, 0.2f), new CCQuad2(0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f), }; CCQuad3 vertices[] = new CCQuad3[]{ new CCQuad3(40, 40, 0, 120, 80, 0, 40, 160, 0, 160, 160, 0), new CCQuad3(240, 80, 0, 480, 80, 0, 180, 120, 0, 420, 120, 0), new CCQuad3(240, 140, 0, 360, 200, 0, 240, 250, 0, 360, 310, 0), }; for (int i = 0; i < 3; i++) { textureAtlas.updateQuad(texCoords[i], vertices[i], i); } textureAtlas.removeQuad(2); } public void draw(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glEnable(GL10.GL_TEXTURE_2D); textureAtlas.drawQuads(gl); // textureAtlas_.draw(gl, 3); gl.glDisable(GL10.GL_TEXTURE_2D); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); } @Override public String title() { return "Atlas: TextureAtlas"; } } static class Atlas2 extends AtlasDemo { LabelAtlas label; float time; public Atlas2() { //The size of the texture should be a power of 2 label = LabelAtlas.label("123 Test", "tuffy_bold_italic-charmap_s.png", 16, 21, ' '); addChild(label); label.setPosition(10, 100); schedule("step"); } public void step(float dt) { time += dt; label.setString(new CCFormatter().format("%2.2f Test", time)); } @Override public String title() { return "Atlas: LabelAtlas"; } } static class Atlas3 extends AtlasDemo { public Atlas3() { Log.i(LOG_TAG, "Atlas3 starts"); // TODO: This needs to be done when binding // Create an aliased Atlas Texture2D.saveTexParameters(); Texture2D.setAliasTexParameters(); TileMapAtlas tilemap = TileMapAtlas.tilemap("tiles.png", "small.tga", 16, 16); Texture2D.restoreTexParameters(); addChild(tilemap, 0, kTagTileMap); tilemap.setAnchorPoint(0, 0); IntervalAction s = ScaleBy.action(4, 0.8f); IntervalAction scaleBack = s.reverse(); IntervalAction go = MoveBy.action(8, -1650, 0); IntervalAction goBack = go.reverse(); IntervalAction seq = Sequence.actions(s, go, goBack, scaleBack); tilemap.runAction(seq); Log.i(LOG_TAG, "Atlas3 ends"); } @Override public String title() { return "Atlas: TileMapAtlas"; } } static class Atlas4 extends AtlasDemo { public Atlas4() { Log.i(LOG_TAG, "Atlas4 starts"); // Create an Aliased Atlas Texture2D.saveTexParameters(); Texture2D.setAliasTexParameters(); TileMapAtlas tilemap = TileMapAtlas.tilemap("tiles.png", "levelmap.tga", 16, 16); Texture2D.restoreTexParameters(); // If you are not going to use the Map, you can free it now // tilemap.releaseMap(); // And if you are going to use, it you can access the data with: schedule("updateMap", 0.2f); addChild(tilemap, 0, kTagTileMap); tilemap.setAnchorPoint(0, 0); tilemap.setPosition(-20, -200); Log.i(LOG_TAG, "Atlas4 starts"); } public void updateMap(float dt) { // IMPORTANT // The only limitation is that you cannot change an empty, or assign an empty tile to a tile // The value 0 is not rendered so don't assign or change a tile with value 0 TileMapAtlas tilemap = (TileMapAtlas) getChild(kTagTileMap); // For example you can iterate over all the tiles // using this code, but try to avoid the iteration // over all your tiles in every frame. It's very expensive // for(int x=0; x < tilemap.tgaInfo.width; x++) { // for(int y=0; y < tilemap.tgaInfo.height; y++) { // CCRGBB c = tilemap.tile(CCGridSize.ccg(x,y)); // if( c.r != 0 ) { // Log.w(null, "%d,%d = %d", x,y,c.r); // } // } // } CCRGBB c = tilemap.tile(CCGridSize.ccg(13, 21)); c.r++; c.r %= 50; if (c.r == 0) c.r = 1; tilemap.setTile(c, CCGridSize.ccg(13, 21)); } @Override public String title() { return "Atlas: Editable TileMapAtlas"; } } }
923a515d85a5577a85f6bb8a750b57252ef9d97a
32,225
java
Java
codec/src/main/java/org/datasand/codec/Encoder.java
saichler/DataSand
3e8ab8b2b555bd4c16c92946582dba894e7b9a52
[ "Apache-2.0" ]
null
null
null
codec/src/main/java/org/datasand/codec/Encoder.java
saichler/DataSand
3e8ab8b2b555bd4c16c92946582dba894e7b9a52
[ "Apache-2.0" ]
null
null
null
codec/src/main/java/org/datasand/codec/Encoder.java
saichler/DataSand
3e8ab8b2b555bd4c16c92946582dba894e7b9a52
[ "Apache-2.0" ]
null
null
null
36.787671
168
0.535499
999,161
/* * Copyright (c) 2015 DataSand,Sharon Aicler and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.datasand.codec; import java.io.IOException; import java.lang.reflect.Array; import java.net.Inet6Address; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.datasand.codec.serialize.ISerializer; import org.datasand.codec.serialize.SerializerGenerator; import org.datasand.codec.serialize.SerializersManager; import org.datasand.codec.serialize.StringSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author - Sharon Aicler (upchh@example.com) */ public class Encoder { public static final byte[] NULL = new byte[]{'-', 'N', 'U', 'L', 'L', '-'}; private static final SerializersManager serializersManager = new SerializersManager(); private static final Logger LOG = LoggerFactory.getLogger(Encoder.class); static { registerSerializer(String.class, new StringSerializer()); } public static final void registerSerializer(Class<?> cls, ISerializer serializer) { serializersManager.registerSerializer(cls, serializer); } public static final ISerializer getSerializerByClass(Class<?> cls) { ISerializer serializer = serializersManager.getSerializerByClass(cls); if (serializer == null) { VTable table = VSchema.instance.getVTable(cls); if (table != null) { try { serializer = SerializerGenerator.generateSerializer(table); serializersManager.registerSerializer(cls, serializer); } catch (IOException | IllegalAccessException | InstantiationException | ClassNotFoundException e) { LOG.error("Failed to create a serializer to class " + cls.getName(), e); } } } return serializer; } public static final Class<?> getClassByMD5(MD5ID id) { return serializersManager.getClassByMD5(id); } public static final MD5ID getMD5ByClass(Class<?> cls) { return serializersManager.getMD5ByClass(cls); } //Object public static final void encodeObject(Object value, BytesArray ba) { if (ba instanceof HierarchyBytesArray && ba.getLocation() != 0) { HierarchyBytesArray hba = (HierarchyBytesArray) ba; ba = hba.addNewChild(); } if (value == null) { encodeNULL(ba); } else { ba.adjustSize(16); MD5ID id = serializersManager.getMD5ByObject(value); encodeInt64(id.getMd5Long1(), ba); encodeInt64(id.getMd5Long2(), ba); if (ba instanceof HierarchyBytesArray) { ((HierarchyBytesArray) ba).setJavaTypeMD5(id); } ISerializer serializer = serializersManager.getSerializerByMD5(id); serializer.encode(value, ba); } } public static final Object decodeObject(BytesArray ba) { if (ba == null) { return null; } else if (ba instanceof HierarchyBytesArray && ba.getLocation() > 0) { HierarchyBytesArray hba = (HierarchyBytesArray) ba; ba = hba.nextChild(); } if (isNULL(ba)) { return null; } else { if (ba.getBytes().length == 0) { return null; } try { long a = decodeInt64(ba); long b = decodeInt64(ba); ISerializer serializer = serializersManager.getSerializerByLongs(a, b); return serializer.decode(ba); } catch (Exception err) { err.printStackTrace(); return null; } } } //INT16 public static final void encodeInt16(int value, byte[] byteArray, int location) { byteArray[location + 1] = (byte) (value >> 8); byteArray[location] = (byte) (value); } public static final int decodeInt16(byte[] byteArray, int location) { int value = 0; if (byteArray[location] > 0) { value += ((int) byteArray[location] & 0xFFL); } else { value += ((int) (256 + byteArray[location]) & 0xFFL); } if (byteArray[location + 1] > 0) { value += ((int) byteArray[location + 1] & 0xFFL) << (8); } else { value += ((int) (256 + byteArray[location + 1]) & 0xFFL) << (8); } return value; } public static final void encodeInt16(int value, BytesArray ba) { ba.adjustSize(2); encodeInt16(value, ba.getBytes(), ba.getLocation()); ba.advance(2); } public static final int decodeInt16(BytesArray ba) { int value = decodeInt16(ba.getBytes(), ba.getLocation()); ba.advance(2); return value; } //INT32 public static final void encodeInt32(int value, byte byteArray[], int location) { byteArray[location] = (byte) ((value >> 24) & 0xff); byteArray[location + 1] = (byte) ((value >> 16) & 0xff); byteArray[location + 2] = (byte) ((value >> 8) & 0xff); byteArray[location + 3] = (byte) ((value) & 0xff); } public static final int decodeInt32(byte[] byteArray, int location) { return (int) (0xff & byteArray[location]) << 24 | (int) (0xff & byteArray[location + 1]) << 16 | (int) (0xff & byteArray[location + 2]) << 8 | (int) (0xff & byteArray[location + 3]); } public static final void encodeInt32(Integer value, BytesArray ba) { if (value == null) value = 0; ba.adjustSize(4); encodeInt32(value, ba.getBytes(), ba.getLocation()); ba.advance(4); } public static final int decodeInt32(BytesArray ba) { int value = decodeInt32(ba.getBytes(), ba.getLocation()); ba.advance(4); return value; } //INT64 - long public static final void encodeInt64(long value, byte[] byteArray, int location) { byteArray[location] = (byte) ((value >> 56) & 0xff); byteArray[location + 1] = (byte) ((value >> 48) & 0xff); byteArray[location + 2] = (byte) ((value >> 40) & 0xff); byteArray[location + 3] = (byte) ((value >> 32) & 0xff); byteArray[location + 4] = (byte) ((value >> 24) & 0xff); byteArray[location + 5] = (byte) ((value >> 16) & 0xff); byteArray[location + 6] = (byte) ((value >> 8) & 0xff); byteArray[location + 7] = (byte) ((value) & 0xff); } public static final long decodeInt64(byte[] byteArray, int location) { return (long) (0xff & byteArray[location]) << 56 | (long) (0xff & byteArray[location + 1]) << 48 | (long) (0xff & byteArray[location + 2]) << 40 | (long) (0xff & byteArray[location + 3]) << 32 | (long) (0xff & byteArray[location + 4]) << 24 | (long) (0xff & byteArray[location + 5]) << 16 | (long) (0xff & byteArray[location + 6]) << 8 | (long) (0xff & byteArray[location + 7]); } public static final void encodeInt64(Long value, BytesArray ba) { if (value == null) value = 0L; ba.adjustSize(8); encodeInt64(value, ba.getBytes(), ba.getLocation()); ba.advance(8); } public static final long decodeInt64(BytesArray ba) { long value = decodeInt64(ba.getBytes(), ba.getLocation()); ba.advance(8); return value; } //NULL public static final void encodeNULL(BytesArray ba) { ba.adjustSize(NULL.length); System.arraycopy(NULL, 0, ba.getBytes(), ba.getLocation(), NULL.length); ba.advance(NULL.length); } public static final boolean isNULL(BytesArray ba) { if (ba.getBytes().length < ba.getLocation() + NULL.length) { return false; } for (int i = 0; i < NULL.length; i++) { if (ba.getBytes()[ba.getLocation() + i] != NULL[i]) { return false; } } ba.advance(NULL.length); return true; } //String public static final void encodeString(String value, byte[] byteArray, int location) { byte bytes[] = value.getBytes(); encodeInt16(bytes.length, byteArray, location); System.arraycopy(bytes, 0, byteArray, location + 2, bytes.length); } public static final String decodeString(byte[] byteArray, int location) { int size = decodeInt16(byteArray, location); return new String(byteArray, location + 2, size); } public static final void encodeString(String value, BytesArray ba) { if (value == null) { encodeNULL(ba); } else { int size = value.getBytes().length + 2; ba.adjustSize(size); encodeString(value, ba.getBytes(), ba.getLocation()); ba.advance(size); } } public static final String decodeString(BytesArray ba) { if (isNULL(ba)) { return null; } int size = decodeInt16(ba.getBytes(), ba.getLocation()); String result = new String(ba.getBytes(), ba.getLocation() + 2, size); ba.advance(size + 2); return result; } //Short public static final void encodeShort(short value, byte[] byteArray, int location) { byteArray[location + 1] = (byte) (value >> 8); byteArray[location] = (byte) (value); } public static final short decodeShort(byte[] byteArray, int location) { short value = 0; if (byteArray[location] > 0) { value += ((int) byteArray[location] & 0xFFL); } else { value += ((int) (256 + byteArray[location]) & 0xFFL); } if (byteArray[location + 1] > 0) { value += ((int) byteArray[location + 1] & 0xFFL) << (8 * (1)); } else { value += ((int) (256 + byteArray[location + 1]) & 0xFFL) << (8 * (1)); } return value; } public static final void encodeShort(Short value, BytesArray ba) { if (value == null) value = 0; ba.adjustSize(2); encodeShort(value, ba.getBytes(), ba.getLocation()); ba.advance(2); } public static final short decodeShort(BytesArray ba) { short value = decodeShort(ba.getBytes(), ba.getLocation()); ba.advance(2); return value; } //Byte Array public static final void encodeByteArray(byte[] value, byte byteArray[], int location) { encodeInt32(value.length, byteArray, location); System.arraycopy(value, 0, byteArray, location + 4, value.length); } public static final byte[] decodeByteArray(byte[] byteArray, int location) { int size = decodeInt32(byteArray, location); byte array[] = new byte[size]; System.arraycopy(byteArray, location + 4, array, 0, array.length); return array; } public static final void encodeByteArray(byte[] value, BytesArray ba) { if (value == null) { encodeNULL(ba); } else { ba.adjustSize(value.length + 4); encodeByteArray(value, ba.getBytes(), ba.getLocation()); ba.advance(value.length + 4); } } public static final byte[] decodeByteArray(BytesArray ba) { if (isNULL(ba)) { return null; } byte[] array = decodeByteArray(ba.getBytes(), ba.getLocation()); ba.advance(array.length + 4); return array; } //Boolean public static final void encodeBoolean(boolean value, byte[] byteArray, int location) { if (value) byteArray[location] = 1; else byteArray[location] = 0; } public static final boolean decodeBoolean(byte[] byteArray, int location) { if (byteArray[location] == 1) return true; else return false; } public static final void encodeBoolean(Boolean value, BytesArray ba) { if (value == null) value = false; ba.adjustSize(1); encodeBoolean(value, ba.getBytes(), ba.getLocation()); ba.advance(1); } public static final Boolean decodeBoolean(BytesArray ba) { boolean result = decodeBoolean(ba.getBytes(), ba.getLocation()); ba.advance(1); return result; } //Byte public static final void encodeByte(Byte value, BytesArray ba) { if (value == null) value = (byte) 0; ba.adjustSize(1); ba.getBytes()[ba.getLocation()] = value; ba.advance(1); } public static final byte decodeByte(BytesArray ba) { ba.advance(1); return ba.getBytes()[ba.getLocation() - 1]; } //Int array public static final void encodeIntArray(int value[], BytesArray ba) { if (value == null) { encodeNULL(ba); } else { encodeInt32(value.length, ba); for (int i = 0; i < value.length; i++) { encodeInt32(value[i], ba); } } } public static final int[] decodeIntArray(BytesArray ba) { if (isNULL(ba)) { return null; } int size = decodeInt32(ba); int result[] = new int[size]; for (int i = 0; i < result.length; i++) { result[i] = decodeInt32(ba); } return result; } //Array of objects public static final void encodeArray(Object value[], BytesArray ba) { if (value == null) { encodeNULL(ba); } else { encodeInt32(value.length, ba); MD5ID id = serializersManager.getMD5ByClass(value.getClass().getComponentType()); encodeInt64(id.getMd5Long1(), ba); encodeInt64(id.getMd5Long2(), ba); ISerializer serializer = serializersManager.getSerializerByMD5(id); for (int i = 0; i < value.length; i++) { serializer.encode(value[i], ba); } } } public static final Object[] decodeArray(BytesArray ba) { if (isNULL(ba)) { return null; } int size = decodeInt32(ba); long a = decodeInt64(ba); long b = decodeInt64(ba); MD5ID id = MD5ID.create(a, b); ISerializer serializer = serializersManager.getSerializerByMD5(id); Class cls = serializersManager.getClassByMD5(id); Object result[] = (Object[]) Array.newInstance(cls, size); for (int i = 0; i < result.length; i++) { result[i] = serializer.decode(ba); } return result; } //List public static final void encodeList(List<?> list, BytesArray ba) { if (ba instanceof HierarchyBytesArray && ba.getLocation() != 0) { HierarchyBytesArray hba = (HierarchyBytesArray) ba; ba = hba.addNewChild(); } if (list == null || list.size() == 0) { encodeNULL(ba); } else { encodeInt32(list.size(), ba); MD5ID id = serializersManager.getMD5ByClass(list.get(0).getClass()); encodeInt64(id.getMd5Long1(), ba); encodeInt64(id.getMd5Long2(), ba); if (ba instanceof HierarchyBytesArray) { ((HierarchyBytesArray) ba).setJavaTypeMD5(id); } ISerializer serializer = serializersManager.getSerializerByMD5(id); for (Object o : list) { serializer.encode(o, ba); } } } public static final List<?> decodeList(BytesArray ba) { if (ba instanceof HierarchyBytesArray && ba.getLocation() > 0) { HierarchyBytesArray hba = (HierarchyBytesArray) ba; ba = hba.nextChild(); } if (isNULL(ba)) { return null; } int size = decodeInt32(ba); long a = decodeInt64(ba); long b = decodeInt64(ba); MD5ID id = MD5ID.create(a, b); ISerializer serializer = serializersManager.getSerializerByMD5(id); List result = new ArrayList(size); for (int i = 0; i < size; i++) { result.add(serializer.decode(ba)); } return result; } /* public int decodeUInt32(byte[] byteArray, int location) { int value = 0; if (byteArray[location] > 0) { value += ((int) byteArray[location] & 0xFFL); } else { value += ((int) (256 + byteArray[location]) & 0xFFL); } if (byteArray[location + 1] > 0) { value += ((int) byteArray[location + 1] & 0xFFL) << (8 * (1)); } else { value += ((int) (256 + byteArray[location + 1]) & 0xFFL) << (8 * (1)); } if (byteArray[location + 2] > 0) { value += ((int) byteArray[location + 2] & 0xFFL) << (8 * (2)); } else { value += ((int) (256 + byteArray[location + 2]) & 0xFFL) << (8 * (2)); } if (byteArray[location + 3] > 0) { value += ((int) byteArray[location + 3] & 0xFFL) << (8 * (3)); } else { value += ((int) (256 + byteArray[location + 3]) & 0xFFL) << (8 * (3)); } return value; } public void encodeBigDecimal(BigDecimal value, EncodeDataContainer ba) { if(value==null){ encodeNULL(ba); return; } encodeString(value.toString(), ba); /* The method Double.doubleToLongBits is EXTREMELY slow! Need * To find other solution to that * long longValue = Double.doubleToLongBits(value.doubleValue()); ba.adjustSize(8); encodeInt64(longValue, ba.getBytes(), ba.getLocation()); ba.advance(8); } public BigDecimal decodeBigDecimal(EncodeDataContainer ba){ if(isNULL(ba)) return null; return new BigDecimal(decodeString(ba)); /* long longValue = decodeInt64(ba); return new BigDecimal(Double.longBitsToDouble(longValue)); } public long decodeUInt64(byte[] byteArray, int location) { long value = 0; if (byteArray[location] > 0) { value += ((long) byteArray[location] & 0xFFL); } else { value += ((long) (256 + byteArray[location]) & 0xFFL); } if (byteArray[location + 1] > 0) { value += ((long) byteArray[location + 1] & 0xFFL) << (8 * (1)); } else { value += ((long) (256 + byteArray[location + 1]) & 0xFFL) << (8 * (1)); } if (byteArray[location + 2] > 0) { value += ((long) byteArray[location + 2] & 0xFFL) << (8 * (2)); } else { value += ((long) (256 + byteArray[location + 2]) & 0xFFL) << (8 * (2)); } if (byteArray[location + 3] > 0) { value += ((long) byteArray[location + 3] & 0xFFL) << (8 * (3)); } else { value += ((long) (256 + byteArray[location + 3]) & 0xFFL) << (8 * (3)); } if (byteArray[location + 4] > 0) { value += ((long) byteArray[location + 4] & 0xFFL) << (8 * (4)); } else { value += ((long) (256 + byteArray[location + 4]) & 0xFFL) << (8 * (4)); } if (byteArray[location + 5] > 0) { value += ((long) byteArray[location + 5] & 0xFFL) << (8 * (5)); } else { value += ((long) (256 + byteArray[location + 5]) & 0xFFL) << (8 * (5)); } if (byteArray[location + 6] > 0) { value += ((long) byteArray[location + 6] & 0xFFL) << (8 * (6)); } else { value += ((long) (256 + byteArray[location + 6]) & 0xFFL) << (8 * (6)); } if (byteArray[location + 7] > 0) { value += ((long) byteArray[location + 7] & 0xFFL) << (8 * (7)); } else { value += ((long) (256 + byteArray[location + 7]) & 0xFFL) << (8 * (7)); } return value; } public void encodeAugmentations(Object value, EncodeDataContainer ba) { IAugmetationObserver ao = ba.getTypeDescriptorContainer().getAugmentationObserver(); if(ao!=null){ ao.encodeAugmentations(value, ba); } } public void decodeAugmentations(Object builder, EncodeDataContainer ba,Class<?> augmentedClass) { IAugmetationObserver ao = ba.getTypeDescriptorContainer().getAugmentationObserver(); if(ao!=null){ ao.decodeAugmentations(builder, ba, augmentedClass); } } /* public void encodeAndAddObject(Object value, EncodeDataContainer _ba,Class<?> objectType) { BytesArray ba = (BytesArray)_ba; if (value == null) { encodeNULL(ba); } else { VTable tbl = ba.getTypeDescriptorContainer().getTypeDescriptorByClass(objectType); int classCode = tbl.getClassCode(); encodeInt16(classCode,ba); EncodeDataContainer subBA = new BytesArray(1024,ba.getTypeDescriptorContainer().getTypeDescriptorByCode(classCode)); ISerializer serializer = getSerializer(objectType,ba.getTypeDescriptorContainer()); if (serializer != null) { encodeInt16(classCode, subBA); serializer.encode(value, subBA); ba.addSubElementData(classCode, subBA,tbl.getMD5IDForObject(value)); } else { System.err.println("Can't find a serializer for " + objectType); } } } public void encodeObject(Object value, EncodeDataContainer ba,Class<?> objectType) { if(value instanceof String){ encodeInt16(FrameworkClassCodes.CODE_String,ba); encodeString((String)value, ba); return; }else if(value instanceof Integer){ encodeInt16(FrameworkClassCodes.CODE_Integer,ba); encodeInt32((Integer)value,ba); return; }else if(value instanceof Long){ encodeInt16(FrameworkClassCodes.CODE_Long,ba); encodeInt64((Long)value,ba); return; }else if(value instanceof List){ encodeInt16(FrameworkClassCodes.CODE_List, ba); encodeList((List<?>)value, ba); return; } if (value == null) { encodeNULL(ba); return; } if(objectType==null) objectType = value.getClass(); ISerializer serializer = getSerializer(objectType,ba.getTypeDescriptorContainer()); if (serializer != null) { Integer classCode = registeredSerializersClassCode.get(objectType); if(classCode==null){ classCode = ba.getTypeDescriptorContainer().getTypeDescriptorByClass(objectType).getClassCode(); } if(classCode==null){ System.err.println("Unable To find a code for this class:"+objectType.getName()); return; } encodeInt16(classCode, ba); serializer.encode(value, ba); } else { System.err.println("Can't find a serializer for " + objectType); } }*/ /* public Object decodeObject(EncodeDataContainer ba) { if (isNULL(ba)) { return null; } int classCode = decodeInt16(ba); if(classCode==FrameworkClassCodes.CODE_String){ return decodeString(ba); }else if(classCode==FrameworkClassCodes.CODE_Integer){ return decodeInt32(ba); }else if(classCode==FrameworkClassCodes.CODE_Long){ return decodeInt64(ba); }else if(classCode==FrameworkClassCodes.CODE_List){ return decodeList(ba); } ISerializer serializer = getSerializer(classCode,ba.getTypeDescriptorContainer()); if (serializer == null) { VTable ts = ba.getTypeDescriptorContainer().getTypeDescriptorByCode(classCode); if(ts!=null) ts.getJavaClassType(); else System.err.println("Missing class code="+classCode); } if (serializer != null) { return serializer.decode(ba, 0); } else { System.err.println("Missing class code=" + classCode); } return null; }*/ /* public Object decodeAndObject(EncodeDataContainer _ba) { BytesArray ba = (BytesArray)_ba; if (isNULL(ba)) { return null; } int classCode = decodeInt16(ba); ISerializer serializer = getSerializer(classCode,ba.getTypeDescriptorContainer()); if (serializer == null) { ba.getTypeDescriptorContainer().getTypeDescriptorByCode(classCode).getJavaClassType(); } if (serializer != null) { if(ba.getSubElementsData().get(classCode)!=null){ BytesArray subBA = (BytesArray)ba.getSubElementsData().get(classCode).get(0); subBA.advance(2); return serializer.decode(subBA, 0); }else return null; } else { System.err.println("Missing class code=" + classCode); } return null; } public void encodeArray(Object value[], EncodeDataContainer ba,Class<?> componentType) { if (value == null) { encodeNULL(ba); } else { encodeInt32(value.length, ba); for (int i = 0; i < value.length; i++) { if (String.class.equals(componentType)) { encodeString((String) value[i], ba); } else if (ISerializer.class.isAssignableFrom(componentType)) { ((ISerializer) value[i]).encode(value[i], ba); } else { encodeObject(value[i], ba, componentType); } } } } public void encodeList(List<?> list, EncodeDataContainer ba) { if (list == null) { encodeNULL(ba); } else { encodeInt32(list.size(), ba); for (Object o: list) { encodeObject(o, ba, null); } } } public void encodeAndAddList(List<?> list, EncodeDataContainer ba,Class<?> componentType) { if (list == null) { encodeNULL(ba); } else { encodeInt32(list.size(), ba); int componentCode = ba.getTypeDescriptorContainer().getTypeDescriptorByClass(componentType).getClassCode(); for (Object o: list) { BytesArray subBA = new BytesArray(1024,ba.getTypeDescriptorContainer().getTypeDescriptorByCode(componentCode)); if (String.class.equals(componentType)) { encodeString((String) o, subBA); } else if (ISerializer.class.isAssignableFrom(componentType)) { ((ISerializer) o).encode(o, subBA); } else { encodeObject(o, subBA, componentType); } ba.addSubElementData(componentCode, subBA,o); } } } public List<Object> decodeList(EncodeDataContainer ba,Class<?> componentType) { if (isNULL(ba)) { return null; } int size = decodeInt32(ba); List<Object> result = new ArrayList<Object>(size); for (int i = 0; i < size; i++) { if (int.class.equals(componentType)) { result.add(decodeInt32(ba)); } else if (long.class.equals(componentType)) { result.add(decodeInt64(ba)); } else if (boolean.class.equals(componentType)) { result.add(decodeBoolean(ba)); } else if (String.class.equals(componentType)) { result.add(decodeString(ba)); } else if (ISerializer.class.isAssignableFrom(componentType)) { ISerializer serializer = getSerializer(componentType,ba.getTypeDescriptorContainer()); if (serializer != null) { result.add(serializer.decode(ba, 0)); } else { System.err.println("Can't find Serializer for class:" + componentType.getName()); } } else { result.add(decodeObject(ba)); } } return result; } public List decodeAndList(EncodeDataContainer ba,Class<?> componentType) { if (isNULL(ba)) { return null; } int size = decodeInt32(ba); List result = new ArrayList(size); List<EncodeDataContainer> subElementData = ba.getSubElementsData().get(ba.getTypeDescriptorContainer().getTypeDescriptorByClass(componentType).getClassCode()); if(subElementData!=null){ for (int i = 0; i < subElementData.size(); i++) { EncodeDataContainer subBA = subElementData.get(i); if (int.class.equals(componentType)) { result.add(decodeInt32(subBA)); } else if (long.class.equals(componentType)) { result.add(decodeInt64(subBA)); } else if (boolean.class.equals(componentType)) { result.add(decodeBoolean(subBA)); } else if (String.class.equals(componentType)) { result.add(decodeString(subBA)); } else if (ISerializer.class.isAssignableFrom(componentType)) { ISerializer serializer = getSerializer(componentType,ba.getTypeDescriptorContainer()); if (serializer != null) { result.add(serializer.decode(subBA, 0)); } else { System.err.println("Can't find Serializer for class:" + componentType.getName()); } } else { result.add(decodeObject(subBA)); } } } if(result.size()==0) return null; return result; }*/ public static String getLocalIPAddress() { try { for (NetworkInterface in : Collections.list(NetworkInterface .getNetworkInterfaces())) { if (in.isLoopback()) continue; if (!in.isUp()) continue; if (in.isVirtual()) continue; if (in.getDisplayName().indexOf("vm") != -1) continue; for (InterfaceAddress addr : in.getInterfaceAddresses()) { if (addr.getAddress() instanceof Inet6Address) continue; if (!addr.getAddress().getHostAddress().startsWith("127.0")) { return addr.getAddress().getHostAddress(); } } } } catch (Exception err) { err.printStackTrace(); } return null; } }
923a520ef667f838c389084af6c3746baebe9152
3,446
java
Java
jackson-apt-processor/src/main/java/org/dominokit/jacksonapt/processor/AbstractMapperProcessor.java
treblereel/domino-jackson
87b4ffced8ac5d3569a93990f2e21a34dac9d983
[ "Apache-2.0" ]
null
null
null
jackson-apt-processor/src/main/java/org/dominokit/jacksonapt/processor/AbstractMapperProcessor.java
treblereel/domino-jackson
87b4ffced8ac5d3569a93990f2e21a34dac9d983
[ "Apache-2.0" ]
null
null
null
jackson-apt-processor/src/main/java/org/dominokit/jacksonapt/processor/AbstractMapperProcessor.java
treblereel/domino-jackson
87b4ffced8ac5d3569a93990f2e21a34dac9d983
[ "Apache-2.0" ]
1
2020-03-05T23:52:10.000Z
2020-03-05T23:52:10.000Z
32.205607
119
0.691817
999,162
package org.dominokit.jacksonapt.processor; import org.dominokit.jacksonapt.annotation.JSONMapper; import org.dominokit.jacksonapt.annotation.JSONReader; import org.dominokit.jacksonapt.annotation.JSONWriter; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * <p>Abstract AbstractMapperProcessor class.</p> * * @author vegegoku * @version $Id: $Id */ public abstract class AbstractMapperProcessor extends AbstractProcessor { /** Constant <code>messager</code> */ public static Messager messager; /** Constant <code>typeUtils</code> */ public static Types typeUtils; /** Constant <code>filer</code> */ public static Filer filer; /** Constant <code>elementUtils</code> */ public static Elements elementUtils; public static ProcessingEnvironment environment; protected Set<? extends Element> mappers; protected Set<? extends Element> readers; protected Set<? extends Element> writers; /** {@inheritDoc} */ @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); environment = processingEnv; filer = processingEnv.getFiler(); messager = processingEnv.getMessager(); typeUtils = processingEnv.getTypeUtils(); elementUtils = processingEnv.getElementUtils(); } /** {@inheritDoc} */ @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { TypeRegistry.resetTypeRegistry(); return false; } mappers = roundEnv.getElementsAnnotatedWith(JSONMapper.class); readers = roundEnv.getElementsAnnotatedWith(JSONReader.class); writers = roundEnv.getElementsAnnotatedWith(JSONWriter.class); return doProcess(annotations, roundEnv); } /** * <p>doProcess.</p> * * @param annotations a {@link java.util.Set} object. * @param roundEnv a {@link javax.annotation.processing.RoundEnvironment} object. * @return a boolean. */ protected abstract boolean doProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv); /** * <p>handleError.</p> * * @param e a {@link java.lang.Exception} object. */ protected void handleError(Exception e) { StringWriter out = new StringWriter(); e.printStackTrace(new PrintWriter(out)); messager.printMessage(Diagnostic.Kind.ERROR, "error while creating source file " + out.getBuffer().toString()); } /** {@inheritDoc} */ @Override public Set<String> getSupportedAnnotationTypes() { return supportedAnnotations().stream() .map(Class::getCanonicalName).collect(Collectors.toSet()); } /** {@inheritDoc} */ @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } /** * <p>supportedAnnotations.</p> * * @return a {@link java.util.List} object. */ protected abstract List<Class<?>> supportedAnnotations(); }