hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
e8b6abcc280f44e51868e296f6f14ee95504a544
2,206
/* * Copyright 2015 Open Networking Laboratory * * 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.onosproject.pcepio.types; import com.google.common.testing.EqualsTester; import org.junit.Test; import java.util.LinkedList; /** * Test of the LocalTENodeDescriptorsTlv. */ public class LocalTENodeDescriptorsTlvTest { private final AutonomousSystemTlv baAutoSysTlvRawValue1 = new AutonomousSystemTlv(1); private final BGPLSidentifierTlv baBgplsIdRawValue1 = new BGPLSidentifierTlv(1); private final AutonomousSystemTlv baAutoSysTlvRawValue2 = new AutonomousSystemTlv(2); private final BGPLSidentifierTlv baBgplsIdRawValue2 = new BGPLSidentifierTlv(2); private final LinkedList<PcepValueType> llNodeDescriptorSubTLVs1 = new LinkedList<PcepValueType>(); private final boolean a = llNodeDescriptorSubTLVs1.add(baAutoSysTlvRawValue1); private final boolean b = llNodeDescriptorSubTLVs1.add(baBgplsIdRawValue1); private final LinkedList<PcepValueType> llNodeDescriptorSubTLVs2 = new LinkedList<PcepValueType>(); private final boolean c = llNodeDescriptorSubTLVs2.add(baAutoSysTlvRawValue2); private final boolean d = llNodeDescriptorSubTLVs2.add(baBgplsIdRawValue2); private final LocalTENodeDescriptorsTlv tlv1 = LocalTENodeDescriptorsTlv.of(llNodeDescriptorSubTLVs1); private final LocalTENodeDescriptorsTlv sameAstlv1 = LocalTENodeDescriptorsTlv.of(llNodeDescriptorSubTLVs1); private final LocalTENodeDescriptorsTlv tlv2 = LocalTENodeDescriptorsTlv.of(llNodeDescriptorSubTLVs2); @Test public void basics() { new EqualsTester().addEqualityGroup(tlv1, sameAstlv1).addEqualityGroup(tlv2).testEquals(); } }
43.254902
112
0.790571
778477e8993f68372ab0446faeef882a8fcfa42b
611
package au.com.totemsoft.shoppingcart.domain; import java.util.ArrayList; import java.util.List; import java.util.UUID; //@lombok.Data public class ShoppingCart { private final UUID id; private final List<ShoppingCartItem> items = new ArrayList<>(); public ShoppingCart() { this.id = UUID.randomUUID(); } public ShoppingCart(UUID id) { this.id = id; } public UUID getId() { return id; } public List<ShoppingCartItem> getItems() { return items; } @Override public String toString() { return id.toString(); } }
16.972222
67
0.621931
099f6ec46082517d8c27fa72ab4ab3db4aa9f87f
3,589
/* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 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. 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.amazonaws.partners.saasfactory.metering.common; import java.time.Instant; public class BillingEvent implements Comparable<BillingEvent> { private final Instant eventTime; private final String tenantID; private final Long quantity; private final String nonce; private BillingEvent(String tenantID, Instant eventTime, Long quantity, String nonce) { this.eventTime = eventTime; this.tenantID = tenantID; this.quantity = quantity; this.nonce = nonce; } public static BillingEvent createBillingEvent(String tenantID, Instant eventTime, Long quantity) { return new BillingEvent(tenantID, eventTime, quantity, ""); } public static BillingEvent createBillingEvent(String tenantID, Instant eventTime, Long quantity, String nonce) { return new BillingEvent(tenantID, eventTime, quantity, nonce); } public static BillingEvent createBillingEvent(EventBridgeBillingEvent event) { String tenantID = event.getDetail().getTenantID(); if (tenantID == null || tenantID.isEmpty()) { return null; } Long quantity = event.getDetail().getQuantity(); if (quantity == null || quantity <= 0) { return null; } Instant timestamp = Instant.now(); return new BillingEvent(tenantID, timestamp, quantity, ""); } public Instant getEventTime() { return this.eventTime; } public String getTenantID() { return this.tenantID; } public Long getQuantity() { return this.quantity; } public String getNonce() { return this.nonce; } @Override public int compareTo(BillingEvent event) { return this.eventTime.compareTo(event.eventTime); } @Override public boolean equals(Object o) { if (o == null) { return false; } if (o.getClass() != this.getClass()) { return false; } if (o == this) { return true; } BillingEvent event = (BillingEvent) o; return this.eventTime.equals(event.eventTime) && this.tenantID.equals(event.tenantID) && this.quantity.equals(event.quantity) && this.nonce.equals(event.nonce); } @Override public int hashCode() { return this.eventTime.hashCode() + this.tenantID.hashCode() + this.quantity.hashCode() + this.nonce.hashCode(); } }
33.542056
116
0.641126
29bf95462a006750879ec421ee7995d59b2c96ce
1,272
package b01.l3; import b01.foc.gui.FGCheckBox; import b01.foc.gui.FPanel; import b01.foc.gui.FValidationPanel; @SuppressWarnings("serial") public class L3ApplicationGuiDetailsPanel extends FPanel{ public L3ApplicationGuiDetailsPanel (int view, L3Application application){ add(application, L3ApplicationDesc.FLD_APPLICATION_MODE, 0, 0); FGCheckBox box = (FGCheckBox) add(application, L3ApplicationDesc.FLD_LAUNCH_AS_SERVICES, 0, 1); box.setText(""); box = (FGCheckBox) add(application, L3ApplicationDesc.FLD_AUTOMATIC_PURGE, 0, 2); box.setText(""); add(application, L3ApplicationDesc.FLD_PURGE_NBR_DAYS_TO_KEEP, 0, 3); add(application, L3ApplicationDesc.FLD_PURGE_NBR_DAYS_TO_KEEP_FOR_COMMITED, 0, 4); box = (FGCheckBox) add(application, L3ApplicationDesc.FLD_KEEP_FILES_FOR_DEBUG, 0, 5); box.setText(""); add(application, L3ApplicationDesc.FLD_APPLICATION_DIRECTORY, 0, 6); add(application, L3ApplicationDesc.FLD_REMOTE_LAUNCHER_HOST, 0, 7); add(application, L3ApplicationDesc.FLD_REMOTE_LAUNCHER_PORT, 0, 8); FValidationPanel validPanel = showValidationPanel(true); validPanel.addSubject(application); setFrameTitle("General Configuration"); } public void dispose(){ super.dispose(); } }
38.545455
99
0.761792
ecaaaffff30e4e1f0347819dca78789224945beb
9,948
package com.example; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin @RequestMapping("/api/visites") public class VisiteDAO implements DAO<Visite>{ @Autowired private DataSource dataSource; @GetMapping("/") public ArrayList<Visite> allUsers(HttpServletResponse response) { try (Connection connection = dataSource.getConnection()){ Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM visites"); ArrayList<Visite> L = new ArrayList<Visite>(); while(rs.next()){ Visite v = new Visite(null,null, null, null, null, null, 0, 0, null, null); v.setVisiteId(rs.getString("visiteId")); v.setDefiId(rs.getString("defiId")); v.setVisiteur(rs.getString("visiteur")); v.setDateVisite(rs.getString("dateVisite")); v.setModeVisite(rs.getString("modeVisite")); v.setStatus(rs.getString("status")); v.setScore(rs.getInt("score")); v.setTemps(rs.getInt("temps")); v.setEvalution(rs.getString("evaluation")); v.setCommentaire(rs.getString("commentaire")); L.add(v); } return L; }catch(Exception e){ response.setStatus(500); try { response.getOutputStream().print( e.getMessage()); }catch(Exception e2){ System.err.println(e2.getMessage()); } System.err.println(e.getMessage()); return null; } } @PostMapping("/{visiteId}") public Visite create(@PathVariable(value="userId") String id, @RequestBody Visite v, HttpServletResponse response){ try (Connection connection = dataSource.getConnection()){ if(! v.getVisiteId().equals(id) ){ response.setStatus(412); return null; } else if( read(v.getVisiteId(), response) != null){ response.setStatus(403); return null; } else if (read(v.getVisiteId(), response) == null){ Statement stmt = connection.createStatement(); stmt.executeUpdate("INSERT INTO visites VALUES ( '"+v.getVisiteId()+"' ,'"+v.getDefiId()+"','"+v.getVisiteur()+"',TO_TIMESTAMP('"+v.getDateVisite()+"','YYYY-MM-DD HH:MI:SS'),'"+v.getModeVisite()+"','"+v.getStatus()+"','"+v.getScore()+"','"+v.getTemps()+"','"+v.getEvalution()+"','"+v.getCommentaire()+"')"); ResultSet rs = stmt.executeQuery("SELECT * FROM visites WHERE visiteId = '"+v.getVisiteId()+"'"); Visite visiteCreated = new Visite(null,null, null, null, null, null, 0, 0, null, null); rs.next(); visiteCreated.setVisiteId(rs.getString("visiteId")); visiteCreated.setDefiId(rs.getString("defiId")); visiteCreated.setVisiteur(rs.getString("visiteur")); visiteCreated.setDateVisite(rs.getString("dateVisite")); visiteCreated.setModeVisite(rs.getString("modeVisite")); visiteCreated.setStatus(rs.getString("status")); visiteCreated.setScore(rs.getInt("score")); visiteCreated.setTemps(rs.getInt("temps")); visiteCreated.setEvalution(rs.getString("evaluation")); visiteCreated.setCommentaire(rs.getString("commentaire")); response.setStatus(200); return visiteCreated; } else{ return null; } }catch(Exception e){ response.setStatus(500); try { response.getOutputStream().print( e.getMessage()); }catch(Exception e2){ System.err.println(e2.getMessage()); } System.err.println(e.getMessage()); return null; } } @Override @GetMapping("/{visiteId}") public Visite read(@PathVariable(value="userId") String id, HttpServletResponse response){ try (Connection connection = dataSource.getConnection()){ Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM visites WHERE visiteId = '"+id+"'"); Visite visiteReaded= new Visite(null,null, null, null, null, null, 0, 0, null, null); if(rs.next()){ visiteReaded.setVisiteId(rs.getString("visiteId")); visiteReaded.setDefiId(rs.getString("defiId")); visiteReaded.setVisiteur(rs.getString("visiteur")); visiteReaded.setDateVisite(rs.getString("dateVisite")); visiteReaded.setModeVisite(rs.getString("modeVisite")); visiteReaded.setStatus(rs.getString("status")); visiteReaded.setScore(rs.getInt("score")); visiteReaded.setTemps(rs.getInt("temps")); visiteReaded.setEvalution(rs.getString("evaluation")); visiteReaded.setCommentaire(rs.getString("commentaire")); return visiteReaded; }else{ response.setStatus(404); return null; } }catch(Exception e){ response.setStatus(500); try { response.getOutputStream().print( e.getMessage()); }catch(Exception e2){ System.err.println(e2.getMessage()); } System.err.println(e.getMessage()); return null; } } @PutMapping("/{visiteId}") @Override public Visite update(@PathVariable(value="visiteId") String id, @RequestBody Visite v, HttpServletResponse response){ try (Connection connection = dataSource.getConnection()){ if(!v.getVisiteId().equals(id)){ response.setStatus(412); return null; } else if(read(id, response) == null){ response.setStatus(403); return null; } else if(read(v.getVisiteId(), response) != null){ Statement stmt = connection.createStatement(); stmt.executeUpdate("UPDATE visites set visiteId = '"+v.getVisiteId()+"', defiId = '"+v.getDefiId()+"', visiteur = '"+v.getVisiteur() +"', dateVisite = TO_TIMESTAMP('"+v.getDateVisite()+"','YYYY-MM-DD HH:MI:SS'), modeVisite = '"+v.getModeVisite()+"', status = "+v.getStatus()+"', score = '"+v.getScore()+ "', temps = "+v.getTemps()+", evaluation = '"+v.getEvalution()+"', commentaire = '"+v.getCommentaire()+"' WHERE visiteId = '"+v.getVisiteId()+"'"); ResultSet rs = stmt.executeQuery("SELECT * FROM visites WHERE visiteId = '"+v.getVisiteId()+"'"); Visite visite = new Visite(null,null, null, null, null, null, 0, 0, null, null); rs.next(); visite.setVisiteId(rs.getString("visiteId")); visite.setDefiId(rs.getString("defiId")); visite.setVisiteur(rs.getString("visiteur")); visite.setDateVisite(rs.getString("dateVisite")); visite.setModeVisite(rs.getString("modeVisite")); visite.setStatus(rs.getString("status")); visite.setScore(rs.getInt("score")); visite.setTemps(rs.getInt("temps")); visite.setEvalution(rs.getString("evaluation")); visite.setCommentaire(rs.getString("commentaire")); return visite; } else { return null; } }catch(Exception e){ response.setStatus(500); try { response.getOutputStream().print( e.getMessage()); }catch(Exception e2){ System.err.println(e2.getMessage()); } System.err.println(e.getMessage()); return null; } } @DeleteMapping("/{visiteId}") public void delete(@PathVariable(value="userId") String id, HttpServletResponse response){ try (Connection connection = dataSource.getConnection()){ if(read(id, response) == null ){ response.setStatus(404); } else{ Statement stmt = connection.createStatement(); stmt.executeUpdate("DELETE FROM visites WHERE visiteId = '"+id+"'"); } }catch(Exception e){ response.setStatus(500); try { response.getOutputStream().print( e.getMessage()); }catch(Exception e2){ System.err.println(e2.getMessage()); } System.err.println(e.getMessage()); } } }
34.783217
323
0.555991
e4d6d491a69b04ba4406a1b0eea406da5219ac6c
2,877
/* * MIT License * * Copyright 2018 Sabre GLBL Inc. * * 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.sabre.oss.yare.model.validator; import java.util.Objects; public class ValidationResult { private final Level level; private final String code; private final String message; ValidationResult(Level level, String code, String message) { this.level = Objects.requireNonNull(level); this.code = code; this.message = message; } public static ValidationResult error(String code, String message) { return new ValidationResult(Level.ERROR, code, message); } public static ValidationResult warning(String code, String message) { return new ValidationResult(Level.WARNING, code, message); } public static ValidationResult info(String code, String message) { return new ValidationResult(Level.INFO, code, message); } public Level getLevel() { return level; } public String getCode() { return code; } public String getMessage() { return message; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ValidationResult that = (ValidationResult) o; return level == that.level && Objects.equals(code, that.code) && Objects.equals(message, that.message); } @Override public int hashCode() { return Objects.hash(level, code, message); } @Override public String toString() { return String.format("ValidationResult{level=%s, code='%s', message='%s'}", level, code, message); } public enum Level { ERROR, WARNING, INFO } }
30.606383
106
0.665624
1c132d9e5b20cc485eec2ea58bd21caa9156281a
3,989
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.pnc.datastore; import org.jboss.arquillian.container.spi.client.container.DeploymentException; import org.jboss.pnc.common.util.ObjectWrapper; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class DeploymentFactory { private static Logger logger = LoggerFactory.getLogger(DeploymentFactory.class); public static Archive<?> createDatastoreDeployment() { JavaArchive datastoreJar = ShrinkWrap.create(JavaArchive.class, "datastore.jar") .addPackages(true, "org.jboss.pnc.datastore") .addAsManifestResource("test-persistence.xml", "persistence.xml") .addAsManifestResource("logback.xml"); logger.info("Deployment datastoreJar: {}", datastoreJar.toString(true)); File[] dependencies = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeAndTestDependencies().resolve() .withTransitivity().asFile(); //remove "model-<version>.jar" from the archive and add it as "model.jar" so we can reference it in the test-persistence.xml ObjectWrapper<File> modelJarWrapper = new ObjectWrapper(); List<File> dependenciesFiltered = Arrays.stream(dependencies) .filter(jar -> extractModelJar(jar, modelJarWrapper)) .filter(jar -> !mockJarMatches(jar)) .collect(Collectors.toList()); File modelJar = modelJarWrapper.get(); if (modelJar == null) { throw new RuntimeException(new DeploymentException("Cannot find model*.jar")); } Optional<File> mockJarOptional = Arrays.stream(dependencies).filter(jar -> mockJarMatches(jar)).findAny(); if (!mockJarOptional.isPresent()) { throw new RuntimeException(new DeploymentException("Cannot find mock*.jar")); } JavaArchive mockJar = ShrinkWrap.createFromZipFile(JavaArchive.class, mockJarOptional.get()); mockJar.addAsManifestResource("mock-beans.xml", "beans.xml"); logger.info("Deployment mockJar: {}", mockJar.toString(true)); EnterpriseArchive enterpriseArchive = ShrinkWrap.create(EnterpriseArchive.class, "datastore-test.ear") .addAsModule(datastoreJar) .addAsLibraries(dependenciesFiltered.toArray(new File[dependenciesFiltered.size()])) .addAsLibrary(mockJar) .addAsLibrary(modelJar, "model.jar"); logger.info("Deployment: {}", enterpriseArchive.toString(true)); return enterpriseArchive; } private static boolean mockJarMatches(File jar) { return jar.getName().matches("pnc-mock.*\\.jar"); } private static boolean extractModelJar(File jar, ObjectWrapper<File> modelJar) { if (jar.getName().matches("model.*\\.jar")) { modelJar.set(jar); return false; } else { return true; } } }
41.123711
132
0.692905
79fc041bf4e9d37b5a2dfbd6a2c95d0e27983977
36,302
/* * Copyright (c) OSGi Alliance (2008, 2009, 2010, 2017). 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 org.osgi.test.cases.remoteservices.junit; import static org.junit.Assert.assertArrayEquals; import static org.osgi.framework.Constants.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.jar.Attributes; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.ServiceException; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.framework.Version; import org.osgi.framework.launch.Framework; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWiring; import org.osgi.test.cases.remoteservices.common.A; import org.osgi.test.cases.remoteservices.common.AsyncJava8Types; import org.osgi.test.cases.remoteservices.common.AsyncTypes; import org.osgi.test.cases.remoteservices.common.B; import org.osgi.test.cases.remoteservices.common.BasicTypes; import org.osgi.test.cases.remoteservices.common.C; import org.osgi.test.cases.remoteservices.common.DTOType; import org.osgi.test.cases.remoteservices.common.SlowService; import org.osgi.test.cases.remoteservices.impl.AsyncJava8TypesImpl; import org.osgi.test.cases.remoteservices.impl.AsyncTypesImpl; import org.osgi.test.cases.remoteservices.impl.BasicTypesTestServiceImpl; import org.osgi.test.cases.remoteservices.impl.SlowServiceImpl; import org.osgi.test.cases.remoteservices.impl.TestServiceImpl; import org.osgi.test.support.sleep.Sleep; import org.osgi.test.support.tracker.Tracker; import org.osgi.util.function.Predicate; import org.osgi.util.promise.Promise; import org.osgi.util.promise.Success; import org.osgi.util.tracker.ServiceTracker; /** * @author <a href="mailto:tdiekman@tibco.com">Tim Diekmann</a> * */ public class SimpleTest extends MultiFrameworkTestCase { /** * Package to be exported by the server side System Bundle */ private static final String ORG_OSGI_TEST_CASES_REMOTESERVICES_COMMON = "org.osgi.test.cases.remoteservices.common"; /** * Magic value. Properties with this value will be replaced by a socket port number that is currently free. */ private static final String FREE_PORT = "@@FREE_PORT@@"; private long timeout; /** * @see org.osgi.test.cases.remoteserviceadmin.junit.MultiFrameworkTestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); timeout = getLongProperty("rsa.ct.timeout", 30000L); } /** * @see org.osgi.test.cases.remoteservices.junit.MultiFrameworkTestCase#getConfiguration() */ @Override public Map<String,String> getConfiguration() { Map<String,String> configuration = new HashMap<>(); configuration.put(Constants.FRAMEWORK_STORAGE_CLEAN, "true"); //make sure that the server framework System Bundle exports the interfaces String systemPacakagesXtra = ORG_OSGI_TEST_CASES_REMOTESERVICES_COMMON; configuration.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, systemPacakagesXtra); String configuratorInitial = System .getProperty("server.configurator.initial"); if (configuratorInitial != null) { configuration.put("configurator.initial", configuratorInitial); } return configuration; } /** * @throws Exception */ public void testSimpleRegistration() throws Exception { Hashtable<String,Object> properties = registrationTestServiceProperties(); // install server side test service in the sub-framework ServiceRegistration< ? > srTestService = installTestBundleAndRegisterServiceObject( TestServiceImpl.class.getName(), properties, A.class.getName(), B.class.getName()); assertNotNull(srTestService); System.out.println("registered test service A and B on server side"); Sleep.sleep(1000); try { { ServiceTracker<A,A> clientTracker = new ServiceTracker<>( getContext(), A.class, null); clientTracker.open(); // the proxy should appear in this framework A client = Tracker.waitForService(clientTracker, timeout); assertNotNull("no proxy for service A found!", client); ServiceReference<A> sr = clientTracker.getServiceReference(); System.out.println(sr); assertNotNull(sr); assertNotNull(sr.getProperty("service.imported")); assertNotNull(sr.getProperty("service.id")); assertNotNull(sr.getProperty("endpoint.id")); assertNotNull(sr.getProperty("service.imported.configs")); assertNull("private properties must not be exported", sr.getProperty(".myprop")); assertEquals("property implementation missing from proxy", "1", sr.getProperty("implementation")); assertNull(sr.getProperty( RemoteServiceConstants.SERVICE_EXPORTED_INTENTS)); assertNull(sr.getProperty( RemoteServiceConstants.SERVICE_EXPORTED_INTENTS_EXTRA)); assertNull(sr.getProperty( RemoteServiceConstants.SERVICE_EXPORTED_INTERFACES)); assertNull(sr.getProperty( RemoteServiceConstants.SERVICE_EXPORTED_CONFIGS)); // invoke the proxy assertEquals("A", client.getA()); clientTracker.close(); } // now check on the hosting framework for the service to become available // make sure C was not registered, since it wasn't exported assertNull( "service C should not have been found as it was not exported", getContext().getServiceReference(C.class)); { // check for service B ServiceTracker<B,B> clientTracker = new ServiceTracker<>( getContext(), B.class, null); clientTracker.open(); // the proxy should appear in this framework B clientB = Tracker.waitForService(clientTracker, timeout); assertNotNull("no proxy for service B found!", clientB); ServiceReference<B> sr = clientTracker.getServiceReference(); System.out.println(sr); assertNotNull(sr); assertNotNull(sr.getProperty("service.imported")); assertNotNull(sr.getProperty("service.id")); assertNotNull(sr.getProperty("endpoint.id")); assertNotNull(sr.getProperty("service.imported.configs")); assertNull("private properties must not be exported", sr.getProperty(".myprop")); assertEquals("property implementation missing from proxy", "1", sr.getProperty("implementation")); assertNull(sr.getProperty( RemoteServiceConstants.SERVICE_EXPORTED_INTENTS)); assertNull(sr.getProperty( RemoteServiceConstants.SERVICE_EXPORTED_INTENTS_EXTRA)); assertNull(sr.getProperty( RemoteServiceConstants.SERVICE_EXPORTED_INTERFACES)); assertNull(sr.getProperty( RemoteServiceConstants.SERVICE_EXPORTED_CONFIGS)); // invoke the proxy assertEquals("B", clientB.getB()); clientTracker.close(); } } finally { srTestService.unregister(); } } private Hashtable<String,Object> registrationTestServiceProperties() throws Exception { // verify that the server framework is exporting the test packages verifyFramework(); Set<String> supportedConfigTypes = getSupportedConfigTypes(); // load the external properties file with the config types for the // server side service Hashtable<String,Object> properties = loadServerTCKProperties(); // make sure the given config type is in the set of supported config // types String str = (String) properties .get(RemoteServiceConstants.SERVICE_EXPORTED_CONFIGS); // I hate not having String.split() available StringTokenizer st = new StringTokenizer(str, " "); boolean found = false; while (st.hasMoreTokens()) { if (supportedConfigTypes.contains(st.nextToken())) { found = true; break; } } assertTrue( "the given service.exported.configs type is not supported by the installed Distribution Provider", found); // add some properties for testing properties.put(RemoteServiceConstants.SERVICE_EXPORTED_INTERFACES, "*"); properties.put("implementation", "1"); properties.put(".myprop", "must not be visible on client side"); processFreePortProperties(properties); return properties; } /** * @throws Exception */ public void testBasicTypesIntent() throws Exception { Filter filter = getFramework().getBundleContext().createFilter( "(" + DistributionProviderConstants.REMOTE_CONFIGS_SUPPORTED + "=*)"); ServiceTracker< ? , ? > dpTracker = new ServiceTracker<>( getFramework().getBundleContext(), filter, null); dpTracker.open(); Object dp = Tracker.waitForService(dpTracker, timeout); assertNotNull("No DistributionProvider found", dp); ServiceReference< ? > dpReference = dpTracker.getServiceReference(); assertNotNull(dpReference); Object property = dpReference.getProperty( DistributionProviderConstants.REMOTE_INTENTS_SUPPORTED); assertNotNull("No intents supported", property); Collection<String> intents; if (property instanceof String) { intents = Collections.singleton((String) property); } else if (property instanceof String[]) { intents = Arrays.asList((String[]) property); } else if (property instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> tmp = (Collection<String>) property; intents = tmp; } else { throw new IllegalArgumentException( "Supported intents are not of the correct type " + property.getClass()); } assertTrue("Did not support osgi.basic", intents.contains("osgi.basic")); } /** * @throws Exception */ public void testBasicTypes() throws Exception { Hashtable<String,Object> properties = registrationTestServiceProperties(); properties.put(RemoteServiceConstants.SERVICE_EXPORTED_INTENTS, "osgi.basic"); // register the service in the server side framework ServiceRegistration< ? > srTestService = installTestBundleAndRegisterServiceObject( BasicTypesTestServiceImpl.class.getName(), properties, BasicTypes.class.getName()); System.out .println("registered basic types test service on server side"); try { // now check on the hosting framework for the service to become // available ServiceTracker<BasicTypes,BasicTypes> clientTracker = new ServiceTracker<>( getContext(), BasicTypes.class, null); clientTracker.open(); // the proxy should appear in this framework BasicTypes client = Tracker.waitForService(clientTracker, timeout); assertNotNull("no proxy for BasicTypes found!", client); ServiceReference<BasicTypes> sr = clientTracker .getServiceReference(); Object property = sr .getProperty(RemoteServiceConstants.SERVICE_INTENTS); assertNotNull("No intents supported", property); Collection<String> intents; if (property instanceof String) { intents = Collections.singleton((String) property); } else if (property instanceof String[]) { intents = Arrays.asList((String[]) property); } else if (property instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> tmp = (Collection<String>) property; intents = tmp; } else { throw new IllegalArgumentException( "Supported intents are not of the correct type " + property.getClass()); } assertTrue("Did not pick up the osgi.basic intent", intents.contains("osgi.basic")); // booleans assertFalse(client.getBooleanPrimitive(true)); assertTrue(client.getBoolean(false)); assertTrue(Arrays.equals(new boolean[] { true, false }, client.getBooleanPrimitiveArray(new boolean[] { false, true }))); assertArrayEquals(new Boolean[] { false, true }, client.getBooleanArray(new Boolean[] { true, false })); assertEquals(Arrays.asList(true, true, false), client.getBooleanList(Arrays.asList(false, false, true))); assertEquals(Collections.singleton(true), client.getBooleanSet(Collections.singleton(false))); // bytes assertEquals(-1, client.getBytePrimitive((byte) 1)); assertEquals(Byte.valueOf((byte) -1), client.getByte((byte) 1)); assertArrayEquals(new byte[] { -1, -2, -3 }, client.getBytePrimitiveArray(new byte[] { 1, 2, 3 })); assertArrayEquals(new Byte[] { (byte) 3, (byte) 2, (byte) 1 }, client.getByteArray(new Byte[] { 1, 2, 3 })); assertEquals(Arrays.asList((byte) 1, (byte) 2, (byte) 3), client .getByteList(Arrays.asList((byte) 3, (byte) 2, (byte) 1))); assertEquals( new HashSet<>(Arrays.asList((byte) 2, (byte) 4, (byte) 6)), client.getByteSet(new HashSet<>( Arrays.asList((byte) 1, (byte) 2, (byte) 3)))); // shorts assertEquals(-1, client.getShortPrimitive((short) 1)); assertEquals(Short.valueOf((short) -1), client.getShort((short) 1)); assertArrayEquals(new short[] { -1, -2, -3 }, client.getShortPrimitiveArray(new short[] { 1, 2, 3 })); assertArrayEquals(new Short[] { (short) 3, (short) 2, (short) 1 }, client.getShortArray(new Short[] { 1, 2, 3 })); assertEquals(Arrays.asList((short) 1, (short) 2, (short) 3), client.getShortList( Arrays.asList((short) 3, (short) 2, (short) 1))); assertEquals( new HashSet<>( Arrays.asList((short) 2, (short) 4, (short) 6)), client.getShortSet(new HashSet<>( Arrays.asList((short) 1, (short) 2, (short) 3)))); // chars assertEquals('b', client.getCharPrimitive('a')); assertEquals(Character.valueOf('b'), client.getChar('a')); assertArrayEquals(new char[] { 'b', 'c', 'd' }, client.getCharacterPrimitiveArray(new char[] { 'a', 'b', 'c' })); assertArrayEquals(new Character[] { 'c', 'b', 'a' }, client.getCharacterArray(new Character[] { 'a', 'b', 'c' })); assertEquals(Arrays.asList('c', 'b', 'a'), client.getCharacterList(Arrays.asList('a', 'b', 'c'))); assertEquals(new HashSet<>(Arrays.asList('A', 'B', 'C')), client.getCharacterSet( new HashSet<>(Arrays.asList('c', 'b', 'a')))); // ints assertEquals(-1, client.getIntPrimitive(1)); assertEquals(Integer.valueOf(-1), client.getInt(1)); assertArrayEquals(new int[] { -1, -2, -3 }, client.getIntPrimitiveArray(new int[] { 1, 2, 3 })); assertArrayEquals(new Integer[] { 3, 2, 1 }, client.getIntegerArray(new Integer[] { 1, 2, 3 })); assertEquals(Arrays.asList(1, 2, 3), client.getIntegerList(Arrays.asList(3, 2, 1))); assertEquals(new HashSet<>(Arrays.asList(2, 4, 6)), client .getIntegerSet(new HashSet<>(Arrays.asList(1, 2, 3)))); // longs assertEquals(-1, client.getLongPrimitive(1)); assertEquals(Long.valueOf(-1), client.getLong((long) 1)); assertArrayEquals(new long[] { -1, -2, -3 }, client.getLongPrimitiveArray(new long[] { 1, 2, 3 })); assertArrayEquals(new Long[] { (long) 3, (long) 2, (long) 1 }, client.getLongArray(new Long[] { (long) 1, (long) 2, (long) 3 })); assertEquals(Arrays.asList((long) 1, (long) 2, (long) 3), client .getLongList(Arrays.asList((long) 3, (long) 2, (long) 1))); assertEquals( new HashSet<>(Arrays.asList((long) 2, (long) 4, (long) 6)), client.getLongSet(new HashSet<>( Arrays.asList((long) 1, (long) 2, (long) 3)))); // floats assertEquals(-1f, client.getFloatPrimitive(1), 0.01f); assertEquals(Float.valueOf(-1), client.getFloat((float) 1)); assertArrayEquals(new float[] { -1, -2, -3 }, client.getFloatPrimitiveArray(new float[] { 1, 2, 3 }), 0.01f); assertArrayEquals(new Float[] { (float) 3, (float) 2, (float) 1 }, client.getFloatArray(new Float[] { (float) 1, (float) 2, (float) 3 })); assertEquals(Arrays.asList((float) 1, (float) 2, (float) 3), client.getFloatList( Arrays.asList((float) 3, (float) 2, (float) 1))); assertEquals( new HashSet<>( Arrays.asList((float) 2, (float) 4, (float) 6)), client.getFloatSet(new HashSet<>( Arrays.asList((float) 1, (float) 2, (float) 3)))); // doubles assertEquals(-1d, client.getDoublePrimitive(1), 0.01d); assertEquals(Double.valueOf(-1), client.getDouble((double) 1)); assertArrayEquals(new double[] { -1, -2, -3 }, client.getDoublePrimitiveArray(new double[] { 1, 2, 3 }), 0.01d); assertArrayEquals(new Double[] { (double) 3, (double) 2, (double) 1 }, client.getDoubleArray(new Double[] { (double) 1, (double) 2, (double) 3 })); assertEquals(Arrays.asList((double) 1, (double) 2, (double) 3), client.getDoubleList( Arrays.asList((double) 3, (double) 2, (double) 1))); assertEquals( new HashSet<>( Arrays.asList((double) 2, (double) 4, (double) 6)), client.getDoubleSet(new HashSet<>(Arrays.asList((double) 1, (double) 2, (double) 3)))); // Strings assertEquals("BANG", client.getString("bang")); assertArrayEquals(new String[] { "fum", "fo", "fi", "fee" }, client.getStringArray(new String[] { "fee", "fi", "fo", "fum" })); assertEquals(Arrays.asList("fum", "fo", "fi", "fee"), client .getStringList(Arrays.asList("fee", "fi", "fo", "fum"))); assertEquals(new HashSet<>(Arrays.asList("FEE", "FI", "FO", "FUM")), client.getStringSet(new HashSet<>( Arrays.asList("fee", "fi", "fo", "fum")))); // Versions assertEquals(Version.parseVersion("2.3.4"), client.getVersion(Version.parseVersion("1.2.3"))); assertArrayEquals(new Version[] { Version.parseVersion("4.5.6"), Version.parseVersion("1.2.3") }, client.getVersionArray(new Version[] { Version.parseVersion("1.2.3"), Version.parseVersion("4.5.6") })); assertEquals( Arrays.asList(Version.parseVersion("4.5.6"), Version.parseVersion("1.2.3")), client.getVersionList( Arrays.asList(Version.parseVersion("1.2.3"), Version.parseVersion("4.5.6")))); assertEquals( new HashSet<>(Arrays.asList(Version.parseVersion("2.3.4"), Version.parseVersion("5.6.7"))), client.getVersionSet(new HashSet<>( Arrays.asList(Version.parseVersion("1.2.3"), Version.parseVersion("4.5.6"))))); // enums assertEquals(TimeUnit.MICROSECONDS, client.getEnum(TimeUnit.NANOSECONDS)); assertArrayEquals(new TimeUnit[] { TimeUnit.HOURS, TimeUnit.DAYS }, client.getEnumArray(new TimeUnit[] { TimeUnit.DAYS, TimeUnit.HOURS })); assertEquals(Arrays.asList(TimeUnit.HOURS, TimeUnit.DAYS), client .getEnumList(Arrays.asList(TimeUnit.DAYS, TimeUnit.HOURS))); assertEquals( new HashSet<>( Arrays.asList(TimeUnit.HOURS, TimeUnit.SECONDS)), client.getEnumSet(new HashSet<>(Arrays .asList(TimeUnit.MILLISECONDS, TimeUnit.MINUTES)))); // dtos DTOType typeA = new DTOType(); typeA.value = "a"; DTOType typeB = new DTOType(); typeB.value = "b"; DTOType typeC = new DTOType(); typeC.value = "c"; assertEquals("A", client.getDTO(typeA).value); DTOType[] array = client.getDTOTypeArray(new DTOType[] { typeA, typeB, typeC }); assertEquals(3, array.length); assertEquals("c", array[0].value); assertEquals("b", array[1].value); assertEquals("a", array[2].value); List<DTOType> list = client .getDTOTypeList(Arrays.asList(typeA, typeB, typeC)); assertEquals(3, list.size()); assertEquals("c", list.get(0).value); assertEquals("b", list.get(1).value); assertEquals("a", list.get(2).value); Set<String> values = new HashSet<>(); for (DTOType dtoType : client.getDTOTypeSet( new HashSet<>(Arrays.asList(typeA, typeB, typeC)))) { values.add(dtoType.value); } assertEquals(new HashSet<>(Arrays.asList("A", "B", "C")), values); Map<String, Integer> map = new HashMap<>(); map.put("foo", 1); map.put("bar", 2); client.populateMap(map); assertEquals(map, client.getMap()); clientTracker.close(); } finally { srTestService.unregister(); } } /** * @throws Exception */ public void testBasicTimeout() throws Exception { Hashtable<String,Object> properties = registrationTestServiceProperties(); properties.put(RemoteServiceConstants.SERVICE_EXPORTED_INTENTS, "osgi.basic"); properties.put("osgi.basic.timeout", "3000"); // register the service in the server side framework ServiceRegistration< ? > srTestService = installTestBundleAndRegisterServiceObject( SlowServiceImpl.class.getName(), properties, SlowService.class.getName()); System.out.println("registered slow test service on server side"); try { // now check on the hosting framework for the service to become // available ServiceTracker<SlowService,SlowService> clientTracker = new ServiceTracker<>( getContext(), SlowService.class, null); clientTracker.open(); // the proxy should appear in this framework SlowService client = Tracker.waitForService(clientTracker, timeout); assertNotNull("no proxy for SlowService found!", client); ServiceReference<SlowService> sr = clientTracker .getServiceReference(); Object property = sr .getProperty(RemoteServiceConstants.SERVICE_INTENTS); assertNotNull("No intents supported", property); Collection<String> intents; if (property instanceof String) { intents = Collections.singleton((String) property); } else if (property instanceof String[]) { intents = Arrays.asList((String[]) property); } else if (property instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> tmp = (Collection<String>) property; intents = tmp; } else { throw new IllegalArgumentException( "Supported intents are not of the correct type " + property.getClass()); } assertTrue("Did not pick up the osgi.basic intent", intents.contains("osgi.basic")); // should work fine assertEquals("ready", client.goSlow(1000)); try { client.goSlow(5000); fail("Invocation should have timed out!"); } catch (ServiceException se) { assertEquals(ServiceException.REMOTE, se.getType()); } clientTracker.close(); } finally { srTestService.unregister(); } } /** * @throws Exception */ public void testAsyncTypesIntent() throws Exception { Filter filter = getFramework().getBundleContext().createFilter( "(" + DistributionProviderConstants.REMOTE_CONFIGS_SUPPORTED + "=*)"); ServiceTracker< ? , ? > dpTracker = new ServiceTracker<>( getFramework().getBundleContext(), filter, null); dpTracker.open(); Object dp = Tracker.waitForService(dpTracker, timeout); assertNotNull("No DistributionProvider found", dp); ServiceReference< ? > dpReference = dpTracker.getServiceReference(); assertNotNull(dpReference); Object property = dpReference.getProperty( DistributionProviderConstants.REMOTE_INTENTS_SUPPORTED); assertNotNull("No intents supported", property); Collection<String> intents; if (property instanceof String) { intents = Collections.singleton((String) property); } else if (property instanceof String[]) { intents = Arrays.asList((String[]) property); } else if (property instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> tmp = (Collection<String>) property; intents = tmp; } else { throw new IllegalArgumentException( "Supported intents are not of the correct type " + property.getClass()); } assertTrue("Did not support osgi.async", intents.contains("osgi.async")); } /** * @throws Exception */ public void testAsyncTypes() throws Exception { Hashtable<String,Object> properties = registrationTestServiceProperties(); properties.put(RemoteServiceConstants.SERVICE_EXPORTED_INTENTS, "osgi.async"); // register the service in the server side framework ServiceRegistration< ? > srTestService = installTestBundleAndRegisterServiceObject( AsyncTypesImpl.class.getName(), properties, AsyncTypes.class.getName()); System.out .println("registered basic types test service on server side"); try { // now check on the hosting framework for the service to become // available ServiceTracker<AsyncTypes,AsyncTypes> clientTracker = new ServiceTracker<>( getContext(), AsyncTypes.class, null); clientTracker.open(); // the proxy should appear in this framework AsyncTypes client = Tracker.waitForService(clientTracker, timeout); assertNotNull("no proxy for AsyncTypes found!", client); ServiceReference<AsyncTypes> sr = clientTracker .getServiceReference(); Object property = sr .getProperty(RemoteServiceConstants.SERVICE_INTENTS); assertNotNull("No intents supported", property); Collection<String> intents; if (property instanceof String) { intents = Collections.singleton((String) property); } else if (property instanceof String[]) { intents = Arrays.asList((String[]) property); } else if (property instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> tmp = (Collection<String>) property; intents = tmp; } else { throw new IllegalArgumentException( "Supported intents are not of the correct type " + property.getClass()); } assertTrue("Did not pick up the osgi.async intent", intents.contains("osgi.async")); final Semaphore s = new Semaphore(0); // Future Future<String> f = client.getFuture(1000); assertFalse(f.isDone()); assertEquals(AsyncTypes.RESULT, f.get(2, TimeUnit.SECONDS)); // Promise Promise<String> p = client.getPromise(1000); p.filter(new Predicate<String>() { @Override public boolean test(String x) { return AsyncTypes.RESULT.equals(x); } }).then(new Success<String,Object>() { @Override public Promise<Object> call(Promise<String> x) throws Exception { s.release(); return null; } }); assertFalse(s.tryAcquire()); assertTrue(s.tryAcquire(2, TimeUnit.SECONDS)); clientTracker.close(); } finally { srTestService.unregister(); } } /** * @throws Exception */ public void testAsyncJava8Types() throws Exception { try { Hashtable<String,Object> properties = registrationTestServiceProperties(); properties.put(RemoteServiceConstants.SERVICE_EXPORTED_INTENTS, "osgi.async"); // register the service in the server side framework ServiceRegistration< ? > srTestService = installTestBundleAndRegisterServiceObject( AsyncJava8TypesImpl.class.getName(), properties, AsyncJava8Types.class.getName()); System.out.println( "registered basic types test service on server side"); try { // now check on the hosting framework for the service to become // available ServiceTracker<AsyncJava8Types,AsyncJava8Types> clientTracker = new ServiceTracker<>( getContext(), AsyncJava8Types.class, null); clientTracker.open(); // the proxy should appear in this framework AsyncJava8Types client = Tracker.waitForService(clientTracker, timeout); assertNotNull("no proxy for AsyncJava8Types found!", client); ServiceReference<AsyncJava8Types> sr = clientTracker .getServiceReference(); Object property = sr .getProperty(RemoteServiceConstants.SERVICE_INTENTS); assertNotNull("No intents supported", property); Collection<String> intents; if (property instanceof String) { intents = Collections.singleton((String) property); } else if (property instanceof String[]) { intents = Arrays.asList((String[]) property); } else if (property instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> tmp = (Collection<String>) property; intents = tmp; } else { throw new IllegalArgumentException( "Supported intents are not of the correct type " + property.getClass()); } assertTrue("Did not pick up the osgi.async intent", intents.contains("osgi.async")); final Semaphore s = new Semaphore(0); // CompletableFuture CompletableFuture<String> cf = client .getCompletableFuture(1000); cf.thenRun(new Runnable() { @Override public void run() { s.release(); } }); assertFalse(s.tryAcquire()); assertTrue(s.tryAcquire(2, TimeUnit.SECONDS)); assertEquals(AsyncJava8Types.RESULT, cf.get()); // CompletionStage CompletionStage<String> cs = client.getCompletionStage(1000); cs.thenAccept(new Consumer<String>() { @Override public void accept(String r) { if (AsyncJava8Types.RESULT.equals(r)) { s.release(); } else { System.out .println("Received the wrong result " + r); } } }); assertFalse(s.tryAcquire()); assertTrue(s.tryAcquire(2, TimeUnit.SECONDS)); clientTracker.close(); } finally { srTestService.unregister(); } } catch (NoClassDefFoundError e) { // must be less than java 8. } } private void processFreePortProperties( Hashtable<String,Object> properties) { String freePort = getFreePort(); for (Iterator<Entry<String,Object>> it = properties.entrySet() .iterator(); it.hasNext();) { Entry<String,Object> entry = it.next(); if (entry.getValue().toString().trim().equals(FREE_PORT)) { entry.setValue(freePort); } } } private String getFreePort() { try { ServerSocket ss = new ServerSocket(0); String port = "" + ss.getLocalPort(); ss.close(); System.out.println("Found free port " + port); return port; } catch (IOException e) { e.printStackTrace(); return null; } } /** * @return */ private Hashtable<String,Object> loadServerTCKProperties() { String serverconfig = getProperty("org.osgi.test.cases.remoteservices.serverconfig"); assertNotNull( "did not find org.osgi.test.cases.remoteservices.serverconfig system property", serverconfig); Hashtable<String,Object> properties = new Hashtable<>(); for (StringTokenizer tok = new StringTokenizer(serverconfig, ","); tok .hasMoreTokens();) { String propertyName = tok.nextToken(); String value = getProperty(propertyName); assertNotNull("system property not found: " + propertyName, value); properties.put(propertyName, value); } return properties; } private Set<String> getSupportedConfigTypes() throws Exception { // make sure there is a Distribution Provider installed in the framework // Filter filter = getFramework().getBundleContext().createFilter("(&(objectClass=*)(" + // DistributionProviderConstants.REMOTE_CONFIGS_SUPPORTED + "=*))"); Filter filter = getFramework().getBundleContext().createFilter("(" + DistributionProviderConstants.REMOTE_CONFIGS_SUPPORTED + "=*)"); ServiceTracker< ? , ? > dpTracker = new ServiceTracker<>( getFramework().getBundleContext(), filter, null); dpTracker.open(); Object dp = Tracker.waitForService(dpTracker, timeout); assertNotNull("No DistributionProvider found", dp); ServiceReference< ? > dpReference = dpTracker.getServiceReference(); assertNotNull(dpReference); assertNotNull(dpReference.getProperty(DistributionProviderConstants.REMOTE_INTENTS_SUPPORTED)); Set<String> supportedConfigTypes = new HashSet<>(); // collect all // supported config // types Object configProperty = dpReference.getProperty(DistributionProviderConstants.REMOTE_CONFIGS_SUPPORTED); if (configProperty instanceof String) { StringTokenizer st = new StringTokenizer((String)configProperty, " "); while (st.hasMoreTokens()) { supportedConfigTypes.add(st.nextToken()); } } else if (configProperty instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> col = (Collection<String>) configProperty; for (Iterator<String> it = col.iterator(); it.hasNext();) { supportedConfigTypes.add(it.next()); } } else { // assume String[] String[] arr = (String[]) configProperty; for (int i=0; i<arr.length; i++) { supportedConfigTypes.add(arr[i]); } } dpTracker.close(); return supportedConfigTypes; } /** * Verifies the server side framework that it exports the test packages for the interface * used by the test service. * @throws Exception */ private void verifyFramework() throws Exception { Framework f = getFramework(); BundleWiring wiring = f.getBundleContext().getBundle() .adapt(BundleWiring.class); assertNotNull( "Framework is not supplying a BundleWiring for the system bundle", wiring); List<BundleCapability> exportedPkgs = wiring .getCapabilities(BundleRevision.PACKAGE_NAMESPACE); for (BundleCapability exportedPkg : exportedPkgs) { String name = (String) exportedPkg.getAttributes().get( BundleRevision.PACKAGE_NAMESPACE); if (name.equals(ORG_OSGI_TEST_CASES_REMOTESERVICES_COMMON)) { return; } } fail("Framework System Bundle is not exporting package " + ORG_OSGI_TEST_CASES_REMOTESERVICES_COMMON); } private ServiceRegistration< ? > installTestBundleAndRegisterServiceObject( String serviceClassName, Dictionary<String,Object> properties, String... ifaces) throws Exception { Bundle bundle = getFramework().getBundleContext() .installBundle("test-bundle", createTestBundle()); bundle.start(); Object object = bundle.loadClass(serviceClassName) .getConstructor() .newInstance(); return bundle.getBundleContext().registerService(ifaces, object, properties); } private InputStream createTestBundle() throws IOException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { Manifest manifest = new Manifest(); Attributes mainAttributes = manifest.getMainAttributes(); mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); mainAttributes.put(new Attributes.Name(BUNDLE_MANIFESTVERSION), "2"); mainAttributes.put(new Attributes.Name(BUNDLE_SYMBOLICNAME), ORG_OSGI_TEST_CASES_REMOTESERVICES_COMMON + ".bundle"); mainAttributes.put(new Attributes.Name(IMPORT_PACKAGE), "org.osgi.util.promise;version=\"[1,2)\",org.osgi.framework"); try (JarOutputStream jos = new JarOutputStream(baos, manifest)) { Bundle bundle = getContext().getBundle(); writePackage(jos, "/org/osgi/test/cases/remoteservices/common", bundle); writePackage(jos, "/org/osgi/test/cases/remoteservices/impl", bundle); } return new ByteArrayInputStream(baos.toByteArray()); } } private void writePackage(JarOutputStream jos, String path, Bundle bundle) throws IOException { Enumeration<String> paths = bundle.getEntryPaths(path); while (paths.hasMoreElements()) { String name = paths.nextElement(); jos.putNextEntry(new ZipEntry(name)); try (InputStream is = bundle.getResource(name).openStream()) { byte[] b = new byte[4096]; int i; while ((i = is.read(b)) != -1) { jos.write(b, 0, i); } jos.closeEntry(); } } } }
33.33517
117
0.697124
5287d91173aa6adc0da822ab114ff8a6412dfc97
1,609
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package binarysearchtree; /** * * @author Ali */ public class B1 { class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } } // Root of BST public Node root; // Constructor B1() { root = null; } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the (unchanged) node pointer */ return root; } // This method mainly calls InorderRec() void inorder() { inorderRec(root); } // A utility function to do inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.print(root.key+" "); inorderRec(root.right); } } }
22.041096
79
0.511498
cdf5582988906a475308d38ad55d1fb102a3cca3
991
package nextstep.subway.applicaion; import nextstep.subway.applicaion.dto.PathResponse; import nextstep.subway.domain.*; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class PathService { private final StationService stationService; private final LineRepository lineRepository; public PathService(StationService stationService, LineRepository lineRepository) { this.stationService = stationService; this.lineRepository = lineRepository; } @Transactional(readOnly = true) public PathResponse findPath(Long source, Long target) { Station sourceStation = stationService.findById(source); Station targetStation = stationService.findById(target); List<Line> lines = lineRepository.findAll(); Path path = new SubwayMap(lines).findPath(sourceStation, targetStation); return PathResponse.from(path); } }
31.967742
86
0.75782
8dbea1590cc5509f9110468b2f7e32f72da06c93
9,048
package gg.projecteden.nexus.features.itemtags; import de.tr7zw.nbtapi.NBTItem; import gg.projecteden.nexus.utils.StringUtils; import gg.projecteden.nexus.utils.StringUtils.Gradient; import lombok.Getter; import lombok.NonNull; import net.md_5.bungee.api.ChatColor; import org.bukkit.Material; import org.bukkit.block.Banner; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BlockStateMeta; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static gg.projecteden.utils.Nullables.isNullOrEmpty; public enum Rarity implements ITag { // @formatter:off ORDINARY(ChatColor.of("#9e9e9e"), 0, 5), COMMON(ChatColor.of("#7aff7a"), 6, 11), UNCOMMON(ChatColor.of("#70ffcd"), 12, 19), RARE(ChatColor.of("#7a9dff"), 20, 29), EPIC(ChatColor.of("#da55ff"), 30, 39), // Uncraftable EXOTIC(List.of(ChatColor.of("#ff55ff"), ChatColor.of("#bf47ff"), ChatColor.of("#9747ff")), false, 40, 49), LEGENDARY(List.of(ChatColor.of("#bf47ff"), ChatColor.of("#00aaaa")), false, 50, 55), MYTHIC(List.of(ChatColor.of("#00aaaa"), ChatColor.of("#00ff91")), false, 56, 60), // Quest Related ARTIFACT(List.of(ChatColor.of("#ff584d"), ChatColor.of("#e39827"))), // Code Related UNIQUE(List.of(ChatColor.of("#6effaa"), ChatColor.of("#abff4a"))), ; // @formatter:on @Getter private final List<ChatColor> chatColors; @Getter private final boolean craftable; @Getter private final Integer min; @Getter private final Integer max; @Getter private final String tag; public static final String NBT_KEY = "ItemTag.RARITY"; Rarity(ChatColor chatColor, Integer min, Integer max) { this(Collections.singletonList(chatColor), true, min, max); } Rarity(List<ChatColor> chatColors, boolean craftable, Integer min, Integer max) { this.chatColors = new ArrayList<>(chatColors); this.craftable = craftable; this.min = min; this.max = max; this.tag = rawGetTag(); } Rarity(List<ChatColor> chatColors) { this(chatColors, false, null, null); } public static Rarity of(ItemStack itemStack) { return of(itemStack, Condition.of(itemStack), null); } public static Rarity of(ItemStack itemStack, Condition condition) { return of(itemStack, condition, null); } public static Rarity of(ItemStack itemStack, Condition condition, Player debugger) { if (!ItemTagsUtils.isArmor(itemStack) && !ItemTagsUtils.isTool(itemStack)) return null; if (ItemTagsUtils.isMythicMobsItem(itemStack)) return null; RarityArgs args = new RarityArgs(); args.setCondition(condition); args.setArmor(ItemTagsUtils.isArmor(itemStack)); args.setMaterial(itemStack.getType()); String itemType = StringUtils.camelCase(args.getMaterial()); ItemTags.debug(debugger, args.isArmor() ? " &3Armor material: &e" + itemType : " &3Tool material: &e" + itemType); args.setMaterialSum(getMaterialVal(args)); ItemTags.debug(debugger, " &3Sum: &e" + number(args.getMaterialSum())); if (itemStack.hasItemMeta()) { ItemTags.debug(debugger, " &3Vanilla Enchants:"); args.setVanillaEnchantsSum(getEnchantsVal(itemStack, args, debugger)); ItemTags.debug(debugger, " &3Sum: &e" + number(args.getVanillaEnchantsSum())); ItemTags.debug(debugger, " &3Custom Enchants:"); args.setCustomEnchantsSum(getCustomEnchantsVal(itemStack, debugger)); ItemTags.debug(debugger, " &3Sum: &e" + number(args.getCustomEnchantsSum())); checkCraftableRules(itemStack, args, debugger); } if (condition != null && condition != Condition.PRISTINE) { int value = ((Condition.values().length * 5) - ((condition.ordinal() + 1) * 5)) * -1; args.setConditionSum(value); ItemTags.debug(debugger, " &3Condition sum: " + number(args.getConditionSum())); } Rarity rarity; if (args.isCraftable()) rarity = clampRarity(args, ORDINARY, EPIC); else rarity = clampRarity(args, EXOTIC, MYTHIC); rarity = checkUniqueItems(itemStack, args, rarity); args.setRarity(rarity); ItemTags.debug(debugger, " &3Total sum: &a" + args.getTotalSum()); ItemTags.debug(debugger, " &3Craftable: &a" + args.isCraftable()); return args.getRarity(); } private static Rarity clampRarity(RarityArgs args, @NonNull Rarity minimum, @NonNull Rarity maximum) { Rarity result = null; int argSum = args.getTotalSum(); for (Rarity _rarity : Rarity.values()) { if (_rarity.getMin() == null || _rarity.getMax() == null) continue; if (_rarity.isCraftable() != args.isCraftable()) continue; if (_rarity.getMax() < minimum.getMax()) continue; int min = _rarity.getMin(); int max = _rarity.getMax(); if (argSum >= min && argSum <= max) result = _rarity; } if (result == null) { if (argSum >= maximum.getMax()) result = maximum; else if (argSum <= maximum.getMin()) result = minimum; else result = ORDINARY; } return result; } private String rawGetTag() { if (chatColors != null && !chatColors.isEmpty()) { if (chatColors.size() == 1) return chatColors.get(0) + "[" + StringUtils.camelCase(this.name()) + "]"; return Gradient.of(chatColors).apply("[" + StringUtils.camelCase(this.name()) + "]"); } return "[" + StringUtils.camelCase(this.name()) + "]"; } private static int getMaterialVal(RarityArgs args) { Integer result; Material material = args.getMaterial(); if (args.isArmor()) result = ItemTags.getArmorMaterialVal(material); else result = ItemTags.getToolMaterialVal(material); if (result == null) return 0; return result; } private static int getEnchantsVal(ItemStack itemStack, RarityArgs args, Player debugger) { int result = 0; ItemMeta meta = itemStack.getItemMeta(); if (meta.hasEnchants()) { Map<Enchantment, Integer> enchantMap = meta.getEnchants(); Set<Enchantment> enchants = enchantMap.keySet(); for (Enchantment enchant : enchants) { int level = enchantMap.get(enchant); int enchantVal = ItemTags.getEnchantVal(enchant, level, args); result += enchantVal; ItemTags.debug(debugger, " &3- " + StringUtils.camelCase(enchant.getKey().getKey()) + " " + level + ": &e" + number(enchantVal)); } } return result; } private static int getCustomEnchantsVal(ItemStack itemStack, Player debugger) { int result = 0; ItemMeta meta = itemStack.getItemMeta(); List<String> lore = meta.getLore(); if (!isNullOrEmpty(lore)) { for (String line : lore) { String enchant = StringUtils.stripColor(line) .replaceAll("[\\d]+", "") // Custom Enchants bug .replaceAll(" [IVXLC]+", "") .trim(); Integer val = ItemTags.getCustomEnchantVal(enchant); if (val != null) { ItemTags.debug(debugger, " &3- " + enchant + ": &e" + number(val)); result += val; } } } return result; } public static String number(int value) { if (value < 0) return "&c" + value; else return "&e" + value; } private static Rarity checkUniqueItems(ItemStack itemStack, RarityArgs args, Rarity defaultValue) { NBTItem nbtItem = new NBTItem(itemStack); if (nbtItem.hasKey(Rarity.NBT_KEY)) { return Rarity.valueOf(nbtItem.getString(Rarity.NBT_KEY).toUpperCase()); } return defaultValue; } private static void checkCraftableRules(ItemStack itemStack, RarityArgs args, Player debugger) { ItemMeta itemMeta = itemStack.getItemMeta(); Set<Enchantment> enchants = itemMeta.getEnchants().keySet(); // Check compatible enchants for (Enchantment enchant : enchants) { if (!args.isIncompatibleEnchants() && !enchant.canEnchantItem(itemStack)) { args.setIncompatibleEnchants(true); break; } } // Check conflicting enchants conflicts: for (Enchantment enchant : enchants) { for (Enchantment _enchant : enchants) { if (enchant.equals(_enchant)) continue; if (enchant.conflictsWith(_enchant)) { args.setConflictingEnchants(true); break conflicts; } } } // Check shield banner pattern size if (itemStack.getType().equals(Material.SHIELD)) { BlockStateMeta blockStateMeta = (BlockStateMeta) itemMeta; Banner banner = (Banner) blockStateMeta.getBlockState(); if (banner.getPatterns().size() > 6) args.setUncraftableItem(true); } } public static void setNBT(NBTItem nbtItem, Rarity rarity) { nbtItem.setString(NBT_KEY, rarity.name()); ItemTagsUtils.updateRarity(nbtItem.getItem(), rarity); } public static final Set<String> ALL_TAGS; public static final Set<String> ALL_TAGS_STRIPPED; static { Set<String> tags = new HashSet<>(Rarity.values().length); for (Rarity rarity : Rarity.values()) tags.add(rarity.getTag()); ALL_TAGS = Collections.unmodifiableSet(tags); Set<String> stripped = new HashSet<>(tags.size()); for (String tag : tags) stripped.add(StringUtils.stripColor(tag)); ALL_TAGS_STRIPPED = Collections.unmodifiableSet(stripped); } }
29.861386
118
0.69695
bd31ad4d51fa6949f6c6741520e99ac9fb7d29a9
155
/** * This package contains classes for configuring the current project. */ package net.ssehub.easy.producer.ui.productline_editor.project_configuration;
38.75
77
0.812903
e379c149fdfa14b231236b79fd01c7fbc3d97f2c
9,185
/** * Licensed to Cloudera, Inc. under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. 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 * * 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.cloudera.flume.core; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cloudera.flume.conf.Context; import com.cloudera.flume.conf.FlumeConfiguration; import com.cloudera.flume.conf.FlumeSpecException; import com.cloudera.flume.conf.SinkFactory.SinkBuilder; import com.cloudera.flume.reporter.ReportEvent; import com.cloudera.flume.reporter.Reportable; import com.cloudera.util.BackoffPolicy; import com.cloudera.util.CappedExponentialBackoff; import com.cloudera.util.MultipleIOException; import com.google.common.base.Preconditions; /** * This failover sink initially opens the primary and the backup attempts to to * append to the primary. If the primary fails, it falls back and appends to the * secondary. When the next message appears, it will continue to send to the * secondary until an initialBackoff time has elapsed. Once this has elapsed, an * attempt to reopen the primary and append to the primary. If the primary fails * again, backoff adjusted and we fall back to the secondary again. * * If we reach the secondary and it fails, the append calls will throw an * exception. * * These can be chained if multiple failovers are desired. (failover to another * failover). To save on open handles or connections, one can wrap the secondary * with a lazyOpen decorator */ public class BackOffFailOverSink extends EventSink.Base { static final Logger LOG = LoggerFactory.getLogger(BackOffFailOverSink.class); public static final String A_PRIMARY = "sentPrimary"; public static final String A_FAILS = "failsPrimary"; public static final String A_BACKUPS = "sentBackups"; final EventSink primary; final EventSink backup; AtomicLong primarySent = new AtomicLong(); AtomicLong fails = new AtomicLong(); AtomicLong backups = new AtomicLong(); boolean primaryOk = false; boolean backupOpen = false; final BackoffPolicy backoffPolicy; public BackOffFailOverSink(EventSink primary, EventSink backup, BackoffPolicy backoff) { Preconditions.checkNotNull(primary, "BackOffFailOverSink called with null primary"); Preconditions.checkNotNull(backup, "BackOffFailOverSink called with null backup"); this.primary = primary; this.backup = backup; this.backoffPolicy = backoff; } public BackOffFailOverSink(EventSink primary, EventSink backup) { this(primary, backup, FlumeConfiguration.get().getFailoverInitialBackoff(), FlumeConfiguration.get().getFailoverMaxSingleBackoff()); } public BackOffFailOverSink(EventSink primary, EventSink backup, long initialBackoff, long maxBackoff) { this(primary, backup, new CappedExponentialBackoff(initialBackoff, maxBackoff)); } @Override public void append(Event e) throws IOException, InterruptedException { // we know primary has already failed, and it is time to retry it. if (!primaryOk) { if (backoffPolicy.isRetryOk()) { // attempt to recover primary. IOException ioe = tryOpenPrimary(); if (ioe != null) { // reopen attempt failed, add to backoff, and fall back to backup. if // backup fails, give up backoffPolicy.backoff(); try { // fall back onto secondary after primary retry failure. backup.append(e); // attempt on secondary. backups.incrementAndGet(); super.append(e); return; } catch (IOException ioe2) { // complete failure case. List<IOException> exceptions = new ArrayList<IOException>(2); exceptions.add(ioe); exceptions.add(ioe2); IOException mio = MultipleIOException.createIOException(exceptions); throw mio; } } } else { // not ready to retry, fall back to secondary. backup.append(e); backups.incrementAndGet(); super.append(e); return; } } // ideal case -- primary is open. try { primary.append(e); primarySent.incrementAndGet(); super.append(e); primaryOk = true; backoffPolicy.reset(); // successfully sent with primary, so backoff // isreset return; } catch (IOException ioe3) { LOG.info(ioe3.getMessage()); fails.incrementAndGet(); primaryOk = false; backoffPolicy.backoff(); backup.append(e); backups.incrementAndGet(); super.append(e); } } @Override public void close() throws IOException, InterruptedException { List<IOException> exs = new ArrayList<IOException>(2); try { if (primaryOk) primary.close(); } catch (IOException ex) { exs.add(ex); } try { if (backupOpen) backup.close(); } catch (IOException ex) { exs.add(ex); } if (exs.size() != 0) { throw MultipleIOException.createIOException(exs); } } IOException tryOpenPrimary() throws InterruptedException { IOException priEx = null; try { if (!primaryOk) { primary.close(); primary.open(); primaryOk = true; } } catch (IOException ex) { try { primary.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } primaryOk = false; priEx = ex; } return priEx; } @Override public void open() throws IOException, InterruptedException { IOException priEx = tryOpenPrimary(); if (Thread.currentThread().isInterrupted()) { LOG.error("Backoff Failover sink exited because of interruption"); throw new IOException("Was interrupted, bailing out"); } try { // this could be opened lazily backup.open(); backupOpen = true; } catch (IOException ex) { backupOpen = false; if (priEx != null) { // both failed, throw multi exception IOException mioe = MultipleIOException.createIOException(Arrays.asList( priEx, ex)); throw mioe; } // if the primary was ok, just continue. (if primary fails, will attempt // to open backup again before falling back on it) } } public EventSink getPrimary() { return primary; } public EventSink getBackup() { return backup; } @Override public String getName() { return "BackoffFailover"; } @Deprecated @Override public ReportEvent getReport() { ReportEvent rpt = super.getReport(); rpt.setLongMetric(A_FAILS, fails.get()); rpt.setLongMetric(A_BACKUPS, backups.get()); rpt.setLongMetric(A_PRIMARY, primarySent.get()); return rpt; } @Deprecated @Override public void getReports(String namePrefix, Map<String, ReportEvent> reports) { super.getReports(namePrefix, reports); primary.getReports(namePrefix + getName() + ".primary.", reports); backup.getReports(namePrefix + getName() + ".backup.", reports); } @Override public ReportEvent getMetrics() { ReportEvent e = super.getMetrics(); e.setLongMetric(A_FAILS, fails.get()); e.setLongMetric(A_BACKUPS, backups.get()); e.setLongMetric(A_PRIMARY, primarySent.get()); return e; } @Override public Map<String, Reportable> getSubMetrics() { Map<String, Reportable> map = new HashMap<String, Reportable>(); map.put("primary." + primary.getName(), primary); map.put("backup." + backup.getName(), backup); return map; } public long getFails() { return fails.get(); } public static SinkBuilder builder() { return new SinkBuilder() { @Override public EventSink build(Context context, String... argv) { Preconditions.checkArgument(argv.length == 2); String primary = argv[0]; String secondary = argv[1]; try { EventSink pri = new CompositeSink(context, primary); EventSink sec = new CompositeSink(context, secondary); return new BackOffFailOverSink(pri, sec); } catch (FlumeSpecException e) { LOG.warn("Spec parsing problem", e); throw new IllegalArgumentException("Spec parsing problem", e); } } }; } }
30.616667
80
0.670985
f86fe41a07438e78d5512da48da85c1456672ae1
456
package com.surgical.decision3.common.bean.player; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Root; @Root public class PlayCase { @Attribute(required=false) int id; @Attribute(required=false) int case_id; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCase_id() { return case_id; } public void setCase_id(int case_id) { this.case_id = case_id; } }
13.028571
50
0.70614
2b162f9a2c46bffaae411de8da61dc80881ee8b6
769
package lexer; public class LexerException extends Exception { private static final long serialVersionUID = -8673728574812248899L; public final int line; public final int character; public final Object[] avaiableCharacter; public LexerException(int line, int character, Object[] avaiableCharacter) { this.line = line; this.character = character; this.avaiableCharacter = avaiableCharacter; } public void printLexerError() { System.err.println("Rilevato un errore durante l'analisi lessicale."); System.err.println("Errore alla riga: " + (this.line + 1)); System.err.println("Carattere rilevato: " + this.character); System.err.println("Caratteri accettati: "); for(Object o : this.avaiableCharacter) System.err.print(o + " "); } }
28.481481
77
0.736021
d3e2629932f80f9974ef33f8e0fd0580d8a20136
2,388
package org.jdb2de.core.data; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.io.Serializable; /** * * @author Rodrigo Tavares */ @Component @Scope(value = "singleton") public class ConnectionConfigurationData implements Serializable { /** * Serial Version UID */ private static final long serialVersionUID = -1229916425332251970L; /** * Driver class */ private String driver; /** * Database connection url */ private String url; /** * Database user name */ private String userName; /** * Database password */ private String password; /** * Database schema */ private String schema; /** * Database catalog */ private String catalog; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; } @Override public boolean equals(Object obj) { return Objects.equal(this, obj); } @Override public int hashCode() { return Objects.hashCode(driver, url, userName, password, schema, catalog); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("driver", driver) .add("url", url) .add("userName", userName) .add("password", password) .add("schema", schema) .add("catalog", catalog) .toString(); } }
19.414634
82
0.585427
b3af6254be576ed4c4085b6242cca80b515b46a2
2,178
package com.cuiot.openservices.sdk.entity.request; import com.cuiot.openservices.sdk.entity.ICheck; import com.cuiot.openservices.sdk.util.Utils; import io.netty.util.internal.StringUtil; import java.util.ArrayList; import java.util.List; /** * 请求参数params:事件上报 * * @author yht */ public class ParamsEventPub implements ICheck { private String key; private String ts = String.valueOf(System.currentTimeMillis()); private List<EventItem> info = new ArrayList<>(); public ParamsEventPub() { } public ParamsEventPub(String key) { this.key = key; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getTs() { return ts; } public void setTs(String ts) { this.ts = ts; } public List<EventItem> getInfo() { return info; } public void setInfo(List<EventItem> info) { this.info = info; } public void addEventItem(String key, Object value) { EventItem eventItem = new EventItem(key, value); info.add(eventItem); } @Override public boolean checkLegal() { if (StringUtil.isNullOrEmpty(key) || Utils.isEmpty(info)) { return false; } for (EventItem eventItem : info) { if (!eventItem.checkLegal()) { return false; } } return true; } public static class EventItem implements ICheck { private String key; private Object value; public EventItem() { } public EventItem(String key, Object value) { this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } @Override public boolean checkLegal() { return !StringUtil.isNullOrEmpty(key) && value != null; } } }
20.942308
67
0.565197
d5e6df82f4811c6261b29b3702d4435aacffb81c
2,061
package cpath.web; import cpath.service.Settings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Profile; import org.springframework.web.bind.annotation.RestController; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.Collections; @Configuration @Profile("web") @EnableSwagger2 @Import(BeanValidatorPluginsConfiguration.class) //JSR-303 (if controllers have bean args and validation annotations) public class SpringFoxConfig { @Autowired Settings settings; @Bean public Docket apiDocket() { return new Docket(DocumentationType.SWAGGER_2) .select() // .apis(RequestHandlerSelectors.any()) //this then shows Spring actuators, swagger, etc.. // .apis(RequestHandlerSelectors.basePackage("cpath.web")) .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) .paths(PathSelectors.any()) .build() .useDefaultResponseMessages(false) .apiInfo(getApiInfo()); } private ApiInfo getApiInfo() { return new ApiInfo( settings.getName() + " " + settings.getVersion(), "cPath2 RESTful web services", "11", null, new Contact("Pathway Commons", "http://www.pathwaycommons.org", "pathway-commons-help@googlegroups.com" ), "MIT", "https://raw.githubusercontent.com/PathwayCommons/cpath2/master/LICENSE", Collections.emptyList() ); } }
34.932203
117
0.764677
c064f0ff80884ccfa2f6e191a67476cc8a3e1d6f
658
package tk.ddvudo.multiThread.ThreadState; public class Testskill extends Thread { private Integer TimesCount = 0; @Override public void run() { while (true) { try { if (TimesCount < 3) { System.out.println("doing skill"); Thread.sleep(1000); TimesCount++; } else { System.out.println("reloading..."); Thread.sleep(5000); TimesCount = 0; } } catch (InterruptedException e) { e.printStackTrace(); } } } }
26.32
55
0.43921
f6d786068cc5ba6fe951b49d6c837865499d81d2
3,254
/* * Copyright 2014 NAVER Corp. * * 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.navercorp.pinpoint.profiler.jdbc; import com.navercorp.pinpoint.common.util.MapUtils; import com.navercorp.pinpoint.common.util.StringUtils; import java.util.Map; /** * duplicate : com.navercorp.pinpoint.profiler.modifier.db.interceptor.BindValueUtils * @author emeroad */ public final class BindValueUtils { private BindValueUtils() { } public static String bindValueToString(final Map<Integer, String> bindValueMap, int limit) { if (MapUtils.isEmpty(bindValueMap)) { return ""; } final int maxParameterIndex = getMaxParameterIndex(bindValueMap); if (maxParameterIndex <= 0) { return ""; } final String[] temp = new String[maxParameterIndex]; for (Map.Entry<Integer, String> entry : bindValueMap.entrySet()) { final int parameterIndex = entry.getKey() - 1; if (parameterIndex < 0) { // invalid index. PreparedStatement first parameterIndex is 1 continue; } if (temp.length <= parameterIndex) { continue; } temp[parameterIndex] = entry.getValue(); } return bindValueToString(temp, limit); } private static int getMaxParameterIndex(Map<Integer, String> bindValueMap) { int maxIndex = 0; for (Integer idx : bindValueMap.keySet()) { maxIndex = Math.max(maxIndex, idx); } return maxIndex; } public static String bindValueToString(String[] bindValueArray, int limit) { if (bindValueArray == null) { return ""; } final StringBuilder sb = new StringBuilder(32); final int length = bindValueArray.length; final int end = length - 1; for (int i = 0; i < length; i++) { if (sb.length() >= limit) { // Appending omission postfix makes generating binded sql difficult. But without this, we cannot say if it's omitted or not. appendLength(sb, length); break; } final String bindValue = StringUtils.defaultString(bindValueArray[i], ""); StringUtils.appendAbbreviate(sb, bindValue, limit); if (i < end) { sb.append(", "); } } return sb.toString(); } private static void appendLength(StringBuilder sb, int length) { sb.append("...("); sb.append(length); sb.append(')'); } public static String bindValueToString(String[] stringArray) { return bindValueToString(stringArray, Integer.MAX_VALUE); } }
33.546392
140
0.617701
8835e45b5df3f09601723ca4d861871ca492723e
212
package com.norswap.autumn.test.languages.clike; import com.norswap.autumn.state.patterns.OutputAccumulator; public class CLikeState extends OutputAccumulator<String> { { items.push("int"); } }
19.272727
59
0.735849
9cfb8e4022c3f176ec59827b4707f05deb3f2016
237
package com.cvdnn.exception; public class OnMainThreadException extends RuntimeException { public OnMainThreadException() { super(); } public OnMainThreadException(String message) { super(message); } }
18.230769
61
0.687764
72df16a593bf1f81cb72727a8b3be770daf36df2
675
package com.example.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; // http://localhost:6100 /gateway /lottery /api/v1 /numbers?column=3 // server.servlet.context-path=/gateway /\ /\ /\ // spring.application.name=lottery ------------| | | // spring.mvc.servlet.path=/api/v1 ---------------------| | // @RestController @RequestMapping("/numbers") -----------------| @SpringBootApplication public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
35.526316
83
0.632593
59da4d93e481c1271783ab078638ecb13f155a0a
2,758
package de.tinycodecrank.xmlConfig4J.parser.assignable; import static de.tinycodecrank.xmlConfig4J.utils.Utils.*; import java.lang.reflect.InvocationTargetException; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import de.tinycodecrank.xmlConfig4J.LoadHelper; import de.tinycodecrank.xmlConfig4J.SaveHelper; public class SetParser implements ParserAssignable { private static final Logger log = LogManager.getLogger(SetParser.class); private static final String ITEM = "item"; @Override public boolean canParse(Class<?> type) { return Set.class.isAssignableFrom(type); } @Override public void save(Element element, Object container, Document document, SaveHelper saveHelper) { if (container == null) { element.setAttribute(NULL, TRUE); } else { String setType = container.getClass().getName(); setType = saveHelper.getMapping(setType); element.setAttribute(TYPE, setType); Set<?> set = (Set<?>) container; for (Object o : set) { try { Element item = saveHelper.saveObject(ITEM, o, document); if(o != null) { item.setAttribute(TYPE, saveHelper.getMapping(o.getClass().getName())); } element.appendChild(item); } catch (IllegalArgumentException | IllegalAccessException e) { log.error(e::getMessage, e); } } } } @SuppressWarnings("unchecked") @Override public Object load(Class<?> type, Node node, LoadHelper loadHelper) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { if (loadIsNotNull(node, loadHelper) && type != null) { @SuppressWarnings("rawtypes") Set set = (Set) type.getDeclaredConstructor().newInstance(); NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node item = nodeList.item(i); if (loadIsNotNull(item, loadHelper)) { try { String itemType = getAttribute(item, TYPE).getValue(); Class<?> itemClass = loadHelper.getClass(loadHelper.getType(itemType)); Object oItem = loadHelper.loadFromNode(itemClass, item); set.add(oItem); } catch ( ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { log.error(e::getMessage, e); } } else { set.add(null); } } return set; } else { return null; } } }
23.982609
94
0.687092
84a4413de5dda7925ce2d8d5eb42ad298fb3750d
2,488
package org.thingsboard.server.dft.repositories; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.dao.model.sql.AuditLogEntity; import java.util.List; import java.util.UUID; public interface AccessHistoryRepository extends JpaRepository<AuditLogEntity, UUID> { AuditLogEntity findAuditLogEntityByTenantIdAndUserIdAndId(UUID tenantId, UUID userId, UUID id); // @Query("SELECT a FROM AuditLogEntity a WHERE " + // "a.tenantId = :tenantId " + // "AND (:startTime IS NULL OR a.createdTime >= :startTime) " + // "AND (:endTime IS NULL OR a.createdTime <= :endTime) " + // "AND ((:entityType) IS NULL OR a.entityType in (:entityType)) " + // "AND (LOWER(a.entityType) LIKE LOWER(CONCAT(:textSearch, '%'))" + // "OR LOWER(a.entityName) LIKE LOWER(CONCAT(:textSearch, '%'))" + // "OR LOWER(a.userName) LIKE LOWER(CONCAT(:textSearch, '%'))" + // "OR LOWER(a.actionType) LIKE LOWER(CONCAT(:textSearch, '%'))" + // "OR LOWER(a.actionStatus) LIKE LOWER(CONCAT(:textSearch, '%')))" // ) // binh dv - tim kiem theo doi tuong (entityName) va tai khoan tac dong (userName) @Query("SELECT a FROM AuditLogEntity a WHERE " + "a.tenantId = :tenantId " + "AND (:startTime IS NULL OR a.createdTime >= :startTime) " + "AND (:endTime IS NULL OR a.createdTime <= :endTime) " + "AND ((:entityType) IS NULL OR a.entityType in (:entityType)) " + "AND (LOWER(a.entityName) LIKE LOWER(CONCAT('%', :textSearch, '%'))" + "OR LOWER(a.userName) LIKE LOWER(CONCAT('%', :textSearch, '%')))" ) Page<AuditLogEntity> findByTenantId( @Param("tenantId") UUID tenantId, @Param("textSearch") String textSearch, @Param("startTime") Long startTime, @Param("endTime") Long endTime, @Param("entityType") List<EntityType> entityType, Pageable pageable); boolean existsByTenantIdAndUserNameAndActionType(UUID tenantId, String username, ActionType actionType); }
47.846154
108
0.647508
0d58b86400e33bc30ac945183f6e7df8ffc7bb2a
4,361
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.analyze; import io.crate.expression.eval.EvaluatingNormalizer; import io.crate.expression.symbol.Literal; import io.crate.expression.symbol.Symbol; import io.crate.metadata.TransactionContext; import io.crate.testing.SqlExpressions; import io.crate.testing.T3; import org.junit.Test; import static io.crate.testing.TestingHelpers.getFunctions; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class WhereClauseTest { private SqlExpressions sqlExpressions = new SqlExpressions(T3.SOURCES); @Test public void testReplaceWithLiteralTrueSemantics() throws Exception { Symbol query = sqlExpressions.asSymbol("x = 10"); WhereClause whereReplaced = new WhereClause(query); whereReplaced.replace(s -> Literal.BOOLEAN_TRUE); WhereClause whereLiteralTrue = new WhereClause(Literal.BOOLEAN_TRUE); assertThat(whereLiteralTrue.hasQuery(), is(whereReplaced.hasQuery())); assertThat(whereLiteralTrue.noMatch(), is(whereReplaced.noMatch())); assertThat(whereLiteralTrue.query(), is(whereReplaced.query())); } @Test public void testReplaceWithLiteralFalseSemantics() throws Exception { Symbol query = sqlExpressions.asSymbol("x = 10"); WhereClause whereReplaced = new WhereClause(query); whereReplaced.replace(s -> Literal.BOOLEAN_FALSE); WhereClause whereLiteralFalse = new WhereClause(Literal.BOOLEAN_FALSE); assertThat(whereLiteralFalse.hasQuery(), is(whereReplaced.hasQuery())); assertThat(whereLiteralFalse.noMatch(), is(whereReplaced.noMatch())); assertThat(whereLiteralFalse.query(), is(whereReplaced.query())); } @Test public void testNormalizeEliminatesNulls() { WhereClause where = new WhereClause(sqlExpressions.asSymbol("null or x = 10 or a = null")); WhereClause normalizedWhere = where.normalize( EvaluatingNormalizer.functionOnlyNormalizer(getFunctions()), TransactionContext.systemTransactionContext()); assertThat(normalizedWhere.query(), is(sqlExpressions.asSymbol("x = 10"))); } @Test public void testAddWithNoMatch() { WhereClause where1 = WhereClause.NO_MATCH; WhereClause where2 = new WhereClause(sqlExpressions.asSymbol("x = 10")); WhereClause where1_where2 = where1.add(where2.query); assertThat(where1_where2.hasQuery(), is(false)); assertThat(where1_where2.noMatch, is(true)); } @Test public void testAddWithMatchAll() { WhereClause where1 = WhereClause.MATCH_ALL; WhereClause where2 = new WhereClause(sqlExpressions.asSymbol("x = 10")); WhereClause where1_where2 = where1.add(where2.query); assertThat(where1_where2.hasQuery(), is(true)); assertThat(where1_where2.noMatch, is(false)); assertThat(where1_where2.query(), is(where2.query())); } @Test public void testAddWithNullQuery() { WhereClause where1 = new WhereClause((Symbol) null); WhereClause where2 = new WhereClause(sqlExpressions.asSymbol("x = 10")); WhereClause where1_where2 = where1.add(where2.query); assertThat(where1_where2.hasQuery(), is(true)); assertThat(where1_where2.noMatch, is(false)); assertThat(where1_where2.query(), is(where2.query())); } }
40.757009
120
0.723687
7513dd881deb8cc3e2d97c5f03996006a8448200
1,508
package com.github.llamarama.team.block; import com.github.llamarama.team.Llamarama; import com.github.llamarama.team.util.IdBuilder; import net.minecraft.block.AbstractBlock; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; import org.jetbrains.annotations.NotNull; @SuppressWarnings("unused") public final class ModBlocks { public static final Block LLAMA_WOOL = register(new Block(AbstractBlock.Settings.copy(Blocks.WHITE_WOOL)), "llama_wool"); public static final Block RUG = register(new RugBlock(AbstractBlock.Settings.copy(Blocks.WHITE_CARPET)), "rug"); public static final Block LLAMA_WOOL_BED = registerNoItem(new LlamaWoolBedBlock(AbstractBlock.Settings.copy(Blocks.WHITE_BED)), "llama_wool_bed"); private ModBlocks() { } @SuppressWarnings("EmptyMethod") public static void init() { } @NotNull private static Block register(Block block, String id) { Identifier identifier = IdBuilder.of(id); Registry.register(Registry.ITEM, identifier, new BlockItem(block, new Item.Settings().group(Llamarama.LLAMA_ITEM_GROUP))); return registerNoItem(block, id); } @NotNull private static Block registerNoItem(Block block, String id) { return Registry.register(Registry.BLOCK, IdBuilder.of(id), block); } }
33.511111
130
0.737401
a7dc6687719e93d7b279da3b11cf4960dc8563a5
86
package edu.ucam.enums; public enum Convocatoria { FEBRERO, JUNIO, SEPTIEMBRE; }
10.75
28
0.732558
1dfbe85f7f56a4831d3c1ebc29918d351546d17c
31,907
package org.apache.xerces.impl.dtd; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLChar; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.XMLDTDContentModelHandler; import org.apache.xerces.xni.XMLDTDHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDTDContentModelFilter; import org.apache.xerces.xni.parser.XMLDTDContentModelSource; import org.apache.xerces.xni.parser.XMLDTDFilter; import org.apache.xerces.xni.parser.XMLDTDSource; public class XMLDTDProcessor implements XMLComponent, XMLDTDContentModelFilter, XMLDTDFilter { private static final int TOP_LEVEL_SCOPE = -1; protected static final String VALIDATION = "http://xml.org/sax/features/validation"; protected static final String NOTIFY_CHAR_REFS = "http://apache.org/xml/features/scanner/notify-char-refs"; protected static final String WARN_ON_DUPLICATE_ATTDEF = "http://apache.org/xml/features/validation/warn-on-duplicate-attdef"; protected static final String WARN_ON_UNDECLARED_ELEMDEF = "http://apache.org/xml/features/validation/warn-on-undeclared-elemdef"; protected static final String PARSER_SETTINGS = "http://apache.org/xml/features/internal/parser-settings"; protected static final String SYMBOL_TABLE = "http://apache.org/xml/properties/internal/symbol-table"; protected static final String ERROR_REPORTER = "http://apache.org/xml/properties/internal/error-reporter"; protected static final String GRAMMAR_POOL = "http://apache.org/xml/properties/internal/grammar-pool"; protected static final String DTD_VALIDATOR = "http://apache.org/xml/properties/internal/validator/dtd"; private static final String[] RECOGNIZED_FEATURES = new String[] { "http://xml.org/sax/features/validation", "http://apache.org/xml/features/validation/warn-on-duplicate-attdef", "http://apache.org/xml/features/validation/warn-on-undeclared-elemdef", "http://apache.org/xml/features/scanner/notify-char-refs" }; private static final Boolean[] FEATURE_DEFAULTS = new Boolean[] { null, Boolean.FALSE, Boolean.FALSE, null }; private static final String[] RECOGNIZED_PROPERTIES = new String[] { "http://apache.org/xml/properties/internal/symbol-table", "http://apache.org/xml/properties/internal/error-reporter", "http://apache.org/xml/properties/internal/grammar-pool", "http://apache.org/xml/properties/internal/validator/dtd" }; private static final Object[] PROPERTY_DEFAULTS = new Object[] { null, null, null, null }; protected boolean fValidation; protected boolean fDTDValidation; protected boolean fWarnDuplicateAttdef; protected boolean fWarnOnUndeclaredElemdef; protected SymbolTable fSymbolTable; protected XMLErrorReporter fErrorReporter; protected DTDGrammarBucket fGrammarBucket; protected XMLDTDValidator fValidator; protected XMLGrammarPool fGrammarPool; protected Locale fLocale; protected XMLDTDHandler fDTDHandler; protected XMLDTDSource fDTDSource; protected XMLDTDContentModelHandler fDTDContentModelHandler; protected XMLDTDContentModelSource fDTDContentModelSource; protected DTDGrammar fDTDGrammar; private boolean fPerformValidation; protected boolean fInDTDIgnore; private boolean fMixed; private final XMLEntityDecl fEntityDecl = new XMLEntityDecl(); private final HashMap fNDataDeclNotations = new HashMap(); private String fDTDElementDeclName = null; private final ArrayList fMixedElementTypes = new ArrayList(); private final ArrayList fDTDElementDecls = new ArrayList(); private HashMap fTableOfIDAttributeNames; private HashMap fTableOfNOTATIONAttributeNames; private HashMap fNotationEnumVals; public void reset(XMLComponentManager paramXMLComponentManager) throws XMLConfigurationException { boolean bool; try { bool = paramXMLComponentManager.getFeature("http://apache.org/xml/features/internal/parser-settings"); } catch (XMLConfigurationException xMLConfigurationException) { bool = true; } if (!bool) { reset(); return; } try { this.fValidation = paramXMLComponentManager.getFeature("http://xml.org/sax/features/validation"); } catch (XMLConfigurationException xMLConfigurationException) { this.fValidation = false; } try { this.fDTDValidation = !paramXMLComponentManager.getFeature("http://apache.org/xml/features/validation/schema"); } catch (XMLConfigurationException xMLConfigurationException) { this.fDTDValidation = true; } try { this.fWarnDuplicateAttdef = paramXMLComponentManager.getFeature("http://apache.org/xml/features/validation/warn-on-duplicate-attdef"); } catch (XMLConfigurationException xMLConfigurationException) { this.fWarnDuplicateAttdef = false; } try { this.fWarnOnUndeclaredElemdef = paramXMLComponentManager.getFeature("http://apache.org/xml/features/validation/warn-on-undeclared-elemdef"); } catch (XMLConfigurationException xMLConfigurationException) { this.fWarnOnUndeclaredElemdef = false; } this.fErrorReporter = (XMLErrorReporter)paramXMLComponentManager.getProperty("http://apache.org/xml/properties/internal/error-reporter"); this.fSymbolTable = (SymbolTable)paramXMLComponentManager.getProperty("http://apache.org/xml/properties/internal/symbol-table"); try { this.fGrammarPool = (XMLGrammarPool)paramXMLComponentManager.getProperty("http://apache.org/xml/properties/internal/grammar-pool"); } catch (XMLConfigurationException xMLConfigurationException) { this.fGrammarPool = null; } try { this.fValidator = (XMLDTDValidator)paramXMLComponentManager.getProperty("http://apache.org/xml/properties/internal/validator/dtd"); } catch (XMLConfigurationException xMLConfigurationException) { this.fValidator = null; } catch (ClassCastException classCastException) { this.fValidator = null; } if (this.fValidator != null) { this.fGrammarBucket = this.fValidator.getGrammarBucket(); } else { this.fGrammarBucket = null; } reset(); } protected void reset() { this.fDTDGrammar = null; this.fInDTDIgnore = false; this.fNDataDeclNotations.clear(); if (this.fValidation) { if (this.fNotationEnumVals == null) this.fNotationEnumVals = new HashMap(); this.fNotationEnumVals.clear(); this.fTableOfIDAttributeNames = new HashMap(); this.fTableOfNOTATIONAttributeNames = new HashMap(); } } public String[] getRecognizedFeatures() { return (String[])RECOGNIZED_FEATURES.clone(); } public void setFeature(String paramString, boolean paramBoolean) throws XMLConfigurationException {} public String[] getRecognizedProperties() { return (String[])RECOGNIZED_PROPERTIES.clone(); } public void setProperty(String paramString, Object paramObject) throws XMLConfigurationException {} public Boolean getFeatureDefault(String paramString) { for (byte b = 0; b < RECOGNIZED_FEATURES.length; b++) { if (RECOGNIZED_FEATURES[b].equals(paramString)) return FEATURE_DEFAULTS[b]; } return null; } public Object getPropertyDefault(String paramString) { for (byte b = 0; b < RECOGNIZED_PROPERTIES.length; b++) { if (RECOGNIZED_PROPERTIES[b].equals(paramString)) return PROPERTY_DEFAULTS[b]; } return null; } public void setDTDHandler(XMLDTDHandler paramXMLDTDHandler) { this.fDTDHandler = paramXMLDTDHandler; } public XMLDTDHandler getDTDHandler() { return this.fDTDHandler; } public void setDTDContentModelHandler(XMLDTDContentModelHandler paramXMLDTDContentModelHandler) { this.fDTDContentModelHandler = paramXMLDTDContentModelHandler; } public XMLDTDContentModelHandler getDTDContentModelHandler() { return this.fDTDContentModelHandler; } public void startExternalSubset(XMLResourceIdentifier paramXMLResourceIdentifier, Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.startExternalSubset(paramXMLResourceIdentifier, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.startExternalSubset(paramXMLResourceIdentifier, paramAugmentations); } public void endExternalSubset(Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.endExternalSubset(paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.endExternalSubset(paramAugmentations); } protected static void checkStandaloneEntityRef(String paramString, DTDGrammar paramDTDGrammar, XMLEntityDecl paramXMLEntityDecl, XMLErrorReporter paramXMLErrorReporter) throws XNIException { int i = paramDTDGrammar.getEntityDeclIndex(paramString); if (i > -1) { paramDTDGrammar.getEntityDecl(i, paramXMLEntityDecl); if (paramXMLEntityDecl.inExternal) paramXMLErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "MSG_REFERENCE_TO_EXTERNALLY_DECLARED_ENTITY_WHEN_STANDALONE", new Object[] { paramString }, (short)1); } } public void comment(XMLString paramXMLString, Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.comment(paramXMLString, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.comment(paramXMLString, paramAugmentations); } public void processingInstruction(String paramString, XMLString paramXMLString, Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.processingInstruction(paramString, paramXMLString, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.processingInstruction(paramString, paramXMLString, paramAugmentations); } public void startDTD(XMLLocator paramXMLLocator, Augmentations paramAugmentations) throws XNIException { this.fNDataDeclNotations.clear(); this.fDTDElementDecls.clear(); if (!this.fGrammarBucket.getActiveGrammar().isImmutable()) this.fDTDGrammar = this.fGrammarBucket.getActiveGrammar(); if (this.fDTDGrammar != null) this.fDTDGrammar.startDTD(paramXMLLocator, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.startDTD(paramXMLLocator, paramAugmentations); } public void ignoredCharacters(XMLString paramXMLString, Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.ignoredCharacters(paramXMLString, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.ignoredCharacters(paramXMLString, paramAugmentations); } public void textDecl(String paramString1, String paramString2, Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.textDecl(paramString1, paramString2, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.textDecl(paramString1, paramString2, paramAugmentations); } public void startParameterEntity(String paramString1, XMLResourceIdentifier paramXMLResourceIdentifier, String paramString2, Augmentations paramAugmentations) throws XNIException { if (this.fPerformValidation && this.fDTDGrammar != null && this.fGrammarBucket.getStandalone()) checkStandaloneEntityRef(paramString1, this.fDTDGrammar, this.fEntityDecl, this.fErrorReporter); if (this.fDTDGrammar != null) this.fDTDGrammar.startParameterEntity(paramString1, paramXMLResourceIdentifier, paramString2, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.startParameterEntity(paramString1, paramXMLResourceIdentifier, paramString2, paramAugmentations); } public void endParameterEntity(String paramString, Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.endParameterEntity(paramString, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.endParameterEntity(paramString, paramAugmentations); } public void elementDecl(String paramString1, String paramString2, Augmentations paramAugmentations) throws XNIException { if (this.fValidation) if (this.fDTDElementDecls.contains(paramString1)) { this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "MSG_ELEMENT_ALREADY_DECLARED", new Object[] { paramString1 }, (short)1); } else { this.fDTDElementDecls.add(paramString1); } if (this.fDTDGrammar != null) this.fDTDGrammar.elementDecl(paramString1, paramString2, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.elementDecl(paramString1, paramString2, paramAugmentations); } public void startAttlist(String paramString, Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.startAttlist(paramString, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.startAttlist(paramString, paramAugmentations); } public void attributeDecl(String paramString1, String paramString2, String paramString3, String[] paramArrayOfString, String paramString4, XMLString paramXMLString1, XMLString paramXMLString2, Augmentations paramAugmentations) throws XNIException { if (paramString3 != XMLSymbols.fCDATASymbol && paramXMLString1 != null) normalizeDefaultAttrValue(paramXMLString1); if (this.fValidation) { boolean bool1 = false; DTDGrammar dTDGrammar = (this.fDTDGrammar != null) ? this.fDTDGrammar : this.fGrammarBucket.getActiveGrammar(); int i = dTDGrammar.getElementDeclIndex(paramString1); if (dTDGrammar.getAttributeDeclIndex(i, paramString2) != -1) { bool1 = true; if (this.fWarnDuplicateAttdef) this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "MSG_DUPLICATE_ATTRIBUTE_DEFINITION", new Object[] { paramString1, paramString2 }, (short)0); } if (paramString3 == XMLSymbols.fIDSymbol) { if (paramXMLString1 != null && paramXMLString1.length != 0 && (paramString4 == null || (paramString4 != XMLSymbols.fIMPLIEDSymbol && paramString4 != XMLSymbols.fREQUIREDSymbol))) this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "IDDefaultTypeInvalid", new Object[] { paramString2 }, (short)1); if (!this.fTableOfIDAttributeNames.containsKey(paramString1)) { this.fTableOfIDAttributeNames.put(paramString1, paramString2); } else if (!bool1) { String str = (String)this.fTableOfIDAttributeNames.get(paramString1); this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "MSG_MORE_THAN_ONE_ID_ATTRIBUTE", new Object[] { paramString1, str, paramString2 }, (short)1); } } if (paramString3 == XMLSymbols.fNOTATIONSymbol) { for (byte b = 0; b < paramArrayOfString.length; b++) this.fNotationEnumVals.put(paramArrayOfString[b], paramString2); if (!this.fTableOfNOTATIONAttributeNames.containsKey(paramString1)) { this.fTableOfNOTATIONAttributeNames.put(paramString1, paramString2); } else if (!bool1) { String str = (String)this.fTableOfNOTATIONAttributeNames.get(paramString1); this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "MSG_MORE_THAN_ONE_NOTATION_ATTRIBUTE", new Object[] { paramString1, str, paramString2 }, (short)1); } } if (paramString3 == XMLSymbols.fENUMERATIONSymbol || paramString3 == XMLSymbols.fNOTATIONSymbol) { byte b; label108: for (b = 0; b < paramArrayOfString.length; b++) { for (int j = b + 1; j < paramArrayOfString.length; j++) { if (paramArrayOfString[b].equals(paramArrayOfString[j])) { this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", (paramString3 == XMLSymbols.fENUMERATIONSymbol) ? "MSG_DISTINCT_TOKENS_IN_ENUMERATION" : "MSG_DISTINCT_NOTATION_IN_ENUMERATION", new Object[] { paramString1, paramArrayOfString[b], paramString2 }, (short)1); break label108; } } } } boolean bool2 = true; if (paramXMLString1 != null && (paramString4 == null || (paramString4 != null && paramString4 == XMLSymbols.fFIXEDSymbol))) { String str = paramXMLString1.toString(); if (paramString3 == XMLSymbols.fNMTOKENSSymbol || paramString3 == XMLSymbols.fENTITIESSymbol || paramString3 == XMLSymbols.fIDREFSSymbol) { StringTokenizer stringTokenizer = new StringTokenizer(str, " "); if (stringTokenizer.hasMoreTokens()) do { String str1 = stringTokenizer.nextToken(); if (paramString3 == XMLSymbols.fNMTOKENSSymbol) { if (!isValidNmtoken(str1)) { bool2 = false; break; } } else if ((paramString3 == XMLSymbols.fENTITIESSymbol || paramString3 == XMLSymbols.fIDREFSSymbol) && !isValidName(str1)) { bool2 = false; break; } } while (stringTokenizer.hasMoreTokens()); } else { if (paramString3 == XMLSymbols.fENTITYSymbol || paramString3 == XMLSymbols.fIDSymbol || paramString3 == XMLSymbols.fIDREFSymbol || paramString3 == XMLSymbols.fNOTATIONSymbol) { if (!isValidName(str)) bool2 = false; } else if ((paramString3 == XMLSymbols.fNMTOKENSymbol || paramString3 == XMLSymbols.fENUMERATIONSymbol) && !isValidNmtoken(str)) { bool2 = false; } if (paramString3 == XMLSymbols.fNOTATIONSymbol || paramString3 == XMLSymbols.fENUMERATIONSymbol) { bool2 = false; for (byte b = 0; b < paramArrayOfString.length; b++) { if (paramXMLString1.equals(paramArrayOfString[b])) bool2 = true; } } } if (!bool2) this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "MSG_ATT_DEFAULT_INVALID", new Object[] { paramString2, str }, (short)1); } } if (this.fDTDGrammar != null) this.fDTDGrammar.attributeDecl(paramString1, paramString2, paramString3, paramArrayOfString, paramString4, paramXMLString1, paramXMLString2, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.attributeDecl(paramString1, paramString2, paramString3, paramArrayOfString, paramString4, paramXMLString1, paramXMLString2, paramAugmentations); } public void endAttlist(Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.endAttlist(paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.endAttlist(paramAugmentations); } public void internalEntityDecl(String paramString, XMLString paramXMLString1, XMLString paramXMLString2, Augmentations paramAugmentations) throws XNIException { DTDGrammar dTDGrammar = (this.fDTDGrammar != null) ? this.fDTDGrammar : this.fGrammarBucket.getActiveGrammar(); int i = dTDGrammar.getEntityDeclIndex(paramString); if (i == -1) { if (this.fDTDGrammar != null) this.fDTDGrammar.internalEntityDecl(paramString, paramXMLString1, paramXMLString2, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.internalEntityDecl(paramString, paramXMLString1, paramXMLString2, paramAugmentations); } } public void externalEntityDecl(String paramString, XMLResourceIdentifier paramXMLResourceIdentifier, Augmentations paramAugmentations) throws XNIException { DTDGrammar dTDGrammar = (this.fDTDGrammar != null) ? this.fDTDGrammar : this.fGrammarBucket.getActiveGrammar(); int i = dTDGrammar.getEntityDeclIndex(paramString); if (i == -1) { if (this.fDTDGrammar != null) this.fDTDGrammar.externalEntityDecl(paramString, paramXMLResourceIdentifier, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.externalEntityDecl(paramString, paramXMLResourceIdentifier, paramAugmentations); } } public void unparsedEntityDecl(String paramString1, XMLResourceIdentifier paramXMLResourceIdentifier, String paramString2, Augmentations paramAugmentations) throws XNIException { if (this.fValidation) this.fNDataDeclNotations.put(paramString1, paramString2); if (this.fDTDGrammar != null) this.fDTDGrammar.unparsedEntityDecl(paramString1, paramXMLResourceIdentifier, paramString2, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.unparsedEntityDecl(paramString1, paramXMLResourceIdentifier, paramString2, paramAugmentations); } public void notationDecl(String paramString, XMLResourceIdentifier paramXMLResourceIdentifier, Augmentations paramAugmentations) throws XNIException { if (this.fValidation) { DTDGrammar dTDGrammar = (this.fDTDGrammar != null) ? this.fDTDGrammar : this.fGrammarBucket.getActiveGrammar(); if (dTDGrammar.getNotationDeclIndex(paramString) != -1) this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "UniqueNotationName", new Object[] { paramString }, (short)1); } if (this.fDTDGrammar != null) this.fDTDGrammar.notationDecl(paramString, paramXMLResourceIdentifier, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.notationDecl(paramString, paramXMLResourceIdentifier, paramAugmentations); } public void startConditional(short paramShort, Augmentations paramAugmentations) throws XNIException { this.fInDTDIgnore = (paramShort == 1); if (this.fDTDGrammar != null) this.fDTDGrammar.startConditional(paramShort, paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.startConditional(paramShort, paramAugmentations); } public void endConditional(Augmentations paramAugmentations) throws XNIException { this.fInDTDIgnore = false; if (this.fDTDGrammar != null) this.fDTDGrammar.endConditional(paramAugmentations); if (this.fDTDHandler != null) this.fDTDHandler.endConditional(paramAugmentations); } public void endDTD(Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) { this.fDTDGrammar.endDTD(paramAugmentations); if (this.fGrammarPool != null) this.fGrammarPool.cacheGrammars("http://www.w3.org/TR/REC-xml", new Grammar[] { this.fDTDGrammar }); } if (this.fValidation) { DTDGrammar dTDGrammar = (this.fDTDGrammar != null) ? this.fDTDGrammar : this.fGrammarBucket.getActiveGrammar(); for (Map.Entry entry : this.fNDataDeclNotations.entrySet()) { String str = (String)entry.getValue(); if (dTDGrammar.getNotationDeclIndex(str) == -1) { String str1 = (String)entry.getKey(); this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "MSG_NOTATION_NOT_DECLARED_FOR_UNPARSED_ENTITYDECL", new Object[] { str1, str }, (short)1); } } for (Map.Entry entry : this.fNotationEnumVals.entrySet()) { String str = (String)entry.getKey(); if (dTDGrammar.getNotationDeclIndex(str) == -1) { String str1 = (String)entry.getValue(); this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "MSG_NOTATION_NOT_DECLARED_FOR_NOTATIONTYPE_ATTRIBUTE", new Object[] { str1, str }, (short)1); } } for (Map.Entry entry : this.fTableOfNOTATIONAttributeNames.entrySet()) { String str = (String)entry.getKey(); int i = dTDGrammar.getElementDeclIndex(str); if (dTDGrammar.getContentSpecType(i) == 1) { String str1 = (String)entry.getValue(); this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "NoNotationOnEmptyElement", new Object[] { str, str1 }, (short)1); } } this.fTableOfIDAttributeNames = null; this.fTableOfNOTATIONAttributeNames = null; if (this.fWarnOnUndeclaredElemdef) checkDeclaredElements(dTDGrammar); } if (this.fDTDHandler != null) this.fDTDHandler.endDTD(paramAugmentations); } public void setDTDSource(XMLDTDSource paramXMLDTDSource) { this.fDTDSource = paramXMLDTDSource; } public XMLDTDSource getDTDSource() { return this.fDTDSource; } public void setDTDContentModelSource(XMLDTDContentModelSource paramXMLDTDContentModelSource) { this.fDTDContentModelSource = paramXMLDTDContentModelSource; } public XMLDTDContentModelSource getDTDContentModelSource() { return this.fDTDContentModelSource; } public void startContentModel(String paramString, Augmentations paramAugmentations) throws XNIException { if (this.fValidation) { this.fDTDElementDeclName = paramString; this.fMixedElementTypes.clear(); } if (this.fDTDGrammar != null) this.fDTDGrammar.startContentModel(paramString, paramAugmentations); if (this.fDTDContentModelHandler != null) this.fDTDContentModelHandler.startContentModel(paramString, paramAugmentations); } public void any(Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.any(paramAugmentations); if (this.fDTDContentModelHandler != null) this.fDTDContentModelHandler.any(paramAugmentations); } public void empty(Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.empty(paramAugmentations); if (this.fDTDContentModelHandler != null) this.fDTDContentModelHandler.empty(paramAugmentations); } public void startGroup(Augmentations paramAugmentations) throws XNIException { this.fMixed = false; if (this.fDTDGrammar != null) this.fDTDGrammar.startGroup(paramAugmentations); if (this.fDTDContentModelHandler != null) this.fDTDContentModelHandler.startGroup(paramAugmentations); } public void pcdata(Augmentations paramAugmentations) { this.fMixed = true; if (this.fDTDGrammar != null) this.fDTDGrammar.pcdata(paramAugmentations); if (this.fDTDContentModelHandler != null) this.fDTDContentModelHandler.pcdata(paramAugmentations); } public void element(String paramString, Augmentations paramAugmentations) throws XNIException { if (this.fMixed && this.fValidation) if (this.fMixedElementTypes.contains(paramString)) { this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "DuplicateTypeInMixedContent", new Object[] { this.fDTDElementDeclName, paramString }, (short)1); } else { this.fMixedElementTypes.add(paramString); } if (this.fDTDGrammar != null) this.fDTDGrammar.element(paramString, paramAugmentations); if (this.fDTDContentModelHandler != null) this.fDTDContentModelHandler.element(paramString, paramAugmentations); } public void separator(short paramShort, Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.separator(paramShort, paramAugmentations); if (this.fDTDContentModelHandler != null) this.fDTDContentModelHandler.separator(paramShort, paramAugmentations); } public void occurrence(short paramShort, Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.occurrence(paramShort, paramAugmentations); if (this.fDTDContentModelHandler != null) this.fDTDContentModelHandler.occurrence(paramShort, paramAugmentations); } public void endGroup(Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.endGroup(paramAugmentations); if (this.fDTDContentModelHandler != null) this.fDTDContentModelHandler.endGroup(paramAugmentations); } public void endContentModel(Augmentations paramAugmentations) throws XNIException { if (this.fDTDGrammar != null) this.fDTDGrammar.endContentModel(paramAugmentations); if (this.fDTDContentModelHandler != null) this.fDTDContentModelHandler.endContentModel(paramAugmentations); } private boolean normalizeDefaultAttrValue(XMLString paramXMLString) { boolean bool = true; int i = paramXMLString.offset; int j = paramXMLString.offset + paramXMLString.length; for (int k = paramXMLString.offset; k < j; k++) { if (paramXMLString.ch[k] == ' ') { if (!bool) { paramXMLString.ch[i++] = ' '; bool = true; } } else { if (i != k) paramXMLString.ch[i] = paramXMLString.ch[k]; i++; bool = false; } } if (i != j) { if (bool) i--; paramXMLString.length = i - paramXMLString.offset; return true; } return false; } protected boolean isValidNmtoken(String paramString) { return XMLChar.isValidNmtoken(paramString); } protected boolean isValidName(String paramString) { return XMLChar.isValidName(paramString); } private void checkDeclaredElements(DTDGrammar paramDTDGrammar) { int i = paramDTDGrammar.getFirstElementDeclIndex(); XMLContentSpec xMLContentSpec = new XMLContentSpec(); while (i >= 0) { short s = paramDTDGrammar.getContentSpecType(i); if (s == 3 || s == 2) checkDeclaredElements(paramDTDGrammar, i, paramDTDGrammar.getContentSpecIndex(i), xMLContentSpec); i = paramDTDGrammar.getNextElementDeclIndex(i); } } private void checkDeclaredElements(DTDGrammar paramDTDGrammar, int paramInt1, int paramInt2, XMLContentSpec paramXMLContentSpec) { paramDTDGrammar.getContentSpec(paramInt2, paramXMLContentSpec); if (paramXMLContentSpec.type == 0) { String str = (String)paramXMLContentSpec.value; if (str != null && paramDTDGrammar.getElementDeclIndex(str) == -1) this.fErrorReporter.reportError("http://www.w3.org/TR/1998/REC-xml-19980210", "UndeclaredElementInContentSpec", new Object[] { (paramDTDGrammar.getElementDeclName(paramInt1)).rawname, str }, (short)0); } else if (paramXMLContentSpec.type == 4 || paramXMLContentSpec.type == 5) { int i = ((int[])paramXMLContentSpec.value)[0]; int j = ((int[])paramXMLContentSpec.otherValue)[0]; checkDeclaredElements(paramDTDGrammar, paramInt1, i, paramXMLContentSpec); checkDeclaredElements(paramDTDGrammar, paramInt1, j, paramXMLContentSpec); } else if (paramXMLContentSpec.type == 2 || paramXMLContentSpec.type == 1 || paramXMLContentSpec.type == 3) { int i = ((int[])paramXMLContentSpec.value)[0]; checkDeclaredElements(paramDTDGrammar, paramInt1, i, paramXMLContentSpec); } } } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/xerces/impl/dtd/XMLDTDProcessor.class * Java compiler version: 3 (47.0) * JD-Core Version: 1.1.3 */
47.339763
313
0.727019
ad185e9706bffea7d1c84f493a8af52ee5cc8f53
1,252
package com.networknt.bot.core; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import org.slf4j.Logger; public class LoggingOutputStream extends OutputStream { private final ByteArrayOutputStream baos = new ByteArrayOutputStream(1000); private final Logger logger; private final LogLevel level; public enum LogLevel { TRACE, DEBUG, INFO, WARN, ERROR, } public LoggingOutputStream(Logger logger, LogLevel level) { this.logger = logger; this.level = level; } @Override public void write(int b) { if (b == '\n') { String line = baos.toString(); baos.reset(); switch (level) { case TRACE: logger.trace(line); break; case DEBUG: logger.debug(line); break; case ERROR: logger.error(line); break; case INFO: logger.info(line); break; case WARN: logger.warn(line); break; } } else { baos.write(b); } } }
24.54902
79
0.491214
638b2fe23e88d9058f6dcd3d1c69db6bd0e58805
1,354
package com.google.android.gms.internal; import android.content.Context; import android.os.DeadObjectException; import android.os.IBinder; import android.os.Looper; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.internal.zzf; import com.google.android.gms.common.internal.zzj; import com.google.android.gms.internal.zzjp.zza; public class zzjs extends zzj<zzjp> { public zzjs(Context context, Looper looper, zzf zzf, ConnectionCallbacks connectionCallbacks, OnConnectionFailedListener onConnectionFailedListener) { super(context, looper, 19, zzf, connectionCallbacks, onConnectionFailedListener); } /* access modifiers changed from: protected */ /* renamed from: zzai */ public zzjp zzW(IBinder iBinder) { return zza.zzag(iBinder); } /* access modifiers changed from: protected */ public String zzfK() { return "com.google.android.gms.icing.LIGHTWEIGHT_INDEX_SERVICE"; } /* access modifiers changed from: protected */ public String zzfL() { return "com.google.android.gms.appdatasearch.internal.ILightweightAppDataSearch"; } public zzjp zzlw() throws DeadObjectException { return (zzjp) zzpc(); } }
35.631579
154
0.747415
9939cd2a83855c967da5d27164a82dbc498e9616
7,768
package com.stopclimatechange.earthgarden.controller; import com.stopclimatechange.earthgarden.config.JwtTokenProvider; import com.stopclimatechange.earthgarden.domain.User; import com.stopclimatechange.earthgarden.domain.UserDto; import com.stopclimatechange.earthgarden.service.MailService; import com.stopclimatechange.earthgarden.service.UserService; import lombok.RequiredArgsConstructor; import net.bytebuddy.utility.RandomString; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.HashMap; @CrossOrigin @RestController @RequiredArgsConstructor public class UserController { private final UserService userService; private final JwtTokenProvider jwtTokenProvider; private final MailService mailService; @GetMapping(value = "/user/signup/email") public ResponseEntity<HashMap> checkValidEmail(@RequestParam String email){ email = email.trim(); Boolean isExist = userService.validateDuplicateEmail(email); HashMap<String, Object> responseMap = new HashMap<>(); if(isExist){ responseMap.put("status", 409); responseMap.put("code", null); responseMap.put("message", "중복된 이메일"); return new ResponseEntity<HashMap> (responseMap, HttpStatus.CONFLICT); } else{ RandomString randomString = new RandomString(6); String code = randomString.nextString(); mailService.sendCheckEmail(email, code); responseMap.put("status", 200); responseMap.put("code", code); responseMap.put("message", "사용 가능한 이메일, 코드 발급됨"); return new ResponseEntity<HashMap>(responseMap, HttpStatus.OK); } } @GetMapping(value = "/user/signup/nickname") public ResponseEntity<HashMap> checkValidNickname(@RequestParam String nickname){ Boolean isExist = userService.validateDuplicateNickname(nickname); HashMap<String, Object> responseMap = new HashMap<>(); if(isExist){ responseMap.put("status", 409); responseMap.put("message", "중복된 닉네임"); return new ResponseEntity<HashMap> (responseMap, HttpStatus.CONFLICT); } else{ responseMap.put("status", 200); responseMap.put("message", "사용 가능한 닉네임"); return new ResponseEntity<HashMap>(responseMap, HttpStatus.OK); } } @PostMapping(value = "/user/signup", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE}) public ResponseEntity<HashMap> create(@RequestPart(value = "email") String email, @RequestPart(value = "pw") String pw, @RequestPart(value = "nickname") String nickname, @RequestPart(value = "image", required = false) MultipartFile image) { email = email.trim(); HashMap<String, Object> responseMap = new HashMap<>(); if(userService.validateDuplicateEmail(email)){ responseMap.put("status", 409); responseMap.put("message", "잘못된 접근. 중복 여부 확인 요함"); return new ResponseEntity<HashMap>(responseMap, HttpStatus.CONFLICT); } else { userService.signUp(email, pw, nickname, image); responseMap.put("status", 200); responseMap.put("message", "회원가입 성공"); return new ResponseEntity<HashMap>(responseMap, HttpStatus.OK); } } @PostMapping("/user/signin/kakao") public ResponseEntity<HashMap> kakaoLogin(@RequestBody UserDto.KakaoDto kakaoDto){ User user; if(userService.checkIsMember(kakaoDto.getKakao_id())) user = userService.signIn(kakaoDto.getKakao_id()); else user = userService.signUp(kakaoDto); HashMap<String, Object> responseMap = new HashMap<>(); if (user != null) { responseMap.put("status", 200); responseMap.put("message", "로그인 성공"); responseMap.put("token", jwtTokenProvider.createToken(user.getEmail(), user.getRoles())); return new ResponseEntity<HashMap>(responseMap, HttpStatus.OK); } else { responseMap.put("status", 401); responseMap.put("message", "소셜 로그인 오류"); return new ResponseEntity<HashMap>(responseMap, HttpStatus.UNAUTHORIZED); } } @PostMapping("/user/signin") public ResponseEntity<HashMap> login(@RequestBody UserDto.LoginDto loginDto) { loginDto.setEmail(loginDto.getEmail().trim()); User user = userService.signIn(loginDto); HashMap<String, Object> responseMap = new HashMap<>(); if (user != null) { responseMap.put("status", 200); responseMap.put("message", "로그인 성공"); responseMap.put("token", jwtTokenProvider.createToken(user.getEmail(), user.getRoles())); return new ResponseEntity<HashMap>(responseMap, HttpStatus.OK); } else { responseMap.put("status", 401); responseMap.put("message", "이메일 또는 비밀번호 오류"); return new ResponseEntity<HashMap>(responseMap, HttpStatus.UNAUTHORIZED); } } @GetMapping(value = "/user/profile") public ResponseEntity<HashMap> getProfile(@RequestHeader("X-AUTH-TOKEN") String token) { User user = userService.findUserByEmail(jwtTokenProvider.getUserEmail(token)); UserDto.ProfileDto profileDto = new UserDto.ProfileDto(user); HashMap<String, Object> responseMap = new HashMap<>(); responseMap.put("status", 200); responseMap.put("message", "조회 완료"); responseMap.put("data", profileDto); return new ResponseEntity<HashMap>(responseMap, HttpStatus.OK); } @PutMapping(value = "/user/profile", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE}) public ResponseEntity<HashMap> updateProfile(@RequestHeader("X-AUTH-TOKEN") String token, @RequestPart(value="nickname") String nickname, @RequestPart(value = "image", required = false) MultipartFile image) { User user = userService.findUserByEmail(jwtTokenProvider.getUserEmail(token)); userService.updateProfile(user, nickname, image); HashMap<String, Object> responseMap = new HashMap<>(); responseMap.put("status", 200); responseMap.put("message", "프로필 업데이트 성공"); return new ResponseEntity<HashMap>(responseMap, HttpStatus.OK); } @PutMapping(value = "/user/password") public ResponseEntity<HashMap> updatePassword(@RequestHeader("X-AUTH-TOKEN") String token, @RequestBody UserDto.PasswordDto passwordDto) { User user = userService.findUserByEmail(jwtTokenProvider.getUserEmail(token)); HashMap<String, Object> responseMap = new HashMap<>(); if(!userService.checkRightPassword(user, passwordDto.getOri_pw())){ responseMap.put("status", 409); responseMap.put("message", "비밀번호 오류"); return new ResponseEntity<HashMap>(responseMap, HttpStatus.CONFLICT); } else{ userService.updatePassword(user, passwordDto.getNew_pw()); responseMap.put("status", 200); responseMap.put("message", "비밀번호 변경 성공"); return new ResponseEntity<HashMap>(responseMap, HttpStatus.OK); } } }
41.540107
124
0.641092
7ad843aa46f8439b6df12613b6a0fc24e508b1ed
2,398
package world.ucode.game; import javafx.animation.AnimationTimer; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import javafx.util.Duration; public class Dino { protected Pane root; protected Image dinoImg = new Image("Dino-left-up.png"); protected ImageView dinoView = new ImageView(this.dinoImg); public AnimationTimer animationTimer; private boolean status = true; /** * Constructor Cactus * * @param pane */ Dino(Pane pane) { this.root = pane; dinoView.setLayoutY(720); dinoView.setLayoutX(30); this.animationRun(); this.animationJump(); this.root.getChildren().add(dinoView); } /** * Animation Dino Run */ public void animationRun() { Timeline t = new Timeline( new KeyFrame(Duration.millis(200), new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { dinoView.setImage(new Image("Dino-left-up.png")); } }), new KeyFrame(Duration.millis(400), new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { dinoView.setImage(new Image("Dino-right-up.png")); } }) ); t.setCycleCount(Timeline.INDEFINITE); t.play(); } /** * Animation Dino Jump * * @return animationTimer */ public AnimationTimer animationJump() { animationTimer = new AnimationTimer() { @Override public void handle(long now) { if (dinoView.getLayoutY() >= 580 && status) { dinoView.setLayoutY(dinoView.getLayoutY() - 4); if (dinoView.getLayoutY() <= 580) status = false; } else if (!status) { dinoView.setLayoutY(dinoView.getLayoutY() + 5); if (dinoView.getLayoutY() >= 720) { status = true; animationTimer.stop(); } } } }; return animationTimer; } }
30.35443
84
0.542535
c2fc78449865af901674347d28c6b31e9aa8bc7c
684
package mensal.locadora; import java.math.BigDecimal; import java.util.List; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import lombok.Data; @Entity @Data public class Locacao{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; Date data; int qtdDiarias; BigDecimal valorDiaria; // muitas locaoes para 1 cliente // muitasw locadcoes para um veiculo @ManyToOne private Cliente cliente ; @ManyToOne private Veiculo veiculo ; }
21.375
55
0.777778
5e313b5182ab7f8304411c2e16409f6a71f62bfc
2,687
/* * Copyright (c) 2008 Nathan Sweet * * 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.esotericsoftware.yamlbeans.emitter; /** @author <a href="mailto:misc@n4te.com">Nathan Sweet</a> */ public class EmitterConfig { boolean canonical; boolean useVerbatimTags = true; int indentSize = 3; int wrapColumn = 100; boolean escapeUnicode = true; boolean prettyFlow; /** If true, the YAML output will be canonical. Default is false. */ public void setCanonical (boolean canonical) { this.canonical = canonical; } /** Sets the number of spaces to indent. Default is 3. */ public void setIndentSize (int indentSize) { if (indentSize < 2) throw new IllegalArgumentException("indentSize cannot be less than 2."); this.indentSize = indentSize; } /** Sets the column at which values will attempt to wrap. Default is 100. */ public void setWrapColumn (int wrapColumn) { if (wrapColumn <= 4) throw new IllegalArgumentException("wrapColumn must be greater than 4."); this.wrapColumn = wrapColumn; } /** If false, tags will never be surrounded by angle brackets (eg, "!&lt;java.util.LinkedList&gt;"). Default is true. */ public void setUseVerbatimTags (boolean useVerbatimTags) { this.useVerbatimTags = useVerbatimTags; } /** If false, UTF-8 unicode characters will be output instead of the escaped unicode character code. */ public void setEscapeUnicode (boolean escapeUnicode) { this.escapeUnicode = escapeUnicode; } /** If true, the YAML output will be pretty flow. Default is false. */ public void setPrettyFlow(boolean prettyFlow) { this.prettyFlow = prettyFlow; } }
44.783333
131
0.734276
b82400a3e25f75d412832f4474ccead949805af5
2,001
package br.com.Modelo; import java.util.Date; /** * @author Brenno * * Copyright (c) 2016 Brenno Dário Pimenta de Almeida * A permissão é concedida, gratuitamente, a qualquer pessoa que obtenha uma cópia deste software e * dos arquivos de documentação associados (o "Software"), para lidar com o Software sem restrições, * incluindo, sem limitação, os direitos de usar, copiar, modificar, mesclar , publicar, distribuir, * sub-licenciar e/ou vender cópias do Software, e para permitir que as pessoas a quem o Software é * fornecido a fazê-lo, sujeito às seguintes condições: * O aviso de copyright acima e este aviso de permissão devem ser incluídos em todas as cópias ou partes * substanciais do Software. * O SOFTWARE É FORNECIDO "COMO ESTÁ", SEM GARANTIA DE QUALQUER TIPO, expressa ou implícita, INCLUINDO, * SEM LIMITAÇÃO, AS GARANTIAS DE COMERCIALIZAÇÃO, ADEQUAÇÃO A UM DETERMINADO FIM E NÃO VIOLAÇÃO. * EM NENHUM CASO OS AUTORES ou direitos de autor DETENTORES DE SER RESPONSÁVEL POR QUALQUER RECLAMAÇÃO, * DANOS OU OUTRA RESPONSABILIDADE, SEJA EM UMA AÇÃO DE CONTRATO, DELITO OU DE OUTRA FORMA, DECORRENTES DE, * OU EM CONEXÃO COM O SOFTWARE OU O USO OU OUTRA APLICAÇÃO DO PROGRAMAS. * */ public class AdicionarDespesa { private Date data; private String tipo, nome; private double entrada, saida, total; public Date getData() { return data; } public void setData(Date data) { this.data = data; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public double getEntrada() { return entrada; } public void setEntrada(double entrada) { this.entrada = entrada; } public double getSaida() { return saida; } public void setSaida(double saída) { this.saida = saída; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } }
29.865672
108
0.729135
1aa877b570488f74efe30702cc02b6ab18262636
2,797
/* * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.registry.jcr.nodetype; import javax.jcr.Value; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.PropertyDefinition; public class RegistryPropertyDefinition implements PropertyDefinition { public int getRequiredType() { return 0; //To change body of implemented methods use File | Settings | File Templates. } public String[] getValueConstraints() { return new String[0]; //To change body of implemented methods use File | Settings | File Templates. } public Value[] getDefaultValues() { return new Value[0]; //To change body of implemented methods use File | Settings | File Templates. } public boolean isMultiple() { return false; //To change body of implemented methods use File | Settings | File Templates. } public String[] getAvailableQueryOperators() { return new String[0]; //To change body of implemented methods use File | Settings | File Templates. } public boolean isFullTextSearchable() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isQueryOrderable() { return false; //To change body of implemented methods use File | Settings | File Templates. } public NodeType getDeclaringNodeType() { return null; //To change body of implemented methods use File | Settings | File Templates. } public String getName() { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isAutoCreated() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isMandatory() { return false; //To change body of implemented methods use File | Settings | File Templates. } public int getOnParentVersion() { return 0; //To change body of implemented methods use File | Settings | File Templates. } public boolean isProtected() { return false; //To change body of implemented methods use File | Settings | File Templates. } }
36.324675
108
0.696103
de7397bf1450e7702775781c241eb12744fc6b9a
817
package com.daomtthuan.chatnow.ejb.facade; import com.daomtthuan.chatnow.ejb.entity.Role; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class RoleFacade extends AbstractFacade<Role> implements RoleFacadeLocal { @PersistenceContext(unitName = "chatnow-ejbPU") private EntityManager entityManager; @Override protected EntityManager getEntityManager() { return this.entityManager; } public RoleFacade() { super(Role.class); } @Override public Role findByName(String name) { List<Role> roles = this.entityManager.createNamedQuery("Role.findByName").setParameter("name", name).getResultList(); if (roles.isEmpty()) { return null; } return roles.get(0); } }
24.029412
121
0.747858
c90aa89448075b09bbacb988d5823a8485b46b52
1,820
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.credhub.support; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPathException; import com.jayway.jsonpath.PathNotFoundException; import org.assertj.core.api.AbstractAssert; import org.assertj.core.api.AbstractObjectAssert; import org.assertj.core.api.Assertions; public class JsonPathAssert extends AbstractAssert<JsonPathAssert, DocumentContext> { public JsonPathAssert(DocumentContext actual) { super(actual, JsonPathAssert.class); } public static JsonPathAssert assertThat(DocumentContext jsonPathDocument) { return new JsonPathAssert(jsonPathDocument); } public JsonPathAssert hasNoPath(String jsonPath) { try { Object value = actual.read(jsonPath); failWithMessage("The path '" + jsonPath + "' was not expected but evaluated to " + value); return null; } catch (JsonPathException e) { return this; } } public AbstractObjectAssert<?, Object> hasPath(String path) { try { return Assertions.assertThat(actual.read(path, Object.class)); } catch (PathNotFoundException e) { failWithMessage("The JSON " + actual.jsonString() + " does not contain the path '" + path + "'"); return null; } } }
33.703704
100
0.752198
617713348989a146606039f3c207a25a61181184
8,498
/* * SonarQube PDF Report * Copyright (C) 2010-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.report.pdf; import java.awt.Color; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.Phrase; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.BaseFont; /** * Static Styles for PDF reporting * */ public class Style { /** * Font used in main chapters title */ private static final Logger LOG = LoggerFactory.getLogger(Style.class); public static final BaseFont CHINESE = setfont(); public static final Font CHAPTER_FONT = new Font(CHINESE, 18, Font.BOLD, Color.GRAY); /** * Font used in sub-chapters title */ public static final Font TITLE_FONT = new Font(CHINESE, 14, Font.BOLD, Color.GRAY); /** * Font used in TABLE_OF_CONTENTS */ public static final Font CONTENTS_FONT = new Font(CHINESE, 9,Font.NORMAL, Color.BLACK); /** * Font used in HEAD */ public static final Font HEAD_FONT = new Font(CHINESE, 12,Font.NORMAL, Color.GRAY); /** * Font used in graphics foots */ public static final Font FOOT_FONT = new Font(Font.TIMES_ROMAN, 10, Font.BOLD, Color.GRAY); /** * Font used in general plain text */ public static final Font NORMAL_FONT = new Font(CHINESE, 11, Font.NORMAL, Color.BLACK); /** * Font used in code text (bold) */ public static final Font MONOSPACED_BOLD_FONT = new Font(Font.COURIER, 11, Font.BOLD, Color.BLACK); /** * Font used in code text */ public static final Font MONOSPACED_FONT = new Font(Font.COURIER, 10, Font.NORMAL, Color.BLACK); /** * Font used in table of contents title */ public static final Font TOC_TITLE_FONT = new Font(CHINESE, 24, Font.BOLD, Color.GRAY); /** * Font used in front page (Project name) */ public static final Font FRONTPAGE_FONT_1 = new Font(CHINESE, 22, Font.BOLD, Color.BLACK); /** * Font used in front page (Project description) */ public static final Font FRONTPAGE_FONT_2 = new Font(Font.HELVETICA, 18, Font.ITALIC, Color.BLACK); /** * Font used in front page (Project date) */ public static final Font FRONTPAGE_FONT_3 = new Font(Font.HELVETICA, 16, Font.BOLDITALIC, Color.GRAY); /** * Underlined font */ public static final Font UNDERLINED_FONT = new Font(CHINESE, 14, Font.UNDERLINE, Color.BLACK); /** * Dashboard metric title font */ public static final Font DASHBOARD_TITLE_FONT = new Font(CHINESE, 12, Font.NORMAL, Color.BLACK); /** * Dashboard metric value font */ public static final Font DASHBOARD_DATA_FONT = new Font(Font.TIMES_ROMAN, 12, Font.BOLD, Color.GRAY); /** * Dashboard metric details font */ public static final Font DASHBOARD_DATA_FONT_2 = new Font(CHINESE, 10, Font.NORMAL, new Color(100, 150, 190)); /** * Tendency icons height + 2 (used in tables style) */ public static final int TENDENCY_ICONS_HEIGHT = 20; public static final float FRONTPAGE_LOGO_POSITION_X = 114; public static final float FRONTPAGE_LOGO_POSITION_Y = 542; private Style() { super(); } public static BaseFont setfont() { try{ return BaseFont.createFont(PDFResources.CHINESE_FONT_FILE, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); }catch(Exception e){ LOG.error("Can not generate yaheiChinese Font", e); return null; } } public static void noBorderTable(final PdfPTable table) { table.getDefaultCell().setBorderColor(Color.WHITE); } public static void alignCenterTable(final PdfPTable table) { table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); } public static void alignRightTable(final PdfPTable table) { table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); } /** * This method makes a simple table with content. * * @param left * Data for left column * @param right * Data for right column * @param title * The table title * @param noData * Showed when left or right are empty * @return The table (iText table) ready to add to the document */ public static PdfPTable createSimpleTable(final List<String> left, final List<String> right, final String title, final String noData) { return createSimpleTable(left, right, null, title, noData); } /** * This method makes a simple table with content. * * @param left * Data for left column * @param right * Data for right column * @param title * The table title * @param noData * Showed when left or right are empty * @return The table (iText table) ready to add to the document */ public static PdfPTable createSimpleTable(final List<String> left, final List<String> right, final List<Color> colors, final String title, final String noData) { PdfPTable table = new PdfPTable(2); table.getDefaultCell().setColspan(2); table.addCell(new Phrase(title, Style.DASHBOARD_TITLE_FONT)); table.getDefaultCell().setBackgroundColor(Color.GRAY); table.addCell(""); table.getDefaultCell().setColspan(1); table.getDefaultCell().setBackgroundColor(Color.WHITE); Iterator<String> itLeft = left.iterator(); Iterator<String> itRight = right.iterator(); Iterator<Color> itColor = null; boolean isColorSet = false; if (colors != null) { itColor = colors.iterator(); isColorSet = true; } while (itLeft.hasNext()) { String textLeft = itLeft.next(); String textRight = itRight.next(); PdfPCell leftCell = new PdfPCell(new Phrase(textLeft,Style.NORMAL_FONT)); PdfPCell rightCell = new PdfPCell(new Phrase(textRight,Style.NORMAL_FONT)); if (isColorSet) { Color color = itColor.next(); leftCell.setBackgroundColor(color); rightCell.setBackgroundColor(color); } table.addCell(leftCell); table.addCell(rightCell); } if (left.isEmpty()) { table.getDefaultCell().setColspan(2); table.addCell(noData); } table.setSpacingBefore(20); table.setSpacingAfter(20); return table; } /** * Method for creating a table with 2 columns * * @param titles * titles * @param content * content * @return The table (iText table) ready to add to the document */ public static PdfPTable createTwoColumnsTitledTable(final List<String> titles, final List<String> content) { PdfPTable table = new PdfPTable(10); Iterator<String> itLeft = titles.iterator(); Iterator<String> itRight = content.iterator(); while (itLeft.hasNext()) { String textLeft = itLeft.next(); String textRight = itRight.next(); table.getDefaultCell().setColspan(1); table.addCell(textLeft); table.getDefaultCell().setColspan(9); table.addCell(textRight); } table.setSpacingBefore(20); table.setSpacingAfter(20); table.setLockedWidth(false); table.setWidthPercentage(90); return table; } }
31.947368
116
0.642622
63d244d66bbf4e344117c2b972c7012b53886f26
312
package pl.aprilapps.easyphotopicker; /** * Created by Jacek Kwiecień on 03.11.2015. */ public interface EasyImageConfig { int REQ_PICK_PICTURE_FROM_DOCUMENTS = 7457; int REQ_PICK_PICTURE_FROM_GALLERY = 7458; int REQ_TAKE_PICTURE = 7459; int REQ_SOURCE_CHOOSER = 7460; int REQ_IMAGE=1; }
22.285714
47
0.737179
550b2f07f481f0a3484f2b7c263842482557ef14
5,026
package com.example.massa.luxvilla.Actividades; import android.content.Intent; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.SwitchPreference; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.app.AppCompatDelegate; import android.view.Menu; import android.view.MenuItem; import com.example.massa.luxvilla.R; import com.google.firebase.messaging.FirebaseMessaging; import com.lapism.searchview.SearchHistoryTable; import com.lapism.searchview.SearchItem; import java.util.ArrayList; import java.util.List; public class settings extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings2); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getFragmentManager().beginTransaction().replace(R.id.fragment_container, new UserPreferenceFragment()).commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: onBackPressed(); break; } return super.onOptionsItemSelected(item); } public static class UserPreferenceFragment extends PreferenceFragment { Preference preferenceclear, preferencesobre; SwitchPreference switchPreferencenightmode; CheckBoxPreference switchPreferencenotifications; SearchHistoryTable msearchHistoryTable; List<SearchItem> sugestions; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); preferenceclear=getPreferenceScreen().findPreference(getResources().getString(R.string.clearhistory)); preferenceclear.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { sugestions=new ArrayList<>(); sugestions.clear(); msearchHistoryTable = new SearchHistoryTable(getActivity()); msearchHistoryTable.clearDatabase(); Snackbar.make(getView(), "histórico de busca eliminado", Snackbar.LENGTH_LONG).show(); return true; } }); switchPreferencenotifications=(CheckBoxPreference)getPreferenceScreen().findPreference(getResources().getString(R.string.notificaçãoes)); switchPreferencenotifications.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { boolean switched = ((SwitchPreference) preference) .isChecked(); if (switched){ FirebaseMessaging.getInstance().unsubscribeFromTopic("todos"); }else{ FirebaseMessaging.getInstance().subscribeToTopic("todos"); } return true; } }); switchPreferencenightmode=(SwitchPreference) getPreferenceScreen().findPreference(getResources().getString(R.string.night_mode)); switchPreferencenightmode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { boolean switched = ((SwitchPreference) preference) .isChecked(); if (switched){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); }else{ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } getActivity().onBackPressed(); return true; } }); preferencesobre=getPreferenceScreen().findPreference(getResources().getString(R.string.sobre)); preferencesobre.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { startActivity(new Intent(getActivity(),Sobre.class)); return true; } }); } } }
40.208
149
0.644648
95a7baae84f22d28700e9cd4a0cf71efc9541fb8
903
package reega.main; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reega.data.remote.RemoteConnection; import reega.generation.DataFiller; import reega.generation.OnDemandDataFiller; import java.io.IOException; public final class GenerationLauncher { private static final Logger LOGGER = LoggerFactory.getLogger(GenerationLauncher.class); private GenerationLauncher() { } public static void main(final String[] args) { final String accessToken = System.getenv("AUTH_TOKEN"); final RemoteConnection connection = new RemoteConnection(); connection.overrideToken(accessToken); try { final DataFiller generation = new OnDemandDataFiller(); generation.fill(); } catch (final IOException e) { GenerationLauncher.LOGGER.error("couldn't access DB"); } System.exit(0); } }
25.8
91
0.697674
bbc17dc4b7a6702a5c9b330aae81330194f6a68e
14,833
/* * Copyright 2008 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oauth.client; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.Map; import junit.framework.TestCase; import net.oauth.OAuth; import net.oauth.OAuthAccessor; import net.oauth.OAuthConsumer; import net.oauth.OAuthMessage; import net.oauth.OAuthProblemException; import net.oauth.ParameterStyle; import net.oauth.client.httpclient4.HttpClient4; import net.oauth.http.HttpMessage; import net.oauth.http.HttpMessageDecoder; import net.oauth.http.HttpResponseMessage; import net.oauth.signature.Echo; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.servlet.GzipFilter; import org.mortbay.thread.BoundedThreadPool; public class OAuthClientTest extends TestCase { public void testRedirect() throws Exception { final OAuthMessage request = new OAuthMessage("GET", "http://google.com/search", OAuth.newList("q", "Java")); final Integer expectedStatus = Integer.valueOf(301); final String expectedLocation = "http://www.google.com/search?q=Java"; for (OAuthClient client : clients) { try { OAuthMessage response = client.invoke(request, ParameterStyle.BODY); fail(client.getHttpClient() + " response: " + response); } catch (OAuthProblemException e) { Map<String, Object> parameters = e.getParameters(); assertEquals("status", expectedStatus, parameters.get(HttpMessage.STATUS_CODE)); assertEquals("Location", expectedLocation, parameters.get(HttpResponseMessage.LOCATION)); } } } public void testInvokeMessage() throws Exception { final String echo = "http://localhost:" + port + "/Echo"; final String data = new String(new char[] { 0, 1, ' ', 'a', 127, 128, 0xFF, 0x3000, 0x4E00 }); final byte[] utf8 = data.getBytes("UTF-8"); List<OAuth.Parameter> parameters = OAuth.newList("x", "y", "oauth_token", "t"); String parametersForm = "oauth_token=t&x=y"; final Object[][] messages = new Object[][] { { new OAuthMessage("GET", echo, parameters), "GET\n" + parametersForm + "\n" + "null\n", null }, { new OAuthMessage("POST", echo, parameters), "POST\n" + parametersForm + "\n" + parametersForm.length() + "\n", OAuth.FORM_ENCODED }, { new MessageWithBody("PUT", echo, parameters, "text/OAuthClientTest; charset=\"UTF-8\"", utf8), "PUT\n" + parametersForm + "\n" + utf8.length + "\n" + data, "text/OAuthClientTest; charset=UTF-8" }, { new MessageWithBody("PUT", echo, parameters, "application/octet-stream", utf8), "PUT\n" + parametersForm + "\n" + utf8.length + "\n" + new String(utf8, "ISO-8859-1"), "application/octet-stream" }, { new OAuthMessage("DELETE", echo, parameters), "DELETE\n" + parametersForm + "\n" + "null\n", null } }; final ParameterStyle[] styles = new ParameterStyle[] { ParameterStyle.BODY, ParameterStyle.AUTHORIZATION_HEADER }; final long startTime = System.nanoTime(); for (OAuthClient client : clients) { for (Object[] testCase : messages) { for (ParameterStyle style : styles) { OAuthMessage request = (OAuthMessage) testCase[0]; final String id = client + " " + request.method + " " + style; OAuthMessage response = null; // System.out.println(id + " ..."); try { response = client.invoke(request, style); } catch (Exception e) { AssertionError failure = new AssertionError(id); failure.initCause(e); throw failure; } // System.out.println(response.getDump() // .get(OAuthMessage.HTTP_REQUEST)); String expectedBody = (String) testCase[1]; if ("POST".equalsIgnoreCase(request.method) && style == ParameterStyle.AUTHORIZATION_HEADER) { // Only the non-oauth parameters went in the body. expectedBody = expectedBody.replace("\n" + parametersForm.length() + "\n", "\n3\n"); } String body = response.readBodyAsString(); assertEquals(id, expectedBody, body); assertEquals(id, testCase[2], response.getHeader(HttpMessage.CONTENT_TYPE)); } } } final long endTime = System.nanoTime(); final float elapsedSec = ((float) (endTime - startTime)) / 1000000000L; if (elapsedSec > 10) { fail("elapsed time = " + elapsedSec + " sec"); // This often means the client isn't re-using TCP connections, // and consequently all the Jetty server threads are occupied // waiting for data on the wasted connections. } } public void testAccess() throws Exception { final String echo = "http://localhost:" + port + "/Echo"; final List<OAuth.Parameter> parameters = OAuth.newList("n", "v"); final String contentType = "text/fred; charset=" + OAuth.ENCODING; final byte[] content = "1234".getBytes(OAuth.ENCODING); for (OAuthClient client : clients) { String id = client.getHttpClient().toString(); OAuthMessage request = new OAuthMessage(OAuthMessage.POST, echo, parameters, new ByteArrayInputStream(content)); request.getHeaders().add(new OAuth.Parameter("Content-Type", contentType)); OAuthMessage response = client.access(request, ParameterStyle.QUERY_STRING); String expectedBody = (client.getHttpClient() instanceof HttpClient4) // ? "POST\nn=v\nnull\n1234" // no Content-Length : "POST\nn=v\n4\n1234"; String body = response.readBodyAsString(); assertEquals(id, contentType, response.getHeader(HttpMessage.CONTENT_TYPE)); assertEquals(id, expectedBody, body); } } public void testGzip() throws Exception { final OAuthConsumer consumer = new OAuthConsumer(null, null, null, null); consumer.setProperty(OAuthConsumer.ACCEPT_ENCODING, HttpMessageDecoder.ACCEPTED); consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, "PLAINTEXT"); final OAuthAccessor accessor = new OAuthAccessor(consumer); final String url = "http://localhost:" + port + "/Echo"; final List<OAuth.Parameter> parameters = OAuth.newList("echoData", "21", OAuth.OAUTH_NONCE, "n", OAuth.OAUTH_TIMESTAMP, "1"); final String expected = "POST\n" + "echoData=21&oauth_consumer_key=&oauth_nonce=n&oauth_signature_method=PLAINTEXT&oauth_timestamp=1&oauth_version=1.0\n" + "abcdefghi1abcdefghi2\n\n" // 21 bytes of data + "134\n" // content-length ; for (OAuthClient client : clients) { try { OAuthMessage response = client.invoke(accessor, "POST", url, parameters); System.out.println(response.getDump().get(HttpMessage.REQUEST)); System.out.println(response.getDump().get(HttpMessage.RESPONSE)); String id = client.getClass().getName(); assertNull(id, response.getHeader(HttpMessage.CONTENT_ENCODING)); assertNull(id, response.getHeader(HttpMessage.CONTENT_LENGTH)); assertEquals(id, expected, response.readBodyAsString()); // assertEqual(id, OAuth.decodeForm(expected), response.getParameters()); } catch (OAuthProblemException e) { Map<String, Object> p = e.getParameters(); System.out.println(p.get(HttpMessage.REQUEST)); System.err.println(p.get(HttpMessage.RESPONSE)); throw e; } catch(Exception e) { AssertionError a = new AssertionError(client.getClass().getName()); a.initCause(e); throw a; } System.out.println(); } } public void testUpload() throws IOException, OAuthProblemException { final String echo = "http://localhost:" + port + "/Echo"; final Class myClass = getClass(); final String sourceName = "/" + myClass.getPackage().getName().replace('.', '/') + "/flower.jpg"; final URL source = myClass.getResource(sourceName); assertNotNull(sourceName, source); for (OAuthClient client : clients) { for (ParameterStyle style : new ParameterStyle[] { ParameterStyle.AUTHORIZATION_HEADER, ParameterStyle.QUERY_STRING }) { final String id = client + " POST " + style; OAuthMessage response = null; InputStream input = source.openStream(); try { OAuthMessage request = new OAuthMessage(OAuthMessage.PUT, echo, null, input); request.addParameter(new OAuth.Parameter("oauth_token", "t")); request.getHeaders().add(new OAuth.Parameter("Content-Type", "image/jpeg")); response = client.invoke(request, style); } catch (OAuthProblemException e) { System.err.println(e.getParameters().get(HttpMessage.REQUEST)); System.err.println(e.getParameters().get(HttpMessage.RESPONSE)); throw e; } catch (Exception e) { AssertionError failure = new AssertionError(); failure.initCause(e); throw failure; } finally { input.close(); } assertEquals(id, "image/jpeg", response.getHeader("Content-Type")); byte[] data = readAll(source.openStream()); Integer contentLength = (client.getHttpClient() instanceof HttpClient4) ? null : new Integer( data.length); byte[] expected = concatenate((OAuthMessage.PUT + "\noauth_token=t\n" + contentLength + "\n") .getBytes(), data); byte[] actual = readAll(response.getBodyAsStream()); StreamTest.assertEqual(id, expected, actual); } } } static byte[] readAll(InputStream from) throws IOException { ByteArrayOutputStream into = new ByteArrayOutputStream(); try { byte[] buf = new byte[1024]; for (int n; 0 < (n = from.read(buf));) { into.write(buf, 0, n); } } finally { from.close(); } into.close(); return into.toByteArray(); } static byte[] concatenate(byte[] x, byte[] y) { byte[] z = new byte[x.length + y.length]; System.arraycopy(x, 0, z, 0, x.length); System.arraycopy(y, 0, z, x.length, y.length); return z; } private OAuthClient[] clients; private int port = 1025; private Server server; @Override public void setUp() throws Exception { clients = new OAuthClient[] { new OAuthClient(new URLConnectionClient()), new OAuthClient(new net.oauth.client.httpclient3.HttpClient3()), new OAuthClient(new net.oauth.client.httpclient4.HttpClient4()) }; { // Get an ephemeral local port number: Socket s = new Socket(); s.bind(null); port = s.getLocalPort(); s.close(); } server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); context.addFilter(GzipFilter.class, "/*", 1); context.addServlet(new ServletHolder(new Echo()), "/Echo/*"); BoundedThreadPool pool = new BoundedThreadPool(); pool.setMaxThreads(4); server.setThreadPool(pool); server.start(); } @Override public void tearDown() throws Exception { server.stop(); } private static class MessageWithBody extends OAuthMessage { public MessageWithBody(String method, String URL, Collection<OAuth.Parameter> parameters, String contentType, byte[] body) { super(method, URL, parameters); this.body = body; Collection<Map.Entry<String, String>> headers = getHeaders(); headers.add(new OAuth.Parameter(HttpMessage.ACCEPT_ENCODING, HttpMessageDecoder.ACCEPTED)); if (body != null) { headers.add(new OAuth.Parameter(HttpMessage.CONTENT_LENGTH, String.valueOf(body.length))); } if (contentType != null) { headers.add(new OAuth.Parameter(HttpMessage.CONTENT_TYPE, contentType)); } } private final byte[] body; @Override public InputStream getBodyAsStream() { return (body == null) ? null : new ByteArrayInputStream(body); } } }
47.694534
137
0.563608
54e3f429ce8f8aae8b2b35657a3c2051e5f72372
1,774
/* * Copyright (c) 2002-2022 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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.neo4j.ogm.domain.gh851; import org.neo4j.ogm.annotation.GeneratedValue; import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; /** * @author Michael J. Simons */ @NodeEntity public class Flight { @Id @GeneratedValue Long id; String name; @Relationship(type = "DEPARTS") Airport departure; @Relationship(type = "ARRIVES") Airport arrival; public Flight() { } public Flight(String name, Airport departure, Airport arrival) { this.name = name; this.departure = departure; this.arrival = arrival; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Airport getDeparture() { return departure; } public void setDeparture(Airport departure) { this.departure = departure; } public Airport getArrival() { return arrival; } public void setArrival(Airport arrival) { this.arrival = arrival; } }
23.972973
75
0.669109
fa4c58311010bff86fd7fe7d6ab63f53840ad9b4
1,929
/* * framework: org.nrg.framework.constants.Scope * XNAT http://www.xnat.org * Copyright (c) 2017, Washington University School of Medicine * All Rights Reserved * * Released under the Simplified BSD. */ package org.nrg.framework.constants; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public enum Scope { Site("site"), Project("prj"), Subject("subj"), Experiment("experiment"), User("user"), DataType("datatype"); Scope(final String code) { _code = code; } public String code() { return _code; } public static Scope getDefaultScope() { return Site; } public static Scope getScope(final String code) { if (_scopes.isEmpty()) { synchronized (Scope.class) { for (Scope scope : values()) { _scopes.put(scope.code(), scope); } } } return _scopes.get(code); } public static Set<String> getCodes() { if (_scopes.isEmpty()) { getScope("site"); } return _scopes.keySet(); } public static String encode(final Scope scope, final String entityId) { if (scope == Site) { return Site.code(); } return String.format("%s:%s", scope.code(), entityId); } public static Map<String, String> decode(final String association) { final String[] atoms = association.split(":", 2); final Scope scope = Scope.getScope(atoms[0]); final String entityId = atoms.length == 1 ? null : atoms[1]; Map<String, String> items = new HashMap<>(); items.put("scope", scope.code()); items.put("entityId", entityId); return items; } private static final Map<String, Scope> _scopes = new ConcurrentHashMap<>(); private final String _code; }
25.72
80
0.587869
749c4fff3ca940d06b86c3ed562b98931986e811
8,762
package com.eterno.joshspy.app; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.app.usage.UsageEvents; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.eterno.joshspy.data.DataManager; import com.eterno.joshspy.R; import com.eterno.joshspy.data.AppItem; import com.eterno.joshspy.data.SheetAppItem; import com.eterno.joshspy.data.SheetEventItem; import com.eterno.joshspy.helper.SendDataToSheet; import com.eterno.joshspy.notification.NotificationRepo; import com.eterno.joshspy.ui.MainActivity; import com.eterno.joshspy.util.AppUtil; import com.google.gson.Gson; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; public class BackUpDataActivity extends AppCompatActivity { long lastUpdatedTime = 0L; long timeNow = System.currentTimeMillis(); private ArrayList<SheetAppItem> sheetAppItems = new ArrayList<SheetAppItem>(); private NotificationRepo notificationRepo; private static final String LAST_UPDATED_TIME = "last_updated_time"; private static final String TAG = "BackUpDataActivity"; HashMap<String, Integer> notiCountList = new HashMap<>(); HashMap<String, Integer> fgServiceCount = new HashMap<>(); private SharedPreferences sharedPref; private TextView mProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_back_up_data); mProgress = findViewById(R.id.progress); sharedPref = this.getPreferences(Context.MODE_PRIVATE); sharedPref.getLong(LAST_UPDATED_TIME, 0L); notificationRepo = new NotificationRepo(this.getApplication()); lastUpdatedTime = getLastUpdated(); if (lastUpdatedTime == 0L) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d(TAG, "first launch, backup from " + AppUtil.formatTimeStamp(cal.getTimeInMillis())); lastUpdatedTime = cal.getTimeInMillis(); } new MyAsyncTask().execute(2); } private void getAndPostAppSpecificData(String mPackageName, SheetAppItem sheetAppItem) { List<AppItem> appItems = DataManager.getInstance().getTargetAppTimelineRange(this, mPackageName, lastUpdatedTime, timeNow); if (appItems == null || appItems.size() == 0) { return; } List<SheetEventItem> sNewList = new ArrayList<>(); long prevFgTime = 0l; setProgress("AE - " + appItems.get(0).mName); Log.d(TAG, "Processing " + mPackageName + " " + (getPackageManager() == null)); for (AppItem item : appItems) { if (item.mEventType == UsageEvents.Event.MOVE_TO_FOREGROUND) { prevFgTime = item.mEventTime; } else if (item.mEventType == UsageEvents.Event.MOVE_TO_BACKGROUND) { sNewList.add(SheetEventItem.getSheetAppItem(item, prevFgTime)); } } sheetAppItem.mTimesOpened = sNewList.size(); sheetAppItems.add(sheetAppItem); Gson gson = new Gson(); String json = gson.toJson(sNewList); Log.d(TAG, "send data size - " + mPackageName + " " +sNewList.size()); Log.d(TAG, " " + mPackageName + " " + json); try { new SendDataToSheet("OPEN").execute(json, mPackageName); } catch (Exception e) { Log.e(TAG, "errror open" + e.getMessage()); } } private void setProgress(String progress) { mProgress.post(() -> { String str = mProgress.getText().toString(); mProgress.setText(str + "\n" + progress); }); } @SuppressLint("StaticFieldLeak") class MyAsyncTask extends AsyncTask<Integer, Void, List<AppItem>> { @Override protected void onPreExecute() { } @Override protected List<AppItem> doInBackground(Integer... integers) { setProgress("********** Fetching Foreground services **********"); HashMap<String, Integer> fgAppItems = DataManager.getInstance() .getAppsFGServiceRange(getApplicationContext(), lastUpdatedTime, timeNow); Log.d(TAG, "Foreground service No of apps = " + fgAppItems.size()); //setProgress("Fetching FG services No of apps = " + fgAppItems.size()); for (String item : fgAppItems.keySet()) { Log.d(TAG, "Get events for Foreground service " + item); if (AppUtil.validatePkgName(item)) { setProgress("FG - " + item); getAndPostFGAppSpecificData(item); } } setProgress("Fetching FG services Completed"); Log.d(TAG, "Foreground service completed"); return DataManager.getInstance().getAppsRange(getApplicationContext(), 2, lastUpdatedTime, timeNow); } @Override protected void onPostExecute(List<AppItem> appItems) { setProgress("********** Fetching App Data **********"); if(appItems == null || appItems.size() == 0){ goToMainActivity(); Log.e(TAG , "size 0 return to main "); return; } Log.d(TAG, "No of app events = " + appItems.size()); // setProgress("Fetching App Events " + appItems.size()+""); for (AppItem item : appItems) { if (item.mUsageTime <= 0) { continue; } if (AppUtil.validatePkgName(item.mPackageName)) { setNotiCountForApp(item.mPackageName); } } for (AppItem item : appItems) { if (item.mUsageTime <= 0) { continue; } if (AppUtil.validatePkgName(item.mPackageName)) { int mNotiCount = 0; if (notiCountList.containsKey(item.mPackageName)) { mNotiCount = notiCountList.get(item.mPackageName); } int mFgServiceCunt = 0; if (fgServiceCount.containsKey(item.mPackageName)) { mFgServiceCunt = fgServiceCount.get(item.mPackageName); } SheetAppItem sheetAppItem = new SheetAppItem( item.mName, item.mPackageName, 0, item.mUsageTime, mFgServiceCunt, mNotiCount, item.mMobile, item.mWifi ); getAndPostAppSpecificData(item.mPackageName, sheetAppItem); } } if (sheetAppItems.size() > 0) { Gson gson = new Gson(); String json = gson.toJson(sheetAppItems); Log.d(TAG, "DDDD Updating sheet app items " + json); try { setProgress("******** Sending Total App usage data ********"); new SendDataToSheet("USAGE").execute(json); } catch (Exception e) { Log.e(TAG, "error usage" + e.getMessage()); } } else { setLastUpdated(timeNow); goToMainActivity(); } Log.d(TAG, "Backup completed"); setLastUpdated(timeNow); } } private void setNotiCountForApp(String pkg) { AsyncTask.execute(() -> { int count = notificationRepo.getTotalNotificationsForApp(pkg); notiCountList.put(pkg, count); }); } private void goToMainActivity() { Intent i = new Intent(BackUpDataActivity.this, MainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i); } private long getLastUpdated() { return sharedPref.getLong(LAST_UPDATED_TIME, 0L); } private void setLastUpdated(Long time) { SharedPreferences.Editor editor = sharedPref.edit(); editor.putLong(LAST_UPDATED_TIME, time); editor.apply(); } private void getAndPostFGAppSpecificData(String mPackageName) { List<AppItem> appItems = DataManager.getInstance().getTargetAppFGTimelineRange(this, mPackageName, lastUpdatedTime, timeNow); if (appItems == null || appItems.size() == 0) { return; } List<SheetEventItem> sNewList = new ArrayList<>(); long prevFgTime = 0l; for (AppItem item : appItems) { if (item.mEventType == UsageEvents.Event.FOREGROUND_SERVICE_START) { prevFgTime = item.mEventTime; } else if (item.mEventType == UsageEvents.Event.FOREGROUND_SERVICE_STOP) { sNewList.add(SheetEventItem.getSheetAppItem(item, prevFgTime)); } } fgServiceCount.put(mPackageName, sNewList.size()); Gson gson = new Gson(); String FGSjson = gson.toJson(sNewList); try { Log.e(TAG, "Send Foreground data" + FGSjson); new SendDataToSheet("SERVICE").execute(FGSjson); } catch (Exception e) { Log.e(TAG, "error usage" + e.getMessage()); } } }
33.570881
96
0.656243
33d38499195e94b76486da4a61e1bd59a47a31eb
464
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.history.utils; import com.intellij.util.ExceptionUtil; public abstract class RunnableAdapter implements Runnable { @Override public void run() { try { doRun(); } catch (Exception e) { ExceptionUtil.rethrow(e); } } public abstract void doRun() throws Exception; }
24.421053
140
0.704741
8939eae9cd28bce975a77f7f481b6c100ed4c2b9
3,235
package org.hzero.wechat.dto; import java.util.List; import java.util.Map; public class GetMaterialResultDTO { // "title":TITLE, // "description":DESCRIPTION, // "down_url":DOWN_URL, private Map<String,List<NewsItemBean>> news_item; private Map<String,String> title; private Map<String,String> description; private Map<String,String> down_url; public Map<String, List<NewsItemBean>> getNews_item() { return news_item; } public void setNews_item(Map<String, List<NewsItemBean>> news_item) { this.news_item = news_item; } public Map<String, String> getTitle() { return title; } public void setTitle(Map<String, String> title) { this.title = title; } public Map<String, String> getDescription() { return description; } public void setDescription(Map<String, String> description) { this.description = description; } public Map<String, String> getDown_url() { return down_url; } public void setDown_url(Map<String, String> down_url) { this.down_url = down_url; } public static class NewsItemBean { /** * title : TITLE * thumb_media_id : THUMB_MEDIA_ID * show_cover_pic : SHOW_COVER_PIC * author : AUTHOR * digest : DIGEST * content : CONTENT * url : URL * content_source_url : CONTENT_SOURCE_URL */ private String title; private String thumb_media_id; private String show_cover_pic; private String author; private String digest; private String content; private String url; private String content_source_url; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getThumb_media_id() { return thumb_media_id; } public void setThumb_media_id(String thumb_media_id) { this.thumb_media_id = thumb_media_id; } public String getShow_cover_pic() { return show_cover_pic; } public void setShow_cover_pic(String show_cover_pic) { this.show_cover_pic = show_cover_pic; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDigest() { return digest; } public void setDigest(String digest) { this.digest = digest; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getContent_source_url() { return content_source_url; } public void setContent_source_url(String content_source_url) { this.content_source_url = content_source_url; } } }
24.323308
73
0.580216
3bb338350cc24d6c684bb1e01822e866e9c06963
6,214
/** * 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.fuerve.villageelder.configuration; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import com.fuerve.villageelder.configuration.types.TypedProperty; /** * This abstract base class provides the underlying mechanism for * loading properties in a way that makes it relatively easy to * extend and modify the set of properties to be loaded at * runtime. * * @author lparker * */ public abstract class PropertyHandler { private static final String DEFAULT_PROPERTY_FILE = "/VillageElder.properties"; private String propertyFilename; private boolean propertyFileOnClassPath = true; private Reader propertySource; private Map<String, TypedProperty<?>> propertyMap; /** * Initializes a new instance of PropertyHandler, which * will load from a default properties file. This default * properties file should be on the class path and named * VillageElder.properties. If this file does not exist, * an exception will result. */ public PropertyHandler() { propertyFilename = DEFAULT_PROPERTY_FILE; } /** * Initializes a new instance of PropertyHandler with a * pathname to a properties file. This pathname should * be absolute. * @param ppropertyFilename The path of the properties file. */ public PropertyHandler(final String ppropertyFilename) { propertyFilename = ppropertyFilename; propertyFileOnClassPath = false; } /** * Initializes a new instance of PropertyHandler with a property * source. This will usually be from a file on disk, but could * be from anywhere. * @param ppropertySource The property source, in Java properties * format. */ public PropertyHandler(final Reader ppropertySource) { propertySource = ppropertySource; } /** * Requests that a property be initialized as part of the property * set. These properties are strongly-typed properties that * support defaults and custom parsing interaction. * @param key The name of the property. * @param property The property itself, which should be a * descendent of TypedProperty with a specific type parameter. */ protected void requestProperty(final String key, final TypedProperty<?> property) { if (propertyMap == null) { propertyMap = new HashMap<String, TypedProperty<?>>(); } if (property == null) { throw new IllegalArgumentException("Tried to request a null property"); } propertyMap.put(key, property); } /** * Gets the value of a property, if the property exists and * has a value. * @param key The name of the property to retrieve. * @return The value of the property, or null if no such * property exists. */ @SuppressWarnings("unchecked") public <T> TypedProperty<T> get(final String key) { TypedProperty<?> property = propertyMap.get(key); return (TypedProperty<T>) property; } /** * Triggers the loading of properties from the properties * stream. * @throws IOException A fatal error occurred while interacting * with the properties stream. */ public void load() throws IOException { if (propertySource == null && propertyFilename != null) { if (propertyFileOnClassPath) { propertySource = new InputStreamReader( this.getClass().getResourceAsStream(propertyFilename) ); } else { propertySource = new FileReader( new File(propertyFilename) ); } } PropertyLoader loader = new PropertyLoader(propertySource); loader.loadProperties(); } /** * This class handles the low-level interaction of loading properties * from the stream and interacting with the strongly-typed property * system. * * @author lparker * */ private class PropertyLoader { private Reader source; private Properties properties; /** * Initializes a new instance of PropertyLoader with a source stream. * @param ssource The source, in Java properties format. */ public PropertyLoader(final Reader ssource) { properties = new Properties(); source = ssource; } /** * Loads the properties from a stream and sets the appropriate * requested values. * @throws IOException A fatal exception occurred while interacting * with the properties source stream. */ public void loadProperties() throws IOException { properties.load(source); if (propertyMap == null) { // No properties were requested, so there's no need to sweat it. propertyMap = new HashMap<String, TypedProperty<?>>(); } for(Entry<Object, Object> property : properties.entrySet()) { TypedProperty<?> typedProperty = propertyMap.get(property.getKey()); if (typedProperty == null) { continue; } else { typedProperty.doParse((String) property.getValue()); } } } } }
33.771739
86
0.663985
fbdda15ad6c702e9a2755af1994d4c3dd34fa5f7
4,457
/*---------------------------------------------------------------------------- * Copyright IBM Corp. 2015, 2016 All Rights Reserved * Copyright Universitat Rovira i Virgili. 2015, 2016 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 org.openstack.storlet.csv.clauses; import java.util.Arrays; import org.openstack.storlet.csv.Utils; import org.openstack.storlet.common.StorletLogger; /** * @author moatti * */ public class LeafClause extends Clause { private LeafOperator op; // the Operator of the Clause private int clauseColumnIndex; // its column index of the clause private String clauseOperand; // its clause operand public LeafClause(StorletLogger logger, String clauseStr) { super(logger); parse(clauseStr); Utils.doubleLogPrint(logger,"LeafClause constructor: " + op.getLeafOpLabel() + " for column " + clauseColumnIndex + " and with operand " + clauseOperand); } @Override public String toString() { return "Clause: op = " + op.getLeafOpLabel() + " column # =" + clauseColumnIndex + " Operand = " + clauseOperand; } public boolean isValidClause(StorletLogger logger, String[] trace_line) { String lineOperand; try { lineOperand = trace_line[clauseColumnIndex]; } catch( ArrayIndexOutOfBoundsException e) { Utils.doubleLogPrint(logger, "ArrayIndexOutOfBoundsException occurred, for trace_line = " + ( ( trace_line == null) ? " null " : Arrays.toString(trace_line) ) + " and clause = " + this); throw e; } return (op.isValid(clauseOperand, lineOperand)); } public int getMaxCol() { return clauseColumnIndex; } void parse(String clauseStr) { Utils.doubleLogPrint(logger,"LeafClause.parse for " + clauseStr); LeafOperator theOp; if (clauseStr.startsWith(LeafOperator.EQUAL.getLeafOpLabel())) { theOp = LeafOperator.EQUAL; } else if (clauseStr.startsWith(LeafOperator.NOT_EQUAL.getLeafOpLabel())) { theOp = LeafOperator.NOT_EQUAL; } else if (clauseStr.startsWith(LeafOperator.STARTS_WITH.getLeafOpLabel())) { theOp = LeafOperator.STARTS_WITH; } else if (clauseStr.startsWith(LeafOperator.ENDS_WITH.getLeafOpLabel())) { theOp = LeafOperator.ENDS_WITH; } else if (clauseStr.startsWith(LeafOperator.CONTAINS.getLeafOpLabel())) { theOp = LeafOperator.CONTAINS; } else { throw new RuntimeException("Unexpected clause operator " + clauseStr); } String[] ops = clauseStr.substring(theOp.getLeafOpLabel().length()).split(","); int clauseIndex; try { clauseIndex = Integer.parseInt(ops[0].substring(1)); // remove the "(" } catch (NumberFormatException e) { Utils.doubleLogPrint(logger,"parseClause for " + clauseStr + " encountered a NumberFormatException when trying to convert " + ops[0].substring(1) + " to int"); throw e; } clauseOperand = ops[1].substring(0, ops[1].length()-1); // remove the ")" op = theOp; clauseColumnIndex = clauseIndex; } @Override public boolean isLeaf() { return true; } @Override public boolean isValid(StorletLogger logger, String[] trace_line) { String lineOperand; try { lineOperand = trace_line[clauseColumnIndex]; } catch( ArrayIndexOutOfBoundsException e) { Utils.doubleLogPrint(logger, "ArrayIndexOutOfBoundsException occurred, for trace_line = " + ( ( trace_line == null) ? " null " : Arrays.toString(trace_line) ) + " and clause = " + this); throw e; } return (op.isValid(clauseOperand, lineOperand)); } }
39.794643
172
0.627328
024ff0f08aee86c858ecad63b2572f201f1491c4
2,432
package pt.tecnico.hds.client; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.*; public class DatabaseManager { private static DatabaseManager databaseManager; private static final String url = "jdbc:sqlite:db/client.db"; private static Connection c = null; public static Connection getConn() throws SQLException { if(c == null){ c = DriverManager.getConnection(url); } return c; } // static method to create instance of Singleton class public static DatabaseManager getInstance() { if (databaseManager == null) databaseManager = new DatabaseManager(); return databaseManager; } public void createDatabase() { String requests = "CREATE TABLE IF NOT EXISTS requests(requestId text PRIMARY KEY);"; Connection conn; try { if (!Files.exists(Paths.get("db/client.db"))) { conn = getConn(); Statement stmt4 = conn.createStatement(); //Statement stmt5 = conn.createStatement(); stmt4.execute(requests); //stmt5.execute("PRAGMA journal_mode = WAL;"); //populate(); //conn.close(); } } catch (SQLException e) { //System.out.println(e.getMessage()); } } public void addToRequests(String hash){ String sql = "INSERT INTO requests(requestId) Values(?)"; Connection conn; try { conn = getConn(); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, hash); pstmt.executeUpdate(); //conn.close(); } catch (SQLException e) { //System.out.println(e.getMessage()); } } public boolean verifyReplay(String hash) { String sql = "SELECT requestId FROM requests WHERE requestId=?"; Connection conn; try { conn = getConn(); PreparedStatement pstmt = conn.prepareStatement(sql); //System.out.println(hash); pstmt.setString(1, hash); ResultSet rs = pstmt.executeQuery(); //conn.close(); if (rs.next()) { return false; } } catch (SQLException e) { e.printStackTrace(); return false; } return true; } }
30.78481
93
0.555921
87000a9580322aff654a58deb6dd227b91e582ed
2,127
package esz.dev.delaunay; import org.opencv.core.Point; public class Triangle { private final Edge ab; private final Edge bc; private final Edge ca; private final Circle circumCircle; public Triangle(Point a, Point b, Point c) { this.ab = new Edge(a, b); this.bc = new Edge(b, c); this.ca = new Edge(c, a); this.circumCircle = calculateCircumCircle(a, b, c); } // https://en.wikipedia.org/wiki/Circumscribed_circle#Triangles private static Circle calculateCircumCircle(Point a, Point b, Point c) { double d = 2 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); double centerX = 1.0 / d * ((a.x * a.x + a.y * a.y) * (b.y - c.y) + (b.x * b.x + b.y * b.y) * (c.y - a.y) + (c.x * c.x + c.y * c.y) * (a.y - b.y)); double centerY = 1.0 / d * ((a.x * a.x + a.y * a.y) * (c.x - b.x) + (b.x * b.x + b.y * b.y) * (a.x - c.x) + (c.x * c.x + c.y * c.y) * (b.x - a.x)); Point bSign = new Point(b.x - a.x, b.y - a.y); Point cSign = new Point(c.x - a.x, c.y - a.y); double dSign = 2 * (bSign.x * cSign.y - bSign.y * cSign.x); double centerXSign = 1.0 / dSign * (cSign.y * (bSign.x * bSign.x + bSign.y * bSign.y) - bSign.y * (cSign.x * cSign.x + cSign.y * cSign.y)); double centerYSign = 1.0 / dSign * (bSign.x * (cSign.x * cSign.x + cSign.y * cSign.y) - cSign.x * (bSign.x * bSign.x + bSign.y * bSign.y)); double r = Math.sqrt(centerXSign * centerXSign + centerYSign * centerYSign); return new Circle(new Point(centerX, centerY), r); } public Circle getCircumCircle() { return circumCircle; } public Edge[] getEdges() { return new Edge[] {ab, bc, ca}; } public boolean containsEdge(Edge edge) { return ab.equals(edge) || bc.equals(edge) || ca.equals(edge); } public boolean containsVertex(Point vertex) { return ab.containsVertex(vertex) || bc.containsVertex(vertex) || ca.containsVertex(vertex); } public Point[] getVertices() { return new Point[] {ab.getA(), bc.getA(), ca.getA()}; } }
37.982143
155
0.554302
a46947593aef851ee46b0664e03f3291e0fe962c
9,111
package com.acgist.ding.view.common; import java.awt.AWTException; import java.awt.Color; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Robot; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import com.acgist.ding.Config; import com.acgist.ding.Dialogs; import com.acgist.ding.DingView; import com.acgist.ding.Exceptions; import com.acgist.ding.Internationalization; /** * 通用 * * @author acgist */ public class CommonView extends DingView { /** * 原始文本 */ private Text source; /** * 目标文本 */ private Text target; /** * 休息时间 */ private Combo restTime; /** * 结果文本 */ private Text result; /** * Control Key Code */ private static final int CONTROL = 0x40000; /** * 休息定时任务 */ private static ScheduledFuture<?> restScheduledFuture; @Override public void createPartControl(Composite composite) { this.layout(composite, SWT.VERTICAL); // 文本模块 final Composite sourceTargetGroup = this.buildFullComposite(composite, SWT.HORIZONTAL); this.source = this.buildMultiText(sourceTargetGroup, Internationalization.Message.COMMON_SOURCE); this.target = this.buildMultiText(sourceTargetGroup, Internationalization.Message.COMMON_TARGET); // 操作模块 final Group operationGroup = this.buildGroup(composite, Internationalization.Label.OPERATION, 0, 0, SWT.VERTICAL); // 颜色模块 final Composite colorGroup = this.buildGroup(operationGroup, Internationalization.Label.COLOR, 0, 0, SWT.HORIZONTAL); this.buildButton(colorGroup, Internationalization.Button.COLOR, this.colorConsumer); this.buildButton(colorGroup, Internationalization.Button.COLOR_HEX_RGB, this.colorHexRgbConsumer); this.buildButton(colorGroup, Internationalization.Button.COLOR_RGB_HEX, this.colorRgbHexConsumer); // 休息模块 final Composite restGroup = this.buildGroup(operationGroup, Internationalization.Label.REST, 0, 0, SWT.HORIZONTAL); this.restTime = this.buildSelect(restGroup, Internationalization.Label.REST_TIME, 2, "30S", "15M", "30M", "45M", "1H"); if(restScheduledFuture == null) { this.buildButton(restGroup, Internationalization.Button.REST, this.restConsumer); } else { this.buildButton(restGroup, Internationalization.Button.REST_CANCEL, this.restConsumer); } // 配置模块 final Composite configGroup = this.buildGroup(operationGroup, Internationalization.Label.CONFIG, 0, 0, SWT.HORIZONTAL); this.buildButton(configGroup, Internationalization.Button.FONT, this.fontConsumer); this.buildButton(configGroup, Internationalization.Button.ENCODING, this.encodingConsumer); this.buildButton(configGroup, Internationalization.Button.EYESHIELD, this.eyeshieldConsumer); // 正则表达式模块 final Composite regexGroup = this.buildGroup(operationGroup, Internationalization.Label.REGEX, 0, 0, SWT.HORIZONTAL); this.buildButton(regexGroup, Internationalization.Button.REGEX_FIND, this.regexFindConsumer); this.buildButton(regexGroup, Internationalization.Button.REGEX_MATCH, this.regexMatchConsumer); // 二级操作模块 final Composite subOperationGroup = this.buildGroup(operationGroup, Internationalization.Label.OPERATION, 0, 0, SWT.HORIZONTAL); this.buildButton(subOperationGroup, Internationalization.Button.RESET, this.resetConsumer); // 结果模块 final Composite resultGroup = this.buildFullComposite(composite, SWT.HORIZONTAL); this.result = this.buildMultiText(resultGroup, Internationalization.Message.COMMON_RESULT); } /** * 取色器 * * 鼠标移动取色位置单击Ctrl按键即可 * * 注意:不可失去焦点 */ private Consumer<MouseEvent> colorConsumer = event -> { final Button button = (Button) event.getSource(); if(Internationalization.get(Internationalization.Button.COLOR).equals(button.getText())) { button.setText(Internationalization.get(Internationalization.Button.COLOR_OFF)); Display.getDefault().addFilter(SWT.KeyDown, this.keyListener); } else { button.setText(Internationalization.get(Internationalization.Button.COLOR)); Display.getDefault().removeFilter(SWT.KeyDown, this.keyListener); } }; /** * 取色器按键 */ private Listener keyListener = keyEvent -> { if(keyEvent.keyCode == CONTROL) { try { final Robot robot = new Robot(); final Point point = MouseInfo.getPointerInfo().getLocation(); final Color color = robot.getPixelColor(point.x, point.y); this.source.setText(String.format("#%02X%02X%02X", color.getRed(), color.getGreen(), color.getBlue())); } catch (AWTException e) { Exceptions.error(this.getClass(), e); } } }; /** * 颜色转换:Hex To RGB */ private Consumer<MouseEvent> colorHexRgbConsumer = event -> { this.consumer(this.source, sourceValue -> { if(sourceValue.startsWith("#")) { sourceValue = sourceValue.substring(1); } int red = 0; int green = 0; int blue = 0; if(sourceValue.length() == 3) { red = Integer.parseInt(sourceValue.substring(0, 1).repeat(2), 16); green = Integer.parseInt(sourceValue.substring(1, 2).repeat(2), 16); blue = Integer.parseInt(sourceValue.substring(2, 3).repeat(2), 16); this.target.setText(String.format("(%d, %d, %d)", red, green, blue)); } else if(sourceValue.length() == 6) { red = Integer.parseInt(sourceValue.substring(0, 2), 16); green = Integer.parseInt(sourceValue.substring(2, 4), 16); blue = Integer.parseInt(sourceValue.substring(4, 6), 16); this.target.setText(String.format("(%d, %d, %d)", red, green, blue)); } }); }; /** * 颜色转换:RGB To Hex */ private Consumer<MouseEvent> colorRgbHexConsumer = event -> { this.consumer(this.target, targetValue -> { if(targetValue.startsWith("(")) { targetValue = targetValue.substring(1); } if(targetValue.endsWith(")")) { targetValue = targetValue.substring(0, targetValue.length() - 1); } final String[] rgbs = targetValue.split(","); if(rgbs.length == 3 || rgbs.length == 4) { final int red = Integer.parseInt(rgbs[0].trim()); final int green = Integer.parseInt(rgbs[1].trim()); final int blue = Integer.parseInt(rgbs[2].trim()); this.source.setText(String.format("#%02X%02X%02X", red, green, blue)); } }); }; /** * 定时休息 */ private Consumer<MouseEvent> restConsumer = event -> { final Button button = (Button) event.getSource(); if(restScheduledFuture == null) { final int restTime = this.restTime(); restScheduledFuture = Config.SCHEDULED.scheduleAtFixedRate(() -> { Display.getDefault().syncExec(() -> Dialogs.info(Internationalization.Message.REST)); }, restTime, restTime, TimeUnit.SECONDS); button.setText(Internationalization.get(Internationalization.Button.REST_CANCEL)); } else { restScheduledFuture.cancel(true); restScheduledFuture = null; button.setText(Internationalization.get(Internationalization.Button.REST)); } }; /** * 休息时间 * * @return 休息时间 */ private int restTime() { return switch (this.restTime.getText()) { case "30S" -> 30; case "15M" -> 15 * 60; case "30M" -> 30 * 60; case "45M" -> 45 * 60; case "1H" -> 60 * 60; default -> 10; }; } /** * 字体调整 */ private Consumer<MouseEvent> fontConsumer = event -> { // final IPreferencesService preferencesService = Platform.getPreferencesService(); // final Preferences preferences = preferencesService.getRootNode(); // final String[] keys = preferences.childrenNames(); // final String[] keys = preferences.keys(); // TODO:实现 }; /** * 编码调整 */ private Consumer<MouseEvent> encodingConsumer = event -> { // TODO:实现 }; /** * 护眼模式 */ private Consumer<MouseEvent> eyeshieldConsumer = event -> { this.result.setText("202,232,202"); // TODO:实现 }; /** * 正则表达式提取 */ private Consumer<MouseEvent> regexFindConsumer = event -> { this.consumer(this.source, this.target, (sourceValue, targetValue) -> { this.result.setText(Config.EMPTY); final Pattern pattern = Pattern.compile(targetValue); final Matcher matcher = pattern.matcher(sourceValue); while(matcher.find()) { final int count = matcher.groupCount(); for (int index = 1; index <= count; index++) { this.result.append(matcher.group(index)); this.result.append(Config.NEW_LINE); } } }); }; /** * 正则表达式匹配 */ private Consumer<MouseEvent> regexMatchConsumer = event -> { this.consumer(this.source, this.target, (sourceValue, targetValue) -> { if(sourceValue.matches(targetValue)) { Dialogs.info(Internationalization.Message.SUCCESS); } else { Dialogs.info(Internationalization.Message.FAIL); } }); }; /** * 重置 */ private Consumer<MouseEvent> resetConsumer = event -> { this.source.setText(Config.EMPTY); this.target.setText(Config.EMPTY); this.result.setText(Config.EMPTY); }; }
32.308511
130
0.714192
4a30538f43c08cbc89046b5ddcb705855e49c05e
1,651
/* * Copyright 2013 Swedish E-identification Board (E-legitimationsnämnden) * * Licensed under the EUPL, Version 1.1 or ñ as soon they will be approved by the * European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in writing, software distributed * under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * See the Licence for the specific language governing permissions and limitations * under the Licence. */ package com.aaasec.sigserv.cscommon; import java.io.UnsupportedEncodingException; import java.util.logging.Level; import java.util.logging.Logger; /** * URL Encoder */ public class URLEncoder { public static String queryEncode(String codedStr) { // Add any custom pre processing here String coded = ""; try { coded = java.net.URLEncoder.encode(codedStr, "UTF-8"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(URLEncoder.class.getName()).log(Level.WARNING, null, ex); } //Add any custom cleanup or customization if needed here return coded; } public static String maskB64String (String b64String){ return b64String.replace('+', '-'); } public static String unmaskB64String (String masked){ return masked.replace('-', '+'); } }
31.150943
86
0.672925
a2cbf9aec0df70c1e9ad29c1f3bbdf7b485e0456
254
package kr.ac.hs.oing.post.dto.request; public class PostUpdateRequest { private String title; private String content; public String getTitle() { return title; } public String getContent() { return content; } }
16.933333
39
0.641732
47cd13b0f3dbfb42d41573948ec73adf608fcf47
629
package br.com.zupacademy.charles.transacao.repository; import br.com.zupacademy.charles.transacao.model.Transacoes; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface TransacoesRepository extends JpaRepository<Transacoes, String> { @Query("SELECT f FROM Transacoes f WHERE f.cartao.id = :idCartao") Page<Transacoes> findByTransacoesCartao(String idCartao, Pageable paginacao); }
39.3125
81
0.828299
28d36027414ba953b3aeb5a6d19111cd3333afce
3,999
package com.civfactions.SabreCore; import java.util.Collection; import java.util.UUID; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.plugin.java.JavaPlugin; import com.civfactions.SabreApi.BlockPermission; import com.civfactions.SabreApi.PlayerSpawner; import com.civfactions.SabreApi.PlayerVanisher; import com.civfactions.SabreApi.SabreCommand; import com.civfactions.SabreApi.SabrePlayer; import com.civfactions.SabreApi.SabrePlugin; import com.civfactions.SabreApi.data.DataStorage; import com.civfactions.SabreApi.data.SabreConfig; import com.civfactions.SabreApi.util.TextFormatter; import com.civfactions.SabreCore.cmd.CmdAutoHelp; import com.civfactions.SabreCore.cmd.CmdBan; import com.civfactions.SabreCore.cmd.CmdFly; import com.civfactions.SabreCore.cmd.CmdGamemode; import com.civfactions.SabreCore.cmd.CmdMore; import com.civfactions.SabreCore.cmd.CmdSabreRespawn; import com.civfactions.SabreCore.cmd.CmdSabre; import com.civfactions.SabreCore.cmd.CmdSetSpawn; import com.civfactions.SabreCore.cmd.CmdUnban; import com.civfactions.SabreCore.cmd.CmdVanish; import com.civfactions.SabreCore.data.CoreConfiguration; import com.civfactions.SabreCore.data.MongoStorage; import com.civfactions.SabreCore.util.TextUtil; /** * This class is the provides the core Sabre classes. * */ public class SabreCorePlugin extends SabrePlugin { private final DataStorage storage = new MongoStorage(this); private final PlayerManager pm = new PlayerManager(this, storage); private final BlockManager bm = new BlockManager(this, storage); private final CorePlayerSpawner spawner = new CorePlayerSpawner(this); private final CoreVanisher vanisher = new CoreVanisher(); private final CmdAutoHelp autoHelp = new CmdAutoHelp(this); private final TextUtil textUtil = new TextUtil(); private final StaticBlockPermission defaultBlockPerms = new StaticBlockPermission(true, true); @Override public void onEnable() { super.onEnable(); // Register core commands registerCommand(new CmdSabre(this)); registerCommand(new CmdBan(this)); registerCommand(new CmdFly(this)); registerCommand(new CmdGamemode(this)); registerCommand(new CmdMore(this)); registerCommand(new CmdSabreRespawn(this)); registerCommand(new CmdSetSpawn(this)); registerCommand(new CmdUnban(this)); registerCommand(new CmdVanish(this)); // Register configuration objects registerConfigObject(storage); registerConfigObject(spawner); registerConfigObject(textUtil); // Loads data into all configuration objects readConfiguration(); if (storage.connect()) { pm.load(); } registerEvents(pm); registerEvents(bm); super.postEnable(); } @Override public void onDisable() { storage.disconnect(); super.onDisable(); } @Override public DataStorage getStorage() { return storage; } @Override public Collection<SabrePlayer> getOnlinePlayers() { return pm.getOnlinePlayers(); } @Override public CorePlayer getPlayer(String name) { return pm.getPlayerByName(name); } @Override public CorePlayer getPlayer(UUID uid) { return pm.getPlayerById(uid); } @Override public String formatText(String text, Object... args) { return textUtil.parse(text, args); } @Override public String formatText(String text) { return textUtil.parse(text); } @Override public TextFormatter getFormatter() { return textUtil; } @Override public SabreConfig getSabreConfig(JavaPlugin plugin) { return new CoreConfiguration(plugin); } @Override public SabreCommand<?> getAutoHelp() { return autoHelp; } public PlayerManager getPlayerManager() { return pm; } @Override public BlockPermission getBlockPermission(Block b) { return defaultBlockPerms; } @Override public BlockPermission getBlockPermission(Location l) { return defaultBlockPerms; } @Override public PlayerSpawner getSpawner() { return spawner; } @Override public PlayerVanisher getVanisher() { return vanisher; } }
25.471338
95
0.778195
06e5c9b18ccf860e64972200fbe5160b1d3bf95e
125
package testclasses.exceptions.nullpointer; public class SupportClassObject { public String a; public String[] b; }
17.857143
43
0.752
9bddf4d3ef320bb7a77e95015cd11797d45b0586
2,975
package com.refinedmods.refinedstorage2.platform.forge.render.model.baked; import com.refinedmods.refinedstorage2.platform.common.util.BiDirection; import java.util.List; import java.util.function.Function; import com.google.common.collect.ImmutableList; import com.mojang.math.Matrix4f; import com.mojang.math.Quaternion; import com.mojang.math.Transformation; import com.mojang.math.Vector3f; import com.mojang.math.Vector4f; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.core.Direction; import net.minecraft.core.Vec3i; import net.minecraftforge.client.model.pipeline.BakedQuadBuilder; import net.minecraftforge.client.model.pipeline.TRSRTransformer; public final class QuadTransformer { private QuadTransformer() { } public static List<BakedQuad> transformSideAndRotate(Function<Direction, List<BakedQuad>> quadGetter, BiDirection direction, Direction side) { Transformation transformation = new Transformation(null, createQuaternion(direction), null, null); ImmutableList.Builder<BakedQuad> rotated = ImmutableList.builder(); for (BakedQuad quad : quadGetter.apply(transformSide(side, transformation.getMatrix()))) { BakedQuadBuilder builder = new BakedQuadBuilder(quad.getSprite()); TRSRTransformer transformer = new TRSRTransformer(builder, transformation.blockCenterToCorner()); quad.pipe(transformer); builder.setQuadOrientation(rotate(quad.getDirection(), transformation.getMatrix())); rotated.add(builder.build()); } return rotated.build(); } private static Quaternion createQuaternion(BiDirection direction) { return new Quaternion(direction.getVec().x(), direction.getVec().y(), direction.getVec().z(), true); } private static Direction transformSide(Direction facing, Matrix4f mat) { for (Direction face : Direction.values()) { if (rotate(face, mat) == facing) { return face; } } return null; } private static Direction rotate(Direction facing, Matrix4f mat) { Vec3i dir = facing.getNormal(); Vector4f vec = new Vector4f(dir.getX(), dir.getY(), dir.getZ(), 1); vec.transform(mat); return Direction.getNearest(vec.x(), vec.y(), vec.z()); } public static List<BakedQuad> translate(List<BakedQuad> quads, Vector3f translation) { Transformation transformation = new Transformation(translation, null, null, null); ImmutableList.Builder<BakedQuad> translated = ImmutableList.builder(); for (BakedQuad quad : quads) { BakedQuadBuilder builder = new BakedQuadBuilder(quad.getSprite()); TRSRTransformer transformer = new TRSRTransformer(builder, transformation.blockCenterToCorner()); quad.pipe(transformer); translated.add(builder.build()); } return translated.build(); } }
37.1875
146
0.703866
bd8a95987690a1284a3aee710abb66ddc929db90
80
package org.pitest.plugin; public enum ToggleStatus { ACTIVATE, DEACTIVATE }
13.333333
26
0.775
0c9f467372a69ba7b734319f26f2718d60827aed
741
package com.zhangshuo.user.dao; import com.zhangshuo.user.domain.User; /** * 用户添加等 * interface */ public interface UserDao { /** * 添加用户 * @param user */ public int add(User user); /** * 由用户的身份(姓名或邮箱)获取用户信息 * @param LoginIdentity * @return */ public User getDbUser(String LoginIdentity); /** * 重新输入密码 * @param userEmail * @param userPassword * @return */ public int resetPassword(String userEmail,String userPassword); /** * 更新用户的checkCode * @param email * @param checkCode * @return */ public int updateCheckCode(String email, String checkCode); /** * 检验校验码 * @param userEmail * @param checkCode * @return */ public boolean isCheckCode(String userEmail,String checkCode); }
15.4375
64
0.662618
b13e45e62d19593260b83eb96f6c2ef095868825
416
package io.github.codejanovic.java.shortcuts; import java.util.Objects; public final class Shortcuts { public static String f(String format, Object... args) { return String.format(format, args); } public static <T> T nn(T obj) { return Objects.requireNonNull(obj); } public static <T> T nn(T obj, String message) { return Objects.requireNonNull(obj, message); } }
23.111111
59
0.658654
6dc7d2552cc61f9b409b445f2cd48077a5c24c8f
10,839
/* * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.pricer.rate; import static com.opengamma.strata.basics.currency.Currency.GBP; import static com.opengamma.strata.basics.currency.Currency.USD; import static com.opengamma.strata.basics.index.OvernightIndices.GBP_SONIA; import static com.opengamma.strata.basics.index.OvernightIndices.USD_FED_FUND; import static com.opengamma.strata.collect.TestHelper.assertSerialization; import static com.opengamma.strata.collect.TestHelper.coverBeanEquals; import static com.opengamma.strata.collect.TestHelper.coverImmutableBean; import static com.opengamma.strata.collect.TestHelper.date; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import java.time.LocalDate; import org.junit.jupiter.api.Test; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.currency.CurrencyPair; import com.opengamma.strata.basics.currency.FxMatrix; import com.opengamma.strata.basics.index.OvernightIndexObservation; import com.opengamma.strata.market.sensitivity.MutablePointSensitivities; import com.opengamma.strata.market.sensitivity.PointSensitivities; import com.opengamma.strata.market.sensitivity.PointSensitivityBuilder; import com.opengamma.strata.pricer.ZeroRateSensitivity; /** * Test {@link OvernightRateSensitivity}. */ public class OvernightRateSensitivityTest { private static final ReferenceData REF_DATA = ReferenceData.standard(); private static final LocalDate DATE = date(2015, 8, 27); private static final LocalDate DATE2 = date(2015, 9, 27); private static final OvernightIndexObservation GBP_SONIA_OBSERVATION = OvernightIndexObservation.of(GBP_SONIA, DATE, REF_DATA); private static final OvernightIndexObservation GBP_SONIA_OBSERVATION2 = OvernightIndexObservation.of(GBP_SONIA, DATE2, REF_DATA); private static final OvernightIndexObservation USD_FED_FUND_OBSERVATION2 = OvernightIndexObservation.of(USD_FED_FUND, DATE2, REF_DATA); //------------------------------------------------------------------------- @Test public void test_of_noCurrency() { OvernightRateSensitivity test = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); assertThat(test.getIndex()).isEqualTo(GBP_SONIA); assertThat(test.getCurrency()).isEqualTo(GBP); assertThat(test.getEndDate()).isEqualTo(date(2015, 8, 28)); assertThat(test.getSensitivity()).isEqualTo(32d); assertThat(test.getIndex()).isEqualTo(GBP_SONIA); } @Test public void test_of_currency() { OvernightRateSensitivity test = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, USD, 32d); assertThat(test.getIndex()).isEqualTo(GBP_SONIA); assertThat(test.getCurrency()).isEqualTo(USD); assertThat(test.getEndDate()).isEqualTo(date(2015, 8, 28)); assertThat(test.getSensitivity()).isEqualTo(32d); assertThat(test.getIndex()).isEqualTo(GBP_SONIA); } @Test public void test_ofPeriod() { OvernightRateSensitivity test = OvernightRateSensitivity.ofPeriod( GBP_SONIA_OBSERVATION, date(2015, 10, 27), GBP, 32d); assertThat(test.getIndex()).isEqualTo(GBP_SONIA); assertThat(test.getCurrency()).isEqualTo(GBP); assertThat(test.getEndDate()).isEqualTo(date(2015, 10, 27)); assertThat(test.getSensitivity()).isEqualTo(32d); assertThat(test.getIndex()).isEqualTo(GBP_SONIA); } @Test public void test_badDateOrder() { assertThatIllegalArgumentException() .isThrownBy(() -> OvernightRateSensitivity.ofPeriod(GBP_SONIA_OBSERVATION, DATE, GBP, 32d)); } //------------------------------------------------------------------------- @Test public void test_withCurrency() { OvernightRateSensitivity base = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); assertThat(base.withCurrency(GBP)).isSameAs(base); LocalDate mat = GBP_SONIA_OBSERVATION.getMaturityDate(); OvernightRateSensitivity expected = OvernightRateSensitivity.ofPeriod(GBP_SONIA_OBSERVATION, mat, USD, 32d); OvernightRateSensitivity test = base.withCurrency(USD); assertThat(test).isEqualTo(expected); } //------------------------------------------------------------------------- @Test public void test_withSensitivity() { OvernightRateSensitivity base = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); OvernightRateSensitivity expected = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 20d); OvernightRateSensitivity test = base.withSensitivity(20d); assertThat(test).isEqualTo(expected); } //------------------------------------------------------------------------- @Test public void test_compareKey() { OvernightRateSensitivity a1 = OvernightRateSensitivity.ofPeriod(GBP_SONIA_OBSERVATION, date(2015, 10, 27), GBP, 32d); OvernightRateSensitivity a2 = OvernightRateSensitivity.ofPeriod(GBP_SONIA_OBSERVATION, date(2015, 10, 27), GBP, 32d); OvernightRateSensitivity b = OvernightRateSensitivity.ofPeriod(USD_FED_FUND_OBSERVATION2, date(2015, 10, 27), GBP, 32d); OvernightRateSensitivity c = OvernightRateSensitivity.ofPeriod(GBP_SONIA_OBSERVATION, date(2015, 10, 27), USD, 32d); OvernightRateSensitivity d = OvernightRateSensitivity.ofPeriod(GBP_SONIA_OBSERVATION2, date(2015, 10, 27), GBP, 32d); OvernightRateSensitivity e = OvernightRateSensitivity.ofPeriod(GBP_SONIA_OBSERVATION, date(2015, 11, 27), GBP, 32d); ZeroRateSensitivity other = ZeroRateSensitivity.of(GBP, 2d, 32d); assertThat(a1.compareKey(a2)).isEqualTo(0); assertThat(a1.compareKey(b) < 0).isTrue(); assertThat(b.compareKey(a1) > 0).isTrue(); assertThat(a1.compareKey(c) < 0).isTrue(); assertThat(c.compareKey(a1) > 0).isTrue(); assertThat(a1.compareKey(e) < 0).isTrue(); assertThat(d.compareKey(a1) > 0).isTrue(); assertThat(a1.compareKey(d) < 0).isTrue(); assertThat(e.compareKey(a1) > 0).isTrue(); assertThat(a1.compareKey(other) < 0).isTrue(); assertThat(other.compareKey(a1) > 0).isTrue(); } //------------------------------------------------------------------------- @Test public void test_convertedTo() { LocalDate fixingDate = DATE; LocalDate endDate = date(2015, 10, 27); double sensi = 32d; OvernightRateSensitivity base = OvernightRateSensitivity.ofPeriod( OvernightIndexObservation.of(GBP_SONIA, fixingDate, REF_DATA), endDate, GBP, sensi); double rate = 1.5d; FxMatrix matrix = FxMatrix.of(CurrencyPair.of(GBP, USD), rate); OvernightRateSensitivity test1 = (OvernightRateSensitivity) base.convertedTo(USD, matrix); OvernightRateSensitivity expected = OvernightRateSensitivity.ofPeriod( OvernightIndexObservation.of(GBP_SONIA, fixingDate, REF_DATA), endDate, USD, rate * sensi); assertThat(test1).isEqualTo(expected); OvernightRateSensitivity test2 = (OvernightRateSensitivity) base.convertedTo(GBP, matrix); assertThat(test2).isEqualTo(base); } //------------------------------------------------------------------------- @Test public void test_multipliedBy() { OvernightRateSensitivity base = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); OvernightRateSensitivity expected = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d * 3.5d); OvernightRateSensitivity test = base.multipliedBy(3.5d); assertThat(test).isEqualTo(expected); } //------------------------------------------------------------------------- @Test public void test_mapSensitivity() { OvernightRateSensitivity base = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); OvernightRateSensitivity expected = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 1 / 32d); OvernightRateSensitivity test = base.mapSensitivity(s -> 1 / s); assertThat(test).isEqualTo(expected); } //------------------------------------------------------------------------- @Test public void test_normalize() { OvernightRateSensitivity base = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); OvernightRateSensitivity test = base.normalize(); assertThat(test).isSameAs(base); } //------------------------------------------------------------------------- @Test public void test_combinedWith() { OvernightRateSensitivity base1 = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); OvernightRateSensitivity base2 = OvernightRateSensitivity.of( OvernightIndexObservation.of(GBP_SONIA, date(2015, 10, 27), REF_DATA), 22d); MutablePointSensitivities expected = new MutablePointSensitivities(); expected.add(base1).add(base2); PointSensitivityBuilder test = base1.combinedWith(base2); assertThat(test).isEqualTo(expected); } @Test public void test_combinedWith_mutable() { OvernightRateSensitivity base = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); MutablePointSensitivities expected = new MutablePointSensitivities(); expected.add(base); PointSensitivityBuilder test = base.combinedWith(new MutablePointSensitivities()); assertThat(test).isEqualTo(expected); } //------------------------------------------------------------------------- @Test public void test_buildInto() { OvernightRateSensitivity base = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); MutablePointSensitivities combo = new MutablePointSensitivities(); MutablePointSensitivities test = base.buildInto(combo); assertThat(test).isSameAs(combo); assertThat(test.getSensitivities()).containsExactly(base); } //------------------------------------------------------------------------- @Test public void test_build() { OvernightRateSensitivity base = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); PointSensitivities test = base.build(); assertThat(test.getSensitivities()).containsExactly(base); } //------------------------------------------------------------------------- @Test public void test_cloned() { OvernightRateSensitivity base = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); OvernightRateSensitivity test = base.cloned(); assertThat(test).isSameAs(base); } //------------------------------------------------------------------------- @Test public void coverage() { OvernightRateSensitivity test = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); coverImmutableBean(test); OvernightRateSensitivity test2 = OvernightRateSensitivity.of(USD_FED_FUND_OBSERVATION2, 16d); coverBeanEquals(test, test2); } @Test public void test_serialization() { OvernightRateSensitivity test = OvernightRateSensitivity.of(GBP_SONIA_OBSERVATION, 32d); assertSerialization(test); } }
45.927966
124
0.698496
049542d657f5b8bdb6cc5b55c0dfddb1e9be4ad5
1,547
// Copyright (c) Aetheros, Inc. See COPYRIGHT package com.aetheros.aos.onem2m.common.resources; /** * Structure class for payload container serialization. */ public class PC { AE ae; Node nod; /** * Default constructor. */ public PC() {} /** * Constructor II * * @param ae An instance of AE. */ public PC(AE ae) { this.ae = ae; } /** * Constructor II * * @param nod An instance of node. */ public PC(Node node) { this.nod= node; } /** * Constructor III * * @param ae An instance of AE. * @param nod An instance of node. */ public PC(AE ae, Node nod) { this.ae = ae; this.nod = nod; } /** * @return Node The node resource. */ public Node getNod() { return this.nod; } /** * @return AE The application entity. */ public AE getAe() { return this.ae; } /** * @param ae The application entity. */ public void setAe(AE ae) { this.ae = ae; } /** * @return String The string representation of the instance. */ @Override public String toString() { if(this.ae != null) { return "{" + " ae='" + getAe() + "'" + "}"; } else if(this.nod != null) { return "{" + " ae='" + getNod() + "'" + "}"; } else { return "{}"; } } }
18.2
64
0.444732
806ac7d26193776ee2a009041c5efe9370b7d5e1
4,135
package com.manywords.softworks.tafl.network.server.database.file; import com.manywords.softworks.tafl.network.server.NetworkServer; import com.manywords.softworks.tafl.network.server.database.PlayerDatabase; import com.manywords.softworks.tafl.network.server.database.PlayerRecord; import java.io.*; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by jay on 5/26/16. */ public class FileBackedPlayerDatabase extends PlayerDatabase { private File mDatabase; private List<FilePlayerRecord> mPlayerRecords = new ArrayList<>(); public FileBackedPlayerDatabase(NetworkServer server, File database) { super(server); mDatabase = database; boolean success = true; if(!mDatabase.exists()) { if(!mDatabase.getParentFile().exists()) { success = mDatabase.getParentFile().mkdirs(); } try { success &= mDatabase.createNewFile(); } catch (IOException e) { success = false; } } if(!success) throw new RuntimeException("Could not create database!"); } private synchronized int getPlayerIndex(String username) { int i = 0; for(PlayerRecord pr : mPlayerRecords) { if(username.equals(pr.getUsername())) return i; i++; } return -1; } @Override public synchronized PlayerRecord getPlayer(String username) { int index = getPlayerIndex(username); return (index == -1 ? null : mPlayerRecords.get(index)); } @Override public synchronized boolean writePlayer(PlayerRecord dataHolder) { int index = getPlayerIndex(dataHolder.getUsername()); if(index != -1) { mPlayerRecords.remove(index); mPlayerRecords.add(index, new FilePlayerRecord(dataHolder)); } else { mPlayerRecords.add(new FilePlayerRecord(dataHolder)); } flushDatabaseInternal(); return true; } private synchronized void flushDatabaseInternal() { try (PrintWriter pw = new PrintWriter(mDatabase)) { for(FilePlayerRecord pr : mPlayerRecords) { pw.println(pr.toString()); } } catch (FileNotFoundException e) { throw new RuntimeException("Failed to write to database file"); } } @Override public synchronized void flushDatabase() { // no-op: database is always flushed after writing } @Override public synchronized void updateDatabase() { mPlayerRecords.clear(); try (BufferedReader reader = new BufferedReader(new FileReader(mDatabase))) { String in; while((in = reader.readLine()) != null) { FilePlayerRecord r = new FilePlayerRecord(in); long time = System.currentTimeMillis(); long offset = 3600 * 24 * 7 * 1000; // One week if(time - r.getLastLoggedIn().getTime() < offset) { // Only load players who are less than a week old. mPlayerRecords.add(r); } } } catch (FileNotFoundException e) { throw new RuntimeException("Failed to open database file"); } catch (IOException e) { throw new RuntimeException("Failed to read database file"); } // Flush the database to clear out any expired players. flushDatabaseInternal(); } private class FilePlayerRecord extends GenericPlayerRecord { public FilePlayerRecord(PlayerRecord record) { super(record); } public FilePlayerRecord(String data) { String[] parts = data.split("\\|"); username = parts[0]; salt = parts[1]; hashedPassword = parts[2]; lastLoggedIn = new Date(Long.parseLong(parts[3])); } @Override public String toString() { return username + "|" + salt + "|" + hashedPassword + "|" + lastLoggedIn.getTime(); } } }
31.325758
95
0.596131
cc4b4b8bbf31e74192f0fbe126453efeae51a3ec
895
package org.vrhel.graphics; abstract class AbstractBuffer { private static int nextID = 0; protected int id; protected boolean enabled; AbstractBuffer() { this.enabled = true; this.id = nextID; nextID++; AbstractBufferHandler.getHandler().add(this); } /** * Returns the ID of this buffer. * * @return The ID. */ public int getID() { return id; } /** * Sets whether this buffer is enabled. * * @param enabled Whether this buffer is * enabled. */ public final void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Returns whether this buffer is enabled. * * @return <code>true</code> if this buffer is * enabled and <code>false</code> otherwise. */ public final boolean isEnabled() { return enabled; } ObjectBuffer getObjectBuffer() { return null; } abstract void render(); abstract void destroy(); }
16.272727
48
0.656983
b85d3c66e06f8204dfe0a4d84656f0174cfec1f4
1,721
/* * Company * Copyright (C) 2014-2020 All Rights Reserved. */ package com.cwenao.leetcode.algs.first; import java.util.Arrays; /** * TODO : Statement the class description * * @author cwenao * @version $Id CanPartition.java, v1.0.0 2020-12-17 21:16 cwenao Exp $$ */ public class CanPartition { public boolean canPartition(int[] nums) { return canPartitionByDP(nums); } private boolean canPartitionByDP(int[] nums) { int sum = Arrays.stream(nums).sum(); if (sum % 2 != 0) { return false; } int n = nums.length; //两个子集和相等则,每个子集的和为sum/2 sum = sum / 2; //DP状态转移方程 //dp[n][j]: 0...n个物品,当前背包容量为j时的状态,为true则表示刚好装满背包 //dp[n-1][j-nums[n-1]]: n-1个物品体积为j-num[n-1] //dp[n][j] 状态由以下两个状态决定: //1.装入nums[n] = j(dp[n-1][j-nums[n-1]] ) //2.不装入nums[n] = j (dp[n-1][j]) //dp[n][j] = dp[n-1][j-nums[n-1]] | dp[n-1][j] boolean[][] dp = new boolean[n + 1][sum + 1]; for (int i = 0; i < dp.length; i++) { dp[i][0] = true; } dp[0][0] = true; for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { if (j - nums[i - 1] < 0) { //容量不够 dp[i][j] = dp[i - 1][j]; } else { //容量够 dp[i][j] = dp[i - 1][j] | dp[i - 1][j - nums[i - 1]]; } } } return dp[n][sum]; } public static void main(String[] args) { int[] nums = {1, 5, 12, 5}; CanPartition canPartition = new CanPartition(); System.out.println(canPartition.canPartition(nums)); } }
26.075758
73
0.463684
f3871a8569e2708876ce1cd1d46ba917ac1013c7
637
package fr.tse.fise2.heapoverflow.wikidata; public class WdTemplateLangCode { private String value; private String language; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } @Override public String toString() { return "WdWdTemplateLangCode{" + "value='" + value + '\'' + ", language='" + language + '\'' + '}'; } }
18.735294
50
0.55102
a997febfb88a8e0cb54c1b8e6f75a5e359a2f2fa
1,516
package org.folio.rest.validator; import org.apache.commons.lang.RandomStringUtils; import org.folio.rest.exception.InputValidationException; import org.folio.rest.jaxrs.model.ProviderPutDataAttributes; import org.folio.rest.jaxrs.model.ProviderPutData; import org.folio.rest.jaxrs.model.ProviderPutRequest; import org.folio.rest.jaxrs.model.Token; import org.junit.Test; public class ProviderPutBodyValidatorTest { private final ProviderPutBodyValidator validator = new ProviderPutBodyValidator(); @Test public void shouldNotThrowExceptionWhenTokenIsMissing() { ProviderPutRequest request = new ProviderPutRequest(); validator.validate(request); } @Test public void shouldNotThrowExceptionWhenTokenIsValidLength() { Token providerToken = new Token(); providerToken.setValue(RandomStringUtils.randomAlphanumeric(500)); ProviderPutRequest request = new ProviderPutRequest() .withData(new ProviderPutData().withAttributes(new ProviderPutDataAttributes().withProviderToken(providerToken))); validator.validate(request); } @Test(expected = InputValidationException.class) public void shouldThrowExceptionWhenTokenIsTooLong() { Token providerToken = new Token(); providerToken.setValue(RandomStringUtils.randomAlphanumeric(501)); ProviderPutRequest request = new ProviderPutRequest() .withData(new ProviderPutData().withAttributes(new ProviderPutDataAttributes().withProviderToken(providerToken))); validator.validate(request); } }
35.255814
122
0.794855
5a25e1bf47570af5e318d7cfae8ecdcef263c96e
736
/** * */ package fr.n7.stl.tam.ast; /** * Sequence of TAMInstruction. * @author Marc Pantel * */ public interface Fragment { /** * Adds a TAM instruction at the end of the fragment. * @param _instruction TAM instruction added at the end of the fragment. */ public void add(TAMInstruction _instruction); /** * Sets the label of the first TAM instruction of the fragment. * @param _label Label that is set to the first TAM instruction of the fragment. */ public void set(String _label); /** * Add the instructions from the provided fragment at the end of the fragment. * @param _fragment Fragment whose instructions are added at the end of the fragment. */ public void append(Fragment _fragment); }
23
86
0.703804
64de135a8208f0fa4bdadcf2eac80a8a43c0c013
708
package by.andd3dfx.hello; import by.andd3dfx.grpc.HelloRequest; import by.andd3dfx.grpc.HelloResponse; import by.andd3dfx.grpc.HelloServiceGrpc.HelloServiceImplBase; import io.grpc.stub.StreamObserver; public class HelloServiceImpl extends HelloServiceImplBase { @Override public void hello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { String greeting = String.format("Hello, %s %s", request.getFirstName(), request.getLastName()); HelloResponse response = HelloResponse.newBuilder() .setGreeting(greeting) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); } }
33.714286
104
0.716102
232c377c43918ea43a90fa083eebf80c598f56e7
3,271
package cn.leancloud.kafka.consumer; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.function.BiConsumer; import static java.util.Objects.requireNonNull; /** * A wrapper over a {@link ConsumerRecordHandler} to catch and swallow all the exceptions throw from the * wrapped {@code ConsumerRecordHandler} when it failed to handle a consumed record. * <p> * This handler seems good to improve the availability of the consumer because it can swallow all the exceptions * on handling a record and carry on to handle next record. But it actually can compromise * the consumer to prevent a livelock, where the application did not crash but fails to * make progress for some reason. * <p> * Please use it judiciously. Usually fail fast, let the polling thread exit on exception, is your best choice. * * @param <K> the type of key for records consumed from Kafka * @param <V> the type of value for records consumed from Kafka */ public final class CatchAllExceptionConsumerRecordHandler<K, V> implements ConsumerRecordHandler<K, V> { private static final Logger logger = LoggerFactory.getLogger(CatchAllExceptionConsumerRecordHandler.class); private final ConsumerRecordHandler<K, V> wrappedHandler; private final BiConsumer<ConsumerRecord<K, V>, Throwable> errorConsumer; /** * Constructor for {@code CatchAllExceptionConsumerRecordHandler} to just log the failed record when * the wrapped handler failed on calling {@link ConsumerRecordHandler#handleRecord(ConsumerRecord)}. * * @param wrappedHandler the wrapped {@link ConsumerRecordHandler}. * @throws NullPointerException when {@code wrappedHandler} is null */ public CatchAllExceptionConsumerRecordHandler(ConsumerRecordHandler<K, V> wrappedHandler) { this(wrappedHandler, (record, throwable) -> logger.error("Handle kafka consumer record: " + record + " failed.", throwable)); } /** * Constructor for {@code CatchAllExceptionConsumerRecordHandler} to use a {@link BiConsumer} to handle the * failed record when the wrapped handler failed on calling {@link ConsumerRecordHandler#handleRecord(ConsumerRecord)}. * * @param wrappedHandler the wrapped {@link ConsumerRecordHandler}. * @param errorConsumer a {@link BiConsumer} to consume the failed record and the exception thrown from * the {@link ConsumerRecordHandler#handleRecord(ConsumerRecord)} * @throws NullPointerException when {@code wrappedHandler} or {@code errorConsumer} is null */ public CatchAllExceptionConsumerRecordHandler(ConsumerRecordHandler<K, V> wrappedHandler, BiConsumer<ConsumerRecord<K, V>, Throwable> errorConsumer) { requireNonNull(wrappedHandler, "wrappedHandler"); requireNonNull(errorConsumer, "errorConsumer"); this.wrappedHandler = wrappedHandler; this.errorConsumer = errorConsumer; } @Override public void handleRecord(ConsumerRecord<K, V> record) { try { wrappedHandler.handleRecord(record); } catch (Exception ex) { errorConsumer.accept(record, ex); } } }
48.102941
133
0.727301
f4042ad4380d3af44d011facf4bb5bcd0603144d
6,987
package com.ruoyi.weeklySchedule.backSystem.domain; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; /** * 项目周进度对象 weekly_project_scheduel * * @author mengdehu * @date 2020-03-10 */ public class WeeklyProjectScheduel extends BaseEntity { private static final long serialVersionUID = 1L; /** 主键 */ private Long id; /** 项目名称 */ @Excel(name = "项目名称") private String projectName; /** 主办团队 */ @Excel(name = "主办团队") private String hostTeam; /** 主办团队id */ @Excel(name = "主办团队id") private String hostTeamId; /** 项目经理 */ @Excel(name = "项目经理") private String projectManager; /** 项目经理id */ @Excel(name = "项目经理id") private String projectManagerId; /** 需求部门 */ @Excel(name = "需求部门") private String demandDept; /** 开始时间 */ @Excel(name = "开始时间") private String startTime; /** 计划投产时间 */ @Excel(name = "计划投产时间") private String plannedProductionTime; /** 当前阶段 */ @Excel(name = "当前阶段") private String currentGeneration; /** 阶段完成 */ @Excel(name = "阶段完成") private String finishedPhase; /** 本周完成内容 */ @Excel(name = "本周完成内容") private String finishThisWeek; /** 风险与困难 */ @Excel(name = "风险与困难") private String risksDifficulties; /** 备注 */ @Excel(name = "备注") private String remarks; /** 流水号 */ @Excel(name = "流水号") private String serialNo; /** 需求部门全称 */ @Excel(name = "需求部门全称") private String demandDeptFullName; public String getDemandDeptFullName() { return demandDeptFullName; } public void setDemandDeptFullName(String demandDeptFullName) { this.demandDeptFullName = demandDeptFullName; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getProjectName() { return projectName; } public void setHostTeam(String hostTeam) { this.hostTeam = hostTeam; } public String getHostTeam() { return hostTeam; } public void setHostTeamId(String hostTeamId) { this.hostTeamId = hostTeamId; } public String getHostTeamId() { return hostTeamId; } public void setProjectManager(String projectManager) { this.projectManager = projectManager; } public String getProjectManager() { return projectManager; } public void setProjectManagerId(String projectManagerId) { this.projectManagerId = projectManagerId; } public String getProjectManagerId() { return projectManagerId; } public void setDemandDept(String demandDept) { this.demandDept = demandDept; } public String getDemandDept() { return demandDept; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getStartTime() { return startTime; } public void setPlannedProductionTime(String plannedProductionTime) { this.plannedProductionTime = plannedProductionTime; } public String getPlannedProductionTime() { return plannedProductionTime; } public void setCurrentGeneration(String currentGeneration) { this.currentGeneration = currentGeneration; } public String getCurrentGeneration() { return currentGeneration; } public void setFinishedPhase(String finishedPhase) { this.finishedPhase = finishedPhase; } public String getFinishedPhase() { return finishedPhase; } public void setFinishThisWeek(String finishThisWeek) { this.finishThisWeek = finishThisWeek; } public String getFinishThisWeek() { return finishThisWeek; } public void setRisksDifficulties(String risksDifficulties) { this.risksDifficulties = risksDifficulties; } public String getRisksDifficulties() { return risksDifficulties; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getRemarks() { return remarks; } public void setSerialNo(String serialNo) { this.serialNo = serialNo; } public String getSerialNo() { return serialNo; } public WeeklyProjectScheduel() { } public WeeklyProjectScheduel( String projectName, String hostTeam, String hostTeamId, String projectManager, String projectManagerId, String demandDept, String startTime, String plannedProductionTime, String currentGeneration, String finishedPhase, String finishThisWeek, String risksDifficulties, String remarks, String serialNo,String demandDeptFullName) { this.projectName = projectName; this.hostTeam = hostTeam; this.hostTeamId = hostTeamId; this.projectManager = projectManager; this.projectManagerId = projectManagerId; this.demandDept = demandDept; this.startTime = startTime; this.plannedProductionTime = plannedProductionTime; this.currentGeneration = currentGeneration; this.finishedPhase = finishedPhase; this.finishThisWeek = finishThisWeek; this.risksDifficulties = risksDifficulties; this.remarks = remarks; this.serialNo = serialNo; this.demandDeptFullName = demandDeptFullName; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("risksDifficulties", getRisksDifficulties()) .append("finishThisWeek", getFinishThisWeek()) .append("finishedPhase", getFinishedPhase()) .append("currentGeneration", getCurrentGeneration()) .append("plannedProductionTime", getPlannedProductionTime()) .append("startTime", getStartTime()) .append("demandDept", getDemandDept()) .append("projectManagerId", getProjectManagerId()) .append("projectManager", getProjectManager()) .append("hostTeamId", getHostTeamId()) .append("hostTeam", getHostTeam()) .append("projectName", getProjectName()) .append("id", getId()) .append("updateTime", getUpdateTime()) .append("createTime", getCreateTime()) .append("remarks", getRemarks()) .append("serialNo", getSerialNo()) .append("demandDeptFullName", getDemandDeptFullName()) .toString(); } }
25.5
108
0.625877
7da4d2a7893718b30aa64ca0d995bcd004802eb0
751
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package FSAApp; /** * * @author 12084819 */ import java.awt.EventQueue; import javax.swing.JFrame; public class FSAApp { public static void main(String[] args) { EventQueue.invokeLater(() -> { FSAAppFrame frame = new FSAAppFrame(); frame.setTitle("FSA Rental Program - Welcome"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setVisible(true); frame.setResizable(false); }); } }
23.46875
80
0.599201
dde4474ea50d4c48f002bc51064cdcc7e3adb93d
1,195
// ============================================================================ // // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // 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.designer.core.ui.editor.connections; import org.talend.core.model.process.INodeConnector; import org.talend.core.model.utils.NodeUtil; import org.talend.designer.core.ui.editor.nodes.Node; import org.talend.designer.core.ui.editor.nodes.NodePart; /** * DOC Talend class global comment. Detailled comment */ public class NodeConnectorTool { private NodePart nodePart; public NodeConnectorTool(NodePart nodePart) { this.nodePart = nodePart; } public INodeConnector getConnector() { Node node = (Node) nodePart.getModel(); return NodeUtil.getValidConnector(node); } }
32.297297
88
0.6159
62feb5c9ddadfd6a19ca38a5180fe46b50f1e26f
1,054
package hu.kalee.multi.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Profile("security-embedded") @EnableWebSecurity public class InMemorySecurityConfig { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("user")).roles("USER").and().withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN", "USER"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
43.916667
203
0.804554
7aff179386bce7e9506f1d3c29e6f2b0d321a05e
359
package wallet; public class WalletElement { public String masterPrivateKey; public String privateKey; public String mnemonic; public WalletElement(String masterPrivateKey, String privateKey, String mnemonic) { this.masterPrivateKey = masterPrivateKey; this.privateKey = privateKey; this.mnemonic = mnemonic; } }
25.642857
87
0.718663
f698f41ef0830def2f42a316e3cf03ff81ae5c98
1,805
package org.springframework.netty.http.support; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * @author thinking * @version 1.0 * @since 2020-03-16 */ public class GenericsUtils { private static final Logger log = LoggerFactory.getLogger(GenericsUtils.class); public static Class<?> getInterfaceGenericType(Class<?> clazz, int indexInterface, int index) { Type[] genericInterfaces = clazz.getGenericInterfaces(); if (indexInterface >= genericInterfaces.length || indexInterface < 0) { throw new IllegalArgumentException("index: " + index + ", size of " + clazz.getSimpleName() + "'s interfaces: " + genericInterfaces.length); } Type genType = genericInterfaces[indexInterface]; if (!(genType instanceof ParameterizedType)) { //log.warn(clazz.getSimpleName() + "'s interfaces not ParameterizedType"); return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { throw new IllegalArgumentException("index: " + index + ", size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length); } Type type = params[index]; //public class ClickController implements HttpRequestHandler<Map<String,String>> if ((type instanceof ParameterizedType)) { Type rawType = ((ParameterizedType) type).getRawType(); return (Class<?>) rawType; } //public class ClickController implements HttpRequestHandler<ClickTracking> if ((type instanceof Class)) { return (Class<?>)type; } return Object.class; } }
37.604167
152
0.654848
e08ea4a5047ae02cbe24d062036fa2de5721b1ba
9,079
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.util; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import org.spongepowered.api.text.Text; import org.spongepowered.common.text.SpongeTexts; import java.util.List; import java.util.Optional; /** * A standard utility class for interacting and manipulating {@link ItemStack}s * and various other objects that interact with {@link NBTTagCompound}s. Also * provided is a static set of fields of the various "id"s of various bits of * data that may be stored on {@link ItemStack}s and/or {@link NBTTagCompound}s * used to store information. */ public class NbtDataUtil { // These are the various tag compound id's for getting to various places public static final String BLOCK_ENTITY_TAG = "BlockEntityTag"; public static final String BLOCK_ENTITY_ID = "id"; public static final String SIGN = "Sign"; public static final String TILE_ENTITY_POSITION_X = "x"; public static final String TILE_ENTITY_POSITION_Y = "y"; public static final String TILE_ENTITY_POSITION_Z = "z"; public static final String ITEM_ENCHANTMENT_LIST = "ench"; public static final String ITEM_ENCHANTMENT_ID = "id"; public static final String ITEM_ENCHANTMENT_LEVEL = "lvl"; public static final String ITEM_DISPLAY = "display"; public static final String ITEM_LORE = "Lore"; public static final String ITEM_BOOK_PAGES = "pages"; public static final String ITEM_BOOK_TITLE = "title"; public static final String ITEM_BOOK_AUTHOR = "author"; public static final String ITEM_BOOK_RESOLVED = "resolved"; // These are the NBT Tag byte id's that can be used in various places while manipulating compound tags public static final byte TAG_END = 0; public static final byte TAG_BYTE = 1; public static final byte TAG_SHORT = 2; public static final byte TAG_INT = 3; public static final byte TAG_LONG = 4; public static final byte TAG_FLOAT = 5; public static final byte TAG_DOUBLE = 6; public static final byte TAG_BYTE_ARRAY = 7; public static final byte TAG_STRING = 8; public static final byte TAG_LIST = 9; public static final byte TAG_COMPOUND = 10; public static final byte TAG_INT_ARRAY = 11; // These are Sponge's NBT tag keys public static final String SPONGE_TAG = "SpongeData"; public static final String CUSTOM_MANIPULATOR_TAG_LIST = "CustomManipulators"; // Compatibility tags for Forge public static final String FORGE_DATA_TAG = "ForgeData"; public static final String UUID_MOST = "UUIDMost"; public static final String UUID_LEAST = "UUIDLeast"; public static final String INVALID_TITLE = "invalid"; // These methods are provided as API like getters since the internal ItemStack does return nullable NBTTagCompounds. /** * Gets the main {@link NBTTagCompound} as an {@link Optional}. The issue * with {@link ItemStack}s is that the main compound is never instantiated * by default, so <code>null</code>s are permitted. Of course, another issue * is that {@link ItemStack#getTagCompound()} does not perform any * <code>null</code> checks, and therefor, may return <code>null</code> as * well. This method is provided to ensure that if the main compound does * not exist, none are created. To create a new compound regardless, * {@link #getOrCreateCompound(ItemStack)} is recommended. * * @param itemStack The itemstack to get the compound from * @return The main compound, if available */ public static Optional<NBTTagCompound> getItemCompound(ItemStack itemStack) { if (itemStack.hasTagCompound()) { return Optional.of(itemStack.getTagCompound()); } else { return Optional.empty(); } } /** * Gets or creates a new {@link NBTTagCompound} as the main compound of the * provided {@link ItemStack}. If there is one already created, this simply * returns the already created main compound. If there is no compound, * one is created and set back onto the {@link ItemStack}. * * @param itemStack The itemstack to get the main compound from * @return The pre-existing or already generated compound */ public static NBTTagCompound getOrCreateCompound(ItemStack itemStack) { if (!itemStack.hasTagCompound()) { itemStack.setTagCompound(new NBTTagCompound()); } return itemStack.getTagCompound(); } /** * Similar to {@link #getOrCreateCompound(ItemStack)}, this will check the * provided {@link NBTTagCompound} whether an internal compound is already * set and created by the provided {@link String} key. If there is no * {@link NBTTagCompound} already created, a new one is made and set for * the key. * * @param mainCompound The main compound to query for * @param key The key * @return The sub compound keyed by the provided string key */ public static NBTTagCompound getOrCreateSubCompound(NBTTagCompound mainCompound, final String key) { if (!mainCompound.hasKey(key, TAG_COMPOUND)) { mainCompound.setTag(key, new NBTTagCompound()); } return mainCompound.getCompoundTag(key); } public static NBTTagCompound filterSpongeCustomData(NBTTagCompound rootCompound) { if (rootCompound.hasKey(FORGE_DATA_TAG, TAG_COMPOUND)) { final NBTTagCompound forgeCompound = rootCompound.getCompoundTag(FORGE_DATA_TAG); if (forgeCompound.hasKey(SPONGE_TAG, TAG_COMPOUND)) { cleanseInnerCompound(forgeCompound, SPONGE_TAG); } } else if (rootCompound.hasKey(SPONGE_TAG, TAG_COMPOUND)) { cleanseInnerCompound(rootCompound, SPONGE_TAG); } return rootCompound; } private static void cleanseInnerCompound(NBTTagCompound compound, String innerCompound) { final NBTTagCompound inner = compound.getCompoundTag(innerCompound); if (inner.hasNoTags()) { compound.removeTag(innerCompound); } } public static List<Text> getLoreFromNBT(NBTTagCompound subCompound) { final NBTTagList list = subCompound.getTagList(ITEM_LORE, TAG_STRING); return SpongeTexts.fromLegacy(list); } public static void removeLoreFromNBT(ItemStack stack) { if(stack.getSubCompound(ITEM_DISPLAY, false) == null) { return; } stack.getSubCompound(ITEM_DISPLAY, false).removeTag(ITEM_LORE); } public static void setLoreToNBT(ItemStack stack, List<Text> lore) { final NBTTagList list = SpongeTexts.asLegacy(lore); stack.getSubCompound(ITEM_DISPLAY, true).setTag(ITEM_LORE, list); } public static List<Text> getPagesFromNBT(NBTTagCompound compound) { final NBTTagList list = compound.getTagList(ITEM_BOOK_PAGES, TAG_STRING); return SpongeTexts.fromLegacy(list); } public static void removePagesFromNBT(ItemStack stack) { final NBTTagList list = new NBTTagList(); if (!stack.hasTagCompound()) { return; } stack.getTagCompound().setTag(ITEM_BOOK_PAGES, list); } public static void setPagesToNBT(ItemStack stack, List<Text> pages){ final NBTTagList list = SpongeTexts.asLegacy(pages); final NBTTagCompound compound = getOrCreateCompound(stack); compound.setTag(ITEM_BOOK_PAGES, list); if (!compound.hasKey(ITEM_BOOK_TITLE)) { compound.setString(ITEM_BOOK_TITLE, INVALID_TITLE); } if (!compound.hasKey(ITEM_BOOK_AUTHOR)) { compound.setString(ITEM_BOOK_AUTHOR, INVALID_TITLE); } compound.setBoolean(ITEM_BOOK_RESOLVED, true); } }
43.440191
120
0.708007
59c027cbeb99038a518d6cf877bccb787a581a2b
740
package com.myproject.thymeleaf.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.myproject.thymeleaf.mapper.UserRoleMapper; import com.myproject.thymeleaf.model.entity.UserRole; import com.myproject.thymeleaf.service.UserRoleService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Slf4j @Service public class UserRoleServiceImpl implements UserRoleService { @Resource private UserRoleMapper userRoleMapper; @Override public List<UserRole> selectByUserRefId(String userRefId) { return userRoleMapper.selectList(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, userRefId)); } }
29.6
110
0.806757
8e26101c0abede14c127147cd8ccc0bbd76bae6d
305
package io.datatok.djobi.engine.stage.livecycle; import io.datatok.djobi.engine.check.CheckResult; import io.datatok.djobi.engine.stage.Stage; /** * @since v2.2.8 (rename on v3.1.0) */ public interface ActionPreChecker extends Action { CheckResult preCheck(final Stage stage) throws Exception; }
23.461538
61
0.763934
d8f9c0381879efa8050c5494ededd66927e3f64e
230
package test; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; public class UsedImport132980 { { new LinkedList(Collections.<Comparator<? super String>>emptyList()); } }
19.166667
76
0.717391
9fc1eb3c5176482d0216f5ce7614fe7f7dd3d9ef
6,882
package com.walmartlabs.concord.server.process.state; /*- * ***** * Concord * ----- * Copyright (C) 2017 - 2018 Walmart Inc. * ----- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ===== */ import com.walmartlabs.concord.common.IOUtils; import com.walmartlabs.concord.common.TemporaryPath; import com.walmartlabs.concord.sdk.Constants; import com.walmartlabs.concord.server.org.ResourceAccessLevel; import com.walmartlabs.concord.server.org.project.ProjectAccessManager; import com.walmartlabs.concord.server.process.OutVariablesUtils; import com.walmartlabs.concord.server.process.ProcessEntry; import com.walmartlabs.concord.server.process.ProcessEntry.ProcessCheckpointEntry; import com.walmartlabs.concord.server.process.queue.ProcessQueueDao; import com.walmartlabs.concord.server.sdk.ProcessKey; import com.walmartlabs.concord.server.security.Roles; import com.walmartlabs.concord.server.security.UserPrincipal; import org.apache.shiro.authz.UnauthorizedException; import org.immutables.value.Value; import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Named; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import static com.walmartlabs.concord.sdk.Constants.Files.CHECKPOINT_META_FILE_NAME; @Named public class ProcessCheckpointManager { private final ProcessCheckpointDao checkpointDao; private final ProcessQueueDao queueDao; private final ProcessStateManager stateManager; private final ProjectAccessManager projectAccessManager; @Inject protected ProcessCheckpointManager(ProcessCheckpointDao checkpointDao, ProcessQueueDao queueDao, ProcessStateManager stateManager, ProjectAccessManager projectAccessManager) { this.checkpointDao = checkpointDao; this.queueDao = queueDao; this.stateManager = stateManager; this.projectAccessManager = projectAccessManager; } public UUID getRecentCheckpointId(ProcessKey processKey, String checkpointName) { return checkpointDao.getRecentId(processKey, checkpointName); } /** * Import checkpoints data from the specified directory or a file. * * @param processKey process key * @param checkpointId process checkpoint ID * @param checkpointName process checkpoint name * @param data checkpoint data file */ public void importCheckpoint(ProcessKey processKey, UUID checkpointId, String checkpointName, Path data) { checkpointDao.importCheckpoint(processKey, checkpointId, checkpointName, data); } /** * Restore process to a saved checkpoint. */ public CheckpointInfo restoreCheckpoint(ProcessKey processKey, UUID checkpointId) { try (TemporaryPath checkpointArchive = IOUtils.tempFile("checkpoint", ".zip")) { String checkpointName = export(processKey, checkpointId, checkpointArchive.path()); if (checkpointName == null) { return null; } try (TemporaryPath extractedDir = IOUtils.tempDir("unzipped-checkpoint")) { IOUtils.unzip(checkpointArchive.path(), extractedDir.path()); // TODO: only for v1 runtime String eventName = readCheckpointEventName(extractedDir.path()); stateManager.tx(tx -> { stateManager.deleteDirectory(tx, processKey, Constants.Files.CONCORD_SYSTEM_DIR_NAME); stateManager.deleteDirectory(tx, processKey, Constants.Files.JOB_ATTACHMENTS_DIR_NAME); stateManager.importPath(tx, processKey, null, extractedDir.path(), (p, attrs) -> true); }); Map<String, Object> out = OutVariablesUtils.read(extractedDir.path().resolve(Constants.Files.JOB_ATTACHMENTS_DIR_NAME)); if (out.isEmpty()) { queueDao.removeMeta(processKey, "out"); } else { queueDao.updateMeta(processKey, Collections.singletonMap("out", out)); } return CheckpointInfo.of(checkpointName, eventName); } } catch (Exception e) { throw new RuntimeException("Restore checkpoint '" + checkpointId + "' error", e); } } /** * List checkpoints of a given instanceId */ public List<ProcessCheckpointEntry> list(ProcessKey processKey) { return checkpointDao.list(processKey); } public void assertProcessAccess(ProcessEntry e) { UserPrincipal p = UserPrincipal.assertCurrent(); UUID initiatorId = e.initiatorId(); if (p.getId().equals(initiatorId)) { // process owners should be able to restore the process from a checkpoint return; } if (Roles.isAdmin()) { return; } UUID projectId = e.projectId(); if (projectId != null) { projectAccessManager.assertAccess(projectId, ResourceAccessLevel.WRITER, false); return; } throw new UnauthorizedException("The current user (" + p.getUsername() + ") doesn't have " + "the necessary permissions to restore the process using a checkpoint: " + e.instanceId()); } @Value.Immutable public interface CheckpointInfo { String name(); @Nullable String eventName(); static CheckpointInfo of(String name, String eventName) { return ImmutableCheckpointInfo.builder() .name(name) .eventName(eventName) .build(); } } private String readCheckpointEventName(Path checkpointDir) throws IOException { Path checkpoint = checkpointDir.resolve(CHECKPOINT_META_FILE_NAME); if (!Files.exists(checkpoint)) { return null; } String checkpointName = new String(Files.readAllBytes(checkpoint)); Files.delete(checkpoint); return checkpointName; } private String export(ProcessKey processKey, UUID checkpointId, Path dest) { return checkpointDao.export(processKey, checkpointId, dest); } }
37.402174
136
0.671607
ac5a0de0dab8288976400c905ac577852536a8c5
1,467
package com.jspxcms.core.web.directive; import java.io.IOException; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import com.jspxcms.common.freemarker.Freemarkers; import com.jspxcms.core.service.SQLService; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; /** * SQLQueryDirective * * @author liufang * */ public class SQLQueryDirective implements TemplateDirectiveModel { public static final String SQL = "sql"; @SuppressWarnings({ "unchecked", "rawtypes" }) public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (loopVars.length < 1) { throw new TemplateModelException("Loop variable is required."); } if (body == null) { throw new RuntimeException("missing body"); } String sql = Freemarkers.getString(params, SQL); Integer maxRows = Freemarkers.getLimit(params); Integer startRow = Freemarkers.getOffset(params); List<?> list = service.query(sql, maxRows, startRow); loopVars[0] = env.getObjectWrapper().wrap(list); body.render(env.getOut()); } @Autowired private SQLService service; }
30.5625
76
0.751193
b4b44bba479f561debe842cc4a6353dbef0de1f4
2,347
package io.fotoapparat.hardware.v1; import android.hardware.Camera; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.Collections; import java.util.Set; import static io.fotoapparat.test.TestUtils.asSet; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) @SuppressWarnings("deprecation") public class CameraParametersDecoratorTest { @Mock Camera.Parameters parameters; @InjectMocks CameraParametersDecorator parametersProvider; @Test public void getSensorSensitivityValues_Available() throws Exception { // Given given(parameters.get(anyString())) .willReturn("400,600,1200"); // When Set<Integer> isoValues = parametersProvider.getSensorSensitivityValues(); // Then Assert.assertEquals( isoValues, asSet(400, 600, 1200) ); } @Test public void getSensorSensitivityValues_NotAvailable() throws Exception { // Given given(parameters.get(anyString())) .willReturn(null); // When Set<Integer> isoValues = parametersProvider.getSensorSensitivityValues(); // Then Assert.assertEquals( isoValues, Collections.<Integer>emptySet() ); } @Test public void setSensorSensitivityValues_Available() throws Exception { // Given given(parameters.get(anyString())) .willReturn("400"); // When parametersProvider.setSensorSensitivityValue(600); // Then verify(parameters, times(1)).set(anyString(), anyInt()); } @Test public void setSensorSensitivityValues_NotAvailable() throws Exception { // Given given(parameters.get(anyString())) .willReturn(null); // When parametersProvider.setSensorSensitivityValue(600); // Then verify(parameters, times(0)).set(anyString(), anyInt()); } }
26.370787
81
0.660844
1332a50ce0cead8dde61dde0391a0ea3e50261c1
540
package com.itacademy.java.oop.basics; public class Square { double length; double width; public Square() { } public Square(double length, double width) { this.length = length; this.width = width; } public double getLength() { return length; } public double getWidth() { return width; } @Override public String toString() { return "Square{" + "length=" + length + ", width=" + width + '}'; } }
17.419355
48
0.509259
10e43a026f9d75d660b156f7c7d613505bcfa9d3
3,016
package com.gra.local.controllers; import com.gra.local.persistence.EntityHelper; import com.gra.local.persistence.domain.VendorAccount; import com.gra.local.persistence.services.VendorAccountService; import com.gra.local.persistence.services.dtos.VendorAccountDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController @CrossOrigin @RequestMapping("/api/v1/account") public class VendorAccountController { private VendorAccountService vendorAccountService; @Autowired public VendorAccountController(VendorAccountService vendorAccountService) { this.vendorAccountService = vendorAccountService; } @PostMapping("/") public ResponseEntity<?> createAccount(@Valid @RequestBody VendorAccountDto accountDto) { VendorAccount createdVendorAccount = vendorAccountService.save(accountDto); return createdVendorAccount != null ? ResponseEntity.ok(EntityHelper.convertToAbstractDto(createdVendorAccount, VendorAccountDto.class)) : ResponseEntity.badRequest().build(); } @GetMapping("/") public ResponseEntity<?> getAllVerifiedVendors() { List<VendorAccount> verifiedVendors = vendorAccountService.findAllVendorsThatAreVerified(); return ResponseEntity.ok(verifiedVendors); } @PostMapping("/validate/{lookupNumber}") public ResponseEntity<?> validatePhoneNumber(@Valid @PathVariable("lookupNumber") String lookupNumber) { boolean validNumber = vendorAccountService.validatePhoneNumber(lookupNumber); return validNumber ? ResponseEntity.ok(validNumber) : ResponseEntity.badRequest().build(); } @PostMapping("/verifyAccount/{toNumber}") public ResponseEntity<Boolean> verifyAccount(@Valid @PathVariable("toNumber") String toNumber) { if (!vendorAccountService.checkIfVendorPhoneNumberIsVerified(toNumber)) { vendorAccountService.verifyAccount(toNumber); return ResponseEntity.ok().build(); } return ResponseEntity.badRequest().build(); } @GetMapping("/confirmCode/{code}") public ResponseEntity<Boolean> confirmCode(@Valid @PathVariable("code") String code) { boolean verifyCode = vendorAccountService.verifyCode(code); if (verifyCode) { return ResponseEntity.ok().build(); } return ResponseEntity.badRequest().build(); } @PutMapping("/password") public ResponseEntity<VendorAccount> addPassword(@Valid @RequestBody VendorAccount account) { VendorAccount existingVendorAccount = vendorAccountService.findByPhone(account.getPhone()); if (existingVendorAccount != null) { vendorAccountService.updatePassword(existingVendorAccount, account.getPassword()); return ResponseEntity.ok(existingVendorAccount); } return ResponseEntity.notFound().build(); } }
41.888889
183
0.744032
a5a80de4dca52bb007707335257c5446b32ee8ae
267
package dydeve.common.util; /** * @see com.netflix.hystrix.util.InternMap * Created by yuduy on 2017/8/17. */ public interface InternStorage<K, V>{ V interned(K key); int size(); interface ValueConstructor<K, V> { V create(K key); } }
14.833333
42
0.625468
979e26ee5e753313534215a4262cc1db81e94a07
113
package com.episode6.hackit.pausable; /** * */ public interface Pausable { void pause(); void resume(); }
11.3
37
0.654867
48dbb840f93c7238df434c7a7b0d53133bedf718
815
package com.miniprofiler.serialization; import java.io.IOException; import java.time.Instant; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; /** * Serialize java.time.Instant like .NET DateTime. */ public class InstantSerializer extends StdSerializer<Instant> { public InstantSerializer() { this(null); } public InstantSerializer(Class<Instant> t) { super(t); } public void serialize(Instant value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { jgen.writeString(String.format("/Date(%d)/", value.toEpochMilli())); } }
28.103448
89
0.743558
0751ba835e5604bebc8bf9ee5e8a0486b53232d3
2,023
/* * Kimberly M. Praxel * 10/20/16 * JsonWriter.java */ package edu.greenriver.it.fileio; import java.io.*; import org.json.simple.*; import org.json.simple.parser.JSONParser; import java.util.*; import edu.greenriver.it.products.*; public class JsonWriter implements Writer{ /** * This saves an object to as json object file into the data folder * * @param object * - a product object */ @SuppressWarnings("unchecked") public void saveObject(Product object){ JSONObject productObject = new JSONObject(); productObject.put("name", object.getName()); productObject.put("price", object.getPrice()); JSONArray keywords = new JSONArray(); for(String keyword: object.getKeywords()){ keywords.add(keyword); } productObject.put("keywords", keywords); try{ FileWriter fileWriter = new FileWriter(getFilename(object.getName())); fileWriter.write(productObject.toJSONString()); fileWriter.flush(); fileWriter.close(); }catch(IOException e){ e.printStackTrace(); } } /** * This loads a json object file from the data folder * * @param name * - name of file * @return product - from file */ public Product loadObject(String name){ JSONParser parser = new JSONParser(); try{ Object object = parser.parse(new FileReader(getFilename(name))); JSONObject productObject = (JSONObject)object; String productsName = (String)productObject.get("name"); double productsPrice = (Double)productObject.get("price"); JSONArray keywords = (JSONArray)productObject.get("keywords"); String [] productsKeywords = new String[keywords.size()]; Iterator<String> iterator = keywords.iterator(); int i = 0; while(iterator.hasNext()){ productsKeywords[i] = (String)(iterator.next()); i++; } return new Product(productsName, productsPrice, productsKeywords); }catch(Exception e){ e.printStackTrace(); } return null; } private String getFilename(String name){ return "data/" + name + ".json"; } }
24.670732
73
0.687593
075c67cd4e0a8ade45cba38976958b086c6419be
831
package com.ll.demo.view; import android.content.Context; import android.support.v7.widget.AppCompatCheckBox; import android.util.AttributeSet; import com.ll.chart.compat.FontConfig; /** * 自定义字体库的CheckBox */ public class FontCheckBox extends AppCompatCheckBox { public FontCheckBox(Context context) { super(context); initFont(); } public FontCheckBox(Context context, AttributeSet attrs) { super(context, attrs); initFont(); } public FontCheckBox(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initFont(); } public void initFont() { if (null != getTypeface() && getTypeface().isBold()) { this.setTypeface(FontConfig.boldTypeFace); } else { this.setTypeface(FontConfig.typeFace); } this.postInvalidate(); } }
22.459459
78
0.705174
21d33b43ee6ddbecb765265e9082cee260a8cdc6
833
package com.qaprosoft.carina.demo.gui.pages; import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement; import com.qaprosoft.carina.core.gui.AbstractPage; import com.qaprosoft.carina.demo.gui.components.Filter; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.FindBy; public class CatalogPage extends AbstractPage { private final String comparePageUrl = "https://xiaomi-store.by/catalog"; @FindBy(xpath = "//button[@class='filter-btn']") private ExtendedWebElement filter; public CatalogPage(WebDriver driver) { super(driver); setUiLoadedMarker(filter); setPageAbsoluteURL(comparePageUrl); } public Filter selectFilters() { assertElementPresent(filter); filter.click(); return new Filter(driver); } }
28.724138
83
0.732293
5ae3d31658f58f744ce0a3fbebcbb651bba393bf
2,482
package cn.iocoder.mall.order.biz.bo.order; import lombok.Data; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.Date; import java.util.List; /** * 订单退货 info * * @author Sin * @time 2019-04-27 10:19 */ @Data @Accessors(chain = true) public class OrderReturnInfoBO implements Serializable { /** * 退货信息 */ private ReturnInfo returnInfo; /** * 订单 item */ private List<OrderItem> orderItems; /** * 最后一个物流信息/最新物流信息 */ private OrderLastLogisticsInfoBO lastLogisticsInfo; @Data @Accessors(chain = true) public static class OrderItem { /** * 商品编号 */ private Integer skuId; /** * 商品名称 */ private String skuName; /** * 商品图片 */ private String skuImage; /** * 数量 */ private Integer quantity; /** * 最终总金额,单位:分。 */ private Integer presentTotal; } @Data @Accessors(chain = true) public static class ReturnInfo { /** * 编号自动增长 */ private Integer id; /** * 服务号 */ private String serviceNumber; /** * 订单编号 */ private Integer orderId; /** * 订单号 (保存一个冗余) */ private String orderNo; /** * 物流id */ private Integer orderLogisticsId; /// /// 退货原因 /** * 退货金额 */ private Integer refundPrice; /** * 退货原因(字典值) */ private Integer reason; /** * 问题描述 */ private String describe; /// /// 时间信息 /** * 同意时间 */ private Date approvalTime; /** * 物流时间(填写物流单号时间) */ private Date logisticsTime; /** * 收货时间 */ private Date receiverTime; /** * 成交时间(确认时间) */ private Date closingTime; /** * 退款类型 * * - 1、退货退款 * - 2、退款 */ private Integer serviceType; /** * 退款类型 转换值 */ private String serviceTypeText; /** * 状态 * * - 1、退货申请 * - 2、申请成功 * - 3、申请失败 * - 4、退货中 * - 5、退货成功 */ private Integer status; } }
17.478873
56
0.431507
b0ca7a1b1d9eaa5446e761ede57771a06736fe40
877
package authoring.resourceutility; import authoring.VoogaScene; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; /** * An abstract class inherited by ImagePreviewer and AudioPreviewer to allow * users to preview resources * @author DoovalSalad * */ public abstract class Previewer { /** * Protected instance variables */ protected VoogaFile file; protected Group group; protected Stage stage; /** * Constructs the previewer using the template method, allowing the * subclasses to specify how to preview the item * @param file */ public Previewer(VoogaFile file) { this.file = file; group = new Group(); Scene scene = new VoogaScene(group); stage = new Stage(); preview(); stage.setScene(scene); stage.show(); } /** * Specifies how the previewing should be done */ abstract void preview(); }
19.931818
76
0.713797
2299022caf3c82fd0016f7d55f9cf4ab7dfed97f
1,432
package classify.twopointers; /** * @author yutiantang * @create 2021/3/28 5:39 PM */ public class RemoveDuplicatesFromSortedArrayII { /** * 1ms 80.57% * 38.6MB 61.12% * @param nums * @return */ public int removeDuplicates(int[] nums) { if (nums.length < 3) { return nums.length; } int slow = 0, fast = 1, slowCount = 1; while (fast < nums.length) { if (nums[fast] == nums[slow]) { if (slowCount == 2) { // 当slow重复了两次 但是fast还是与slow相同时,则需要寻找到下一位不同的值 while (fast < nums.length && nums[fast] == nums[slow]) { fast++; } if (fast == nums.length) { return slow + 1; } slowCount = 0; } } else { slowCount = 0; } slowCount++; nums[++slow] = nums[fast++]; } return slow + 1; } /** * 0ms 100.00% * 39.8MB 47.59% * @param nums * @return */ public int removeDuplicates2(int[] nums) { int slow = 0, fast = 1; while (fast < nums.length) { if (nums[fast] != nums[slow]) { nums[++slow] = nums[fast]; } fast++; } return ++slow; } }
23.47541
76
0.403631
9a2f3f0a1ca98beee6c28e8fac7385f03f413f67
1,225
package it.polimi.ingsw.PSP48.networkMessagesToClient; import it.polimi.ingsw.PSP48.DivinitiesWithDescription; import it.polimi.ingsw.PSP48.ViewInterface; import java.util.ArrayList; /** * Network message used to request the challenger to choose the available divinities in the game. * It contains the divinities available for the specific type of game in progress; */ public class ChallengerDivinitiesSelectionRequest extends NetworkMessagesToClient { private ArrayList<DivinitiesWithDescription> div; private int playerNumber; /** * Invokes the request of challenger's divinities selection * * @param v the view interface where the method must be invoked */ @Override public void doAction(ViewInterface v) { v.requestChallengerDivinitiesSelection(div, playerNumber); } /** * Initializes the network message * * @param div the available divinities * @param playerNumber the number of players */ public ChallengerDivinitiesSelectionRequest(ArrayList<DivinitiesWithDescription> div, int playerNumber) { this.div = (ArrayList<DivinitiesWithDescription>) div.clone(); this.playerNumber = playerNumber; } }
33.108108
109
0.733878
8ac730e8a39c95a186bb822b3e2f7348b77a7295
359
package com.example.gmall.wms.dao; import com.example.gmall.wms.entity.ShAreaEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 全国省市区信息 * * @author mousse * @email 958860184@qq.com * @date 2020-09-06 14:12:08 */ @Mapper public interface ShAreaDao extends BaseMapper<ShAreaEntity> { }
19.944444
61
0.754875
d2071465ac99b5bcb79e2e00f82c6c5f27874116
4,048
/* Copyright (C) 2010 by * * Cam-Tu Nguyen * ncamtu@ecei.tohoku.ac.jp or ncamtu@gmail.com * * Xuan-Hieu Phan * pxhieu@gmail.com * * College of Technology, Vietnamese University, Hanoi * Graduate School of Information Sciences, Tohoku University * * JVnTextPro-v.2.0 is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * JVnTextPro-v.2.0 is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JVnTextPro-v.2.0); if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ package jvnsegmenter; import java.io.File; import java.util.Vector; import org.w3c.dom.Element; import jflexcrf.Labeling; import jvntextpro.data.DataReader; import jvntextpro.data.DataWriter; import jvntextpro.data.TaggingData; // TODO: Auto-generated Javadoc /** * The Class CRFSegmenter. */ public class CRFSegmenter { /** The reader. */ DataReader reader = new WordDataReader(); /** The writer. */ DataWriter writer = new WordDataWriter(); /** The data tagger. */ TaggingData dataTagger = new TaggingData(); /** The labeling. */ Labeling labeling = null; /** * Instantiates a new cRF segmenter. * * @param modelDir the model dir */ public CRFSegmenter(String modelDir){ init(modelDir); } /** * Instantiates a new cRF segmenter. */ public CRFSegmenter() { //do nothing until now } /** * Inits the. * * @param modelDir the model dir */ public void init(String modelDir) { //Read feature template file String templateFile = modelDir + File.separator + "featuretemplate.xml"; Vector<Element> nodes = BasicContextGenerator.readFeatureNodes(templateFile); for (int i = 0; i < nodes.size(); ++i){ Element node = nodes.get(i); String cpType = node.getAttribute("value"); BasicContextGenerator contextGen = null; if (cpType.equals("Conjunction")){ contextGen = new ConjunctionContextGenerator(node); } else if (cpType.equals("Lexicon")){ contextGen = new LexiconContextGenerator(node); LexiconContextGenerator.loadVietnameseDict(modelDir + File.separator + "VNDic_UTF-8.txt"); LexiconContextGenerator.loadViLocationList(modelDir + File.separator + "vnlocations.txt"); LexiconContextGenerator.loadViPersonalNames(modelDir + File.separator + "vnpernames.txt"); } else if (cpType.equals("Regex")){ contextGen = new RegexContextGenerator(node); } else if (cpType.equals("SyllableFeature")){ contextGen = new SyllableContextGenerator(node); } else if (cpType.equals("ViSyllableFeature")){ contextGen = new VietnameseContextGenerator(node); } if (contextGen != null) dataTagger.addContextGenerator(contextGen); } //create context generators labeling = new Labeling(modelDir, dataTagger, reader, writer); } /** * Segmenting. * * @param instr the instr * @return the string */ public String segmenting(String instr) { return labeling.strLabeling(instr); } /** * Segmenting. * * @param file the file * @return the string */ public String segmenting(File file) { return labeling.strLabeling(file); } /** * Sets the data reader. * * @param reader the new data reader */ public void setDataReader(DataReader reader){ this.reader = reader; } /** * Sets the data writer. * * @param writer the new data writer */ public void setDataWriter(DataWriter writer){ this.writer = writer; } }
26.285714
95
0.673666