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
872cec5be4430ae9ad76c26a265c38bcb413900b
299
package se.kth.iv1201.group4.recruitment.util.error; /** * This exception is thrown if a SSN trying to be used already * exists. * * @author Filip Garamvölgyi */ public class SSNAlreadyExistsException extends RuntimeException { public SSNAlreadyExistsException(String msg){super(msg);} }
24.916667
65
0.759197
5e83e881907e5007b89dc734ee7068419f6a8a1c
2,667
package carpet.mixins; import carpet.CarpetSettings; import carpet.fakes.ServerWorldInterface; import carpet.script.CarpetEventServer; import net.minecraft.entity.Entity; import net.minecraft.entity.LightningEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.profiler.Profiler; import net.minecraft.world.chunk.WorldChunk; import net.minecraft.world.level.ServerWorldProperties; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import static carpet.script.CarpetEventServer.Event.ENTITY_LOAD; import static carpet.script.CarpetEventServer.Event.LIGHTNING; @Mixin(ServerWorld.class) public class ServerWorld_scarpetMixin implements ServerWorldInterface { @Inject(method = "tickChunk", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( value = "INVOKE", target = "Lnet/minecraft/server/world/ServerWorld;spawnEntity(Lnet/minecraft/entity/Entity;)Z", shift = At.Shift.BEFORE, ordinal = 1 )) private void onNaturalLightinig(WorldChunk chunk, int randomTickSpeed, CallbackInfo ci, //ChunkPos chunkPos, boolean bl, int i, int j, Profiler profiler, BlockPos blockPos, boolean bl2) ChunkPos chunkPos, boolean bl, int i, int j, Profiler profiler, BlockPos blockPos, boolean bl2, LightningEntity lightningEntity) { if (LIGHTNING.isNeeded()) LIGHTNING.onWorldEventFlag((ServerWorld) (Object)this, blockPos, bl2?1:0); } @Inject(method = "loadEntityUnchecked", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/world/ServerChunkManager;loadEntity(Lnet/minecraft/entity/Entity;)V" )) private void onEntityAddedToWorld(Entity entity, CallbackInfo ci) { CarpetEventServer.Event event = ENTITY_LOAD.get(entity.getType()); if (event != null) { if (event.isNeeded()) { event.onEntityAction(entity); } } else { CarpetSettings.LOG.error("Failed to handle entity "+entity.getType().getTranslationKey()); } } @Shadow private ServerWorldProperties worldProperties; public ServerWorldProperties getWorldPropertiesCM(){ return worldProperties; } }
40.409091
164
0.706787
8dd16953433b88bc800ccea4d4dfb5100de15f45
1,426
/* * Copyright 2016 Futurice GmbH * * 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.futurice.freesound.app; import com.futurice.freesound.feature.analytics.AnalyticsModule; import com.futurice.freesound.feature.common.scheduling.SchedulingModule; import com.futurice.freesound.feature.images.ImagesModule; import com.futurice.freesound.feature.logging.LoggingModule; import com.futurice.freesound.feature.user.UserModule; import com.futurice.freesound.inject.app.BaseApplicationModule; import com.futurice.freesound.network.api.ApiModule; import dagger.Module; @Module(includes = {BaseApplicationModule.class, ApiModule.class, ImagesModule.class, SchedulingModule.class, AnalyticsModule.class, LoggingModule.class, UserModule.class}) final class FreesoundApplicationModule { }
37.526316
75
0.732118
bce1126f1c199c154e9faa22bdd0a0a8f92f6595
796
package vehicle; /** * * @author Polis */ public class Car extends Vehicle { private int doors; public Car() {} public Car(int doors) { this.doors = doors; } public Car(String owner, String licensePlate, int buildYear, Engine eng, int doors) { super(owner, licensePlate, buildYear, eng); this.doors = doors; } public int getDoors() { return doors; } public void setDoors(int doors) { this.doors = doors; } @Override public void Drive() { System.out.println("You need a car driving license dear " + super.getOwner()); } @Override public String toString() { String s = super.toString(); s+=("Doors: " + getDoors()); return s; } }
18.952381
89
0.55402
90941a8bb6e52f2e003d8bdfed15d83feef92ef9
5,595
package pl.softmate.xsd.dbunit.ant; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.dialect.Dialect; import org.junit.Assert; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.junit.After; public abstract class BaseHibernatePoweredTest { public DbUnitSchemaGenerator generator; public Path schemaFilePath = Paths.get( System.getProperty( "java.io.tmpdir" ), "schema.xsd" ); public Path updateSchemaFilePath = Paths.get( System.getProperty( "java.io.tmpdir" ), "updateSchema.xsd" ); public DocumentBuilder builder; public XPath xpath; final String sampletableXpath = "//*[local-name()='element' and translate(@name,'ABELMPST', 'abelmpst')='sampletable']"; public BaseHibernatePoweredTest() { super(); } public void initDbUnitSchemaGenerator( String driverName, String url, Class<? extends Dialect> clazz ) throws Exception { final Properties properties = new Properties(); properties.load( this.getClass().getResourceAsStream( "/db.props" ) ); generator = new DbUnitSchemaGenerator(); generator.setDriverName( driverName ); generator.setUrl( url + properties.getProperty( "db" ) ); generator.setUser( properties.getProperty( "user" ) ); generator.setPassword( properties.getProperty( "pass" ) ); generator.setSchemaName( "public" ); generator.setOutputFolder( System.getProperty( "java.io.tmpdir" ) ); initDbSchemaByHibernate( clazz ); initPArserAndXPath(); } public void initDbSchemaByHibernate( Class<? extends Dialect> clazz ) throws Exception { //@formatter:off Configuration cfg = new Configuration() .addAnnotatedClass( SampleTable.class ) .setProperty( "hibernate.hbm2ddl.auto", "create" ) .setProperty( "hibernate.connection.pool_size", "1" ) .setProperty( "hibernate.current_session_context_class", "thread" ) .setProperty( "hibernate.cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider" ) .setProperty( "hibernate.show_sql", "true" ) .setProperty( "hibernate.connection.driver_class", generator.getDriverName() ) .setProperty( "hibernate.connection.url", generator.getUrl()) .setProperty( "hibernate.connection.username", generator.getUser() ) .setProperty( "hibernate.connection.password", generator.getPassword() ) .setProperty( "hibernate.dialect", clazz.getName() ); //@formatter:on StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( cfg.getProperties() ).build(); SessionFactory sf = cfg.buildSessionFactory( serviceRegistry ); sf.close(); } public void initPArserAndXPath() throws Exception { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware( true ); builder = domFactory.newDocumentBuilder(); xpath = XPathFactory.newInstance().newXPath(); } public String getAttr( String name, String type, String use ) { return "[local-name()='attribute' and @name='" + name + "' and @type='" + type + "' and @use='" + use + "']"; } public void assertXPath( Document doc, String _xpath ) throws Exception { XPathExpression c1 = xpath.compile( _xpath ); Object result = c1.evaluate( doc, XPathConstants.NODESET ); NodeList nodes = (NodeList) result; Assert.assertEquals( "XPath :: " + _xpath, 1, nodes.getLength() ); } public void checkBaseAssertions() throws SAXException, IOException, Exception { assertTrue( schemaFilePath.toFile().exists() ); Document schemaDoc = builder.parse( schemaFilePath.toFile() ); assertXPath( schemaDoc, sampletableXpath + "//*" + getAttr( "c1", "xs:long", "required" ) ); assertXPath( schemaDoc, sampletableXpath + "//*" + getAttr( "c2", "xs:int", "required" ) ); assertXPath( schemaDoc, sampletableXpath + "//*" + getAttr( "c3", "varchar_100", "optional" ) ); assertXPath( schemaDoc, sampletableXpath + "//*" + getAttr( "c4", "decimal_5_2", "optional" ) ); assertTrue( updateSchemaFilePath.toFile().exists() ); Document updateSchemaDoc = builder.parse( updateSchemaFilePath.toFile() ); assertXPath( updateSchemaDoc, sampletableXpath + "//*" + getAttr( "c1", "xs:long", "required" ) ); assertXPath( updateSchemaDoc, sampletableXpath + "//*" + getAttr( "c2", "xs:int", "optional" ) ); assertXPath( updateSchemaDoc, sampletableXpath + "//*" + getAttr( "c3", "varchar_100", "optional" ) ); assertXPath( updateSchemaDoc, sampletableXpath + "//*" + getAttr( "c4", "decimal_5_2", "optional" ) ); } @After public void tearDown() throws IOException { Files.deleteIfExists(schemaFilePath); Files.deleteIfExists(updateSchemaFilePath); } }
46.239669
132
0.686506
1a3f9e9a2f7bff80c2083c41492b5a12dd1c068a
8,501
/** * Copyright (C) 2011 Brian Ferris <bdferris@onebusaway.org> * Copyright (C) 2011 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onebusaway.transit_data_federation.impl.beans; import org.apache.lucene.queryparser.classic.ParseException; import org.onebusaway.container.cache.Cacheable; import org.onebusaway.container.refresh.Refreshable; import org.onebusaway.exceptions.InvalidArgumentServiceException; import org.onebusaway.exceptions.NoSuchAgencyServiceException; import org.onebusaway.exceptions.ServiceException; import org.onebusaway.geospatial.model.CoordinateBounds; import org.onebusaway.gtfs.model.AgencyAndId; import org.onebusaway.transit_data.model.ListBean; import org.onebusaway.transit_data.model.RouteBean; import org.onebusaway.transit_data.model.RoutesBean; import org.onebusaway.transit_data.model.SearchQueryBean; import org.onebusaway.transit_data.model.StopBean; import org.onebusaway.transit_data_federation.impl.RefreshableResources; import org.onebusaway.transit_data_federation.model.SearchResult; import org.onebusaway.transit_data_federation.services.AgencyAndIdLibrary; import org.onebusaway.transit_data_federation.services.RouteCollectionSearchService; import org.onebusaway.transit_data_federation.services.RouteService; import org.onebusaway.transit_data_federation.services.beans.GeospatialBeanService; import org.onebusaway.transit_data_federation.services.beans.RouteBeanService; import org.onebusaway.transit_data_federation.services.beans.RoutesBeanService; import org.onebusaway.transit_data_federation.services.beans.StopBeanService; import org.onebusaway.transit_data_federation.services.transit_graph.AgencyEntry; import org.onebusaway.transit_data_federation.services.transit_graph.RouteCollectionEntry; import org.onebusaway.transit_data_federation.services.transit_graph.StopEntry; import org.onebusaway.transit_data_federation.services.transit_graph.TransitGraphDao; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.index.ItemVisitor; import com.vividsolutions.jts.index.strtree.STRtree; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.PostConstruct; @Component class RoutesBeanServiceImpl implements RoutesBeanService { private static Logger _log = LoggerFactory.getLogger(RoutesBeanServiceImpl.class); @Autowired private RouteService _routeService; @Autowired private RouteCollectionSearchService _searchService; @Autowired private GeospatialBeanService _whereGeospatialService; @Autowired private RouteBeanService _routeBeanService; @Autowired private StopBeanService _stopService; @Autowired private TransitGraphDao _graphDao; private Map<AgencyAndId, STRtree> _stopTreesByRouteId = new HashMap<AgencyAndId, STRtree>(); @Refreshable(dependsOn = { RefreshableResources.NARRATIVE_DATA }) @PostConstruct public void setup() { _stopTreesByRouteId.clear(); for (StopEntry stop : _graphDao.getAllStops()) { Set<AgencyAndId> routeIds = _routeService.getRouteCollectionIdsForStop(stop.getId()); for (AgencyAndId routeId : routeIds) { STRtree tree = _stopTreesByRouteId.get(routeId); if (tree == null) { tree = new STRtree(); _stopTreesByRouteId.put(routeId, tree); } double x = stop.getStopLon(); double y = stop.getStopLat(); Envelope env = new Envelope(x, x, y, y); tree.insert(env, routeId); } } for (STRtree tree : _stopTreesByRouteId.values()) tree.build(); } @Override public RoutesBean getRoutesForQuery(SearchQueryBean query) throws ServiceException { if (query.getQuery() != null) return getRoutesWithRouteNameQuery(query); else return getRoutesWithoutRouteNameQuery(query); } @Cacheable @Override public ListBean<String> getRouteIdsForAgencyId(String agencyId) { AgencyEntry agency = _graphDao.getAgencyForId(agencyId); if (agency == null) throw new NoSuchAgencyServiceException(agencyId); List<String> ids = new ArrayList<String>(); for (RouteCollectionEntry routeCollection : agency.getRouteCollections()) { AgencyAndId id = routeCollection.getId(); ids.add(AgencyAndIdLibrary.convertToString(id)); } return new ListBean<String>(ids, false); } @Cacheable @Override public ListBean<RouteBean> getRoutesForAgencyId(String agencyId) { AgencyEntry agency = _graphDao.getAgencyForId(agencyId); if (agency == null) throw new NoSuchAgencyServiceException(agencyId); List<RouteBean> routes = new ArrayList<RouteBean>(); for (RouteCollectionEntry routeCollection : agency.getRouteCollections()) { AgencyAndId routeId = routeCollection.getId(); RouteBean route = _routeBeanService.getRouteForId(routeId); routes.add(route); } return new ListBean<RouteBean>(routes, false); } /**** * Private Methods ****/ private RoutesBean getRoutesWithoutRouteNameQuery(SearchQueryBean query) { CoordinateBounds bounds = query.getBounds(); List<AgencyAndId> stops = _whereGeospatialService.getStopsByBounds(bounds); Set<RouteBean> routes = new HashSet<RouteBean>(); for (AgencyAndId stopId : stops) { StopBean stop = _stopService.getStopForId(stopId, null); routes.addAll(stop.getRoutes()); } List<RouteBean> routeBeans = new ArrayList<RouteBean>(routes); boolean limitExceeded = BeanServiceSupport.checkLimitExceeded(routeBeans, query.getMaxCount()); return constructResult(routeBeans, limitExceeded); } private RoutesBean getRoutesWithRouteNameQuery(SearchQueryBean query) throws ServiceException { SearchResult<AgencyAndId> result = searchForRoutes(query); List<RouteBean> routeBeans = new ArrayList<RouteBean>(); CoordinateBounds bounds = query.getBounds(); for (AgencyAndId id : result.getResults()) { STRtree tree = _stopTreesByRouteId.get(id); if (tree == null) { _log.warn("stop tree not found for routeId=" + id); continue; } Envelope env = new Envelope(bounds.getMinLon(), bounds.getMaxLon(), bounds.getMinLat(), bounds.getMaxLat()); HasItemsVisitor v = new HasItemsVisitor(); tree.query(env, v); if (v.hasItems()) { RouteBean routeBean = _routeBeanService.getRouteForId(id); routeBeans.add(routeBean); } } boolean limitExceeded = BeanServiceSupport.checkLimitExceeded(routeBeans, query.getMaxCount()); return constructResult(routeBeans, limitExceeded); } private SearchResult<AgencyAndId> searchForRoutes(SearchQueryBean query) throws ServiceException, InvalidArgumentServiceException { try { return _searchService.searchForRoutesByName(query.getQuery(), query.getMaxCount() + 1, query.getMinScoreToKeep()); } catch (IOException e) { throw new ServiceException(); } catch (ParseException e) { throw new InvalidArgumentServiceException("query", "queryParseError"); } } private RoutesBean constructResult(List<RouteBean> routeBeans, boolean limitExceeded) { Collections.sort(routeBeans, new RouteBeanIdComparator()); RoutesBean result = new RoutesBean(); result.setRoutes(routeBeans); result.setLimitExceeded(limitExceeded); return result; } private static class HasItemsVisitor implements ItemVisitor { private boolean _hasItems = false; public boolean hasItems() { return _hasItems; } @Override public void visitItem(Object arg0) { _hasItems = true; } } }
34.417004
94
0.753558
7d06cf1b31b954c038b390223818d11a1c3e857b
1,220
package com.example.kidroca.mylittlequizapp.authentication.models; import org.json.JSONException; import org.json.JSONObject; /** * Created by kidroca on 16.1.2016 г.. */ public class Token { public static final String FIELD_ACCESS_TOKEN = "access_token"; public static final String FIELD_EXPIRES_IN = "expires_in"; public static final String FIELD_TOKEN_TYPE = "token_type"; public static final String FIELD_USERNAME = "userName"; private String type; private String access; private String userName; public Token(String type, String access, String userName) { this.type = type; this.access = access; this.userName = userName; } public Token(JSONObject jObj) throws JSONException { this.type = jObj.getString(FIELD_TOKEN_TYPE); this.access = jObj.getString(FIELD_ACCESS_TOKEN); this.userName = jObj.getString(FIELD_USERNAME); } public String getType() { return type; } public String getAccess() { return access; } public String getUserName() { return userName; } @Override public String toString() { return String.format("%s %s", type, access); } }
25.416667
67
0.668852
93cc41ced5a9651ebfbcba6a97b1af42898445b4
1,291
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands.autonomous; import frc.robot.subsystems.Shooter; import frc.robot.subsystems.Climber; import frc.robot.subsystems.Drivetrain; import frc.robot.subsystems.Index; import frc.robot.subsystems.Intake; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; /** An example command that uses an example subsystem. */ public class TwoBallAuto extends SequentialCommandGroup { public TwoBallAuto(Drivetrain drivetrain, Shooter shooter, Intake intake, Index index, Climber climber) { super( new InstantCommand(index::startWithOneBall, index), new DelayedIndexConditional(index, 2) .alongWith(new DriveToPickup(drivetrain, shooter, climber, intake, 3.5, -0.15).withInterrupt(index::getIntakeSensor)), new InstantCommand(climber::raiseArms, climber), new PickupBalls(intake, 1), new AutoHorizontalAim(drivetrain, 1), new AutonomousShootConditional(shooter, index, 0, 1850).alongWith(new IndexShootingUpperConditional(index, 0)) ); } }
44.517241
128
0.757552
7a10c4ed4cd9638e25f11ff2fc31b11068730f06
2,789
package com.spoonacular.client.model; import com.spoonacular.client.model.InlineResponse20010Ingredients; import java.math.BigDecimal; import java.util.*; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; @ApiModel(description = "") public class InlineResponse20010 { @SerializedName("ingredients") private List<InlineResponse20010Ingredients> ingredients = null; @SerializedName("totalCost") private BigDecimal totalCost = null; @SerializedName("totalCostPerServing") private BigDecimal totalCostPerServing = null; /** **/ @ApiModelProperty(required = true, value = "") public List<InlineResponse20010Ingredients> getIngredients() { return ingredients; } public void setIngredients(List<InlineResponse20010Ingredients> ingredients) { this.ingredients = ingredients; } /** **/ @ApiModelProperty(required = true, value = "") public BigDecimal getTotalCost() { return totalCost; } public void setTotalCost(BigDecimal totalCost) { this.totalCost = totalCost; } /** **/ @ApiModelProperty(required = true, value = "") public BigDecimal getTotalCostPerServing() { return totalCostPerServing; } public void setTotalCostPerServing(BigDecimal totalCostPerServing) { this.totalCostPerServing = totalCostPerServing; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InlineResponse20010 inlineResponse20010 = (InlineResponse20010) o; return (this.ingredients == null ? inlineResponse20010.ingredients == null : this.ingredients.equals(inlineResponse20010.ingredients)) && (this.totalCost == null ? inlineResponse20010.totalCost == null : this.totalCost.equals(inlineResponse20010.totalCost)) && (this.totalCostPerServing == null ? inlineResponse20010.totalCostPerServing == null : this.totalCostPerServing.equals(inlineResponse20010.totalCostPerServing)); } @Override public int hashCode() { int result = 17; result = 31 * result + (this.ingredients == null ? 0: this.ingredients.hashCode()); result = 31 * result + (this.totalCost == null ? 0: this.totalCost.hashCode()); result = 31 * result + (this.totalCostPerServing == null ? 0: this.totalCostPerServing.hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse20010 {\n"); sb.append(" ingredients: ").append(ingredients).append("\n"); sb.append(" totalCost: ").append(totalCost).append("\n"); sb.append(" totalCostPerServing: ").append(totalCostPerServing).append("\n"); sb.append("}\n"); return sb.toString(); } }
32.057471
168
0.705988
ceb1d0959972866c967d52e0e09054b22a7e13dd
1,051
package edu.buffalo.rtdroid.ci; import android.content.Context; import android.content.Intent; import edu.buffalo.rtdroid.content.RealtimeIntent; import edu.buffalo.rtdroid.content.RealtimeReceiver; import java.nio.ByteBuffer; public class ResultReceiver extends RealtimeReceiver { private ByteBuffer bb = null; private int count = 0; public ResultReceiver() { } @Override public void onReceive(Context context, Intent intent) { long end = System.nanoTime(); bb = ((RealtimeIntent)intent).getByteBuffer(); bb.flip(); //System.out.println("pos"+bb.position()+", limit:" + bb.limit()); for( int i=0; i<ProcessingService.NUM_CHANNELS; i++ ){ bb.getDouble(); } long[] time = new long[4]; for( int i=0; i<4; i++){ time[i] = bb.getLong(); } System.out.println(time[0] + " " + time[1] + " " + time[2] + " " + time[3] + " " + end); if ( count++ > 4000){ System.exit(0); } } }
26.948718
74
0.577545
3d457df68694fa57878304b1d3f9671f540915cd
2,011
/* * Copyright (C) 2019 Digitoy Games. * * 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.digitoygames.compiler; /** * * @author mustafa */ public class If extends Branch { public String right; public String operand; @Override public void execute(Method meth, Stack stack) { if(right != null) { code = "if("+stack.pop().value+operand+right+")"; } else { code = "if("+stack.get(stack.size()-2).value+operand+stack.get(stack.size()-1).value+")"; stack.pop(); stack.pop(); } /* if(zero) { code = "if("+stack.pop().value+operand+"0)"; } else { code = "if("+stack.get(stack.size()-2).value+operand+stack.get(stack.size()-1).value+")"; stack.pop(); stack.pop(); }*/ code += " goto BC"+(pc+offset)+";";// "{flow="+(pc+offset)+";break outer;}"; } @Override public int getStackDelta() { return right == null ? -2 : -1; } @Override public String toString() { return "if "+operand+" go "+(pc+offset); } @Override public void generate(SourceWriter out) { /* if(zero) { out.print("if(ST[--SP].I %s 0) goto"); } else { out.print("SP-=2;"); out.print("if(ST[SP].%s %s ST[SP+1].%s) goto", type, operand, type); } out.println(" BC%d;", pc+offset); */ } }
26.813333
101
0.551964
4a44e2c9cad49f62c212e231858cdfe065779432
1,499
package uk.ac.ebi.embl.api.validation.dao.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class SubmitterReference { private String submissionAccountId; private Date firstCreated; private SubmissionAccount submissionAccount; private List<SubmissionContact> submissionContacts = new ArrayList<>(); public SubmitterReference(List<SubmissionContact> submissionContacts, SubmissionAccount submissionAccount) { this.submissionContacts = submissionContacts; this.submissionAccount = submissionAccount; } public SubmitterReference() { } public String getSubmissionAccountId() { return submissionAccountId; } public void setSubmissionAccountId(String submissionAccountId) { this.submissionAccountId = submissionAccountId; } public Date getFirstCreated() { return firstCreated; } public void setFirstCreated(Date firstCreated) { this.firstCreated = firstCreated; } public SubmissionAccount getSubmissionAccount() { return submissionAccount; } public void setSubmissionAccount(SubmissionAccount submissionAccount) { this.submissionAccount = submissionAccount; } public List<SubmissionContact> getSubmissionContacts() { return submissionContacts; } public void setSubmissionContacts(List<SubmissionContact> submissionContacts) { this.submissionContacts = submissionContacts; } }
26.767857
112
0.733823
5197558756b28aee06a7ff7de1cf44daca485421
614
package zone.cogni.asquare.graphcomposer; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; public class RegexUtils { @Deprecated // Reflectional access to named groups, should be replaced with capturing groups regex library public static Map<String, Integer> getNamedGroups(Pattern pattern) { try { Method method = Pattern.class.getDeclaredMethod("namedGroups"); method.setAccessible(true); return (Map<String, Integer>)method.invoke(pattern); } catch (Exception ex) { return new HashMap<>(); } } }
26.695652
96
0.721498
e3ac86ae2be6af54229f249045e56a4dc550db11
6,476
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.broker.service; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.common.policies.data.Policies; import org.apache.pulsar.common.policies.data.PublishRate; import org.testng.Assert; import org.testng.annotations.Test; import java.util.HashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @Test(groups = "broker") public class PrecisTopicPublishRateThrottleTest extends BrokerTestBase{ @Override protected void setup() throws Exception { //No-op } @Override protected void cleanup() throws Exception { //No-op } @Test public void testPrecisTopicPublishRateLimitingDisabled() throws Exception { PublishRate publishRate = new PublishRate(1,10); // disable precis topic publish rate limiting conf.setPreciseTopicPublishRateLimiterEnable(false); conf.setMaxPendingPublishRequestsPerConnection(0); super.baseSetup(); final String topic = "persistent://prop/ns-abc/testPrecisTopicPublishRateLimiting"; org.apache.pulsar.client.api.Producer<byte[]> producer = pulsarClient.newProducer() .topic(topic) .producerName("producer-name") .create(); Policies policies = new Policies(); policies.publishMaxMessageRate = new HashMap<>(); policies.publishMaxMessageRate.put("test", publishRate); Topic topicRef = pulsar.getBrokerService().getTopicReference(topic).get(); Assert.assertNotNull(topicRef); ((AbstractTopic)topicRef).updateMaxPublishRate(policies); MessageId messageId = null; try { // first will be success messageId = producer.sendAsync(new byte[10]).get(500, TimeUnit.MILLISECONDS); Assert.assertNotNull(messageId); // second will be success messageId = producer.sendAsync(new byte[10]).get(500, TimeUnit.MILLISECONDS); Assert.assertNotNull(messageId); } catch (TimeoutException e) { // No-op } Thread.sleep(1000); try { messageId = producer.sendAsync(new byte[10]).get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { // No-op } Assert.assertNotNull(messageId); super.internalCleanup(); } @Test public void testProducerBlockedByPrecisTopicPublishRateLimiting() throws Exception { PublishRate publishRate = new PublishRate(1,10); conf.setPreciseTopicPublishRateLimiterEnable(true); conf.setMaxPendingPublishRequestsPerConnection(0); super.baseSetup(); final String topic = "persistent://prop/ns-abc/testPrecisTopicPublishRateLimiting"; org.apache.pulsar.client.api.Producer<byte[]> producer = pulsarClient.newProducer() .topic(topic) .producerName("producer-name") .create(); Policies policies = new Policies(); policies.publishMaxMessageRate = new HashMap<>(); policies.publishMaxMessageRate.put("test", publishRate); Topic topicRef = pulsar.getBrokerService().getTopicReference(topic).get(); Assert.assertNotNull(topicRef); ((AbstractTopic)topicRef).updateMaxPublishRate(policies); MessageId messageId = null; try { // first will be success, and will set auto read to false messageId = producer.sendAsync(new byte[10]).get(500, TimeUnit.MILLISECONDS); Assert.assertNotNull(messageId); // second will be blocked producer.sendAsync(new byte[10]).get(500, TimeUnit.MILLISECONDS); Assert.fail("should failed, because producer blocked by topic publish rate limiting"); } catch (TimeoutException e) { // No-op } super.internalCleanup(); } @Test public void testPrecisTopicPublishRateLimitingProduceRefresh() throws Exception { PublishRate publishRate = new PublishRate(1,10); conf.setPreciseTopicPublishRateLimiterEnable(true); conf.setMaxPendingPublishRequestsPerConnection(0); super.baseSetup(); final String topic = "persistent://prop/ns-abc/testPrecisTopicPublishRateLimiting"; org.apache.pulsar.client.api.Producer<byte[]> producer = pulsarClient.newProducer() .topic(topic) .producerName("producer-name") .create(); Policies policies = new Policies(); policies.publishMaxMessageRate = new HashMap<>(); policies.publishMaxMessageRate.put("test", publishRate); Topic topicRef = pulsar.getBrokerService().getTopicReference(topic).get(); Assert.assertNotNull(topicRef); ((AbstractTopic)topicRef).updateMaxPublishRate(policies); MessageId messageId = null; try { // first will be success, and will set auto read to false messageId = producer.sendAsync(new byte[10]).get(500, TimeUnit.MILLISECONDS); Assert.assertNotNull(messageId); // second will be blocked producer.sendAsync(new byte[10]).get(500, TimeUnit.MILLISECONDS); Assert.fail("should failed, because producer blocked by topic publish rate limiting"); } catch (TimeoutException e) { // No-op } Thread.sleep(1000); try { messageId = producer.sendAsync(new byte[10]).get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { // No-op } Assert.assertNotNull(messageId); super.internalCleanup(); } }
41.780645
98
0.664145
8a214fe7237071a8f8ff7d0616753b6e6ddbc90e
1,385
package top.aprilyolies.beehive.transporter.server.serializer.factory; import com.alibaba.com.caucho.hessian.io.Hessian2Input; import com.alibaba.com.caucho.hessian.io.Hessian2Output; import io.netty.buffer.ByteBuf; import top.aprilyolies.beehive.common.URL; import top.aprilyolies.beehive.transporter.server.serializer.InputSerializer; import top.aprilyolies.beehive.transporter.server.serializer.OutputSerializer; import top.aprilyolies.beehive.transporter.server.serializer.hessian.HessianDeserializer; import top.aprilyolies.beehive.transporter.server.serializer.hessian.HessianSerializer; import top.aprilyolies.beehive.transporter.server.serializer.InputStreamAdapter; import top.aprilyolies.beehive.transporter.server.serializer.OutputStreamAdapter; /** * @Author EvaJohnson * @Date 2019-06-16 * @Email g863821569@gmail.com */ public class HessianFactory implements SerializerFactory { private final byte SERIALIZER_ID = 0x02; @Override public OutputSerializer serializer(URL url, ByteBuf buf) { return new HessianSerializer(new Hessian2Output(new OutputStreamAdapter(buf))); } @Override public InputSerializer deserializer(URL url, ByteBuf buf) { return new HessianDeserializer(new Hessian2Input(new InputStreamAdapter(buf))); } @Override public byte getSerializerId(URL url) { return SERIALIZER_ID; } }
37.432432
89
0.797112
d750a2358eea7c5ab096f7c0ae1d09aa398bc416
1,073
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.rflpz; /** * * @author Rflpz */ public class Place { private String name; private String address; private String type; private float lat; private float lon; public Place(){ } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getType() { return type; } public void setType(String type) { this.type = type; } public double getLat() { return lat; } public void setLat(float lat) { this.lat = lat; } public float getLon() { return lon; } public void setLon(float lon) { this.lon = lon; } }
17.031746
79
0.575023
1194e686b46c1ec15e4cbc402a1c4d9a548bab10
7,043
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.exec.store.sys; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import com.dremio.common.utils.PathUtils; import com.dremio.connector.metadata.BytesOutput; import com.dremio.connector.metadata.DatasetHandle; import com.dremio.connector.metadata.DatasetHandleListing; import com.dremio.connector.metadata.DatasetMetadata; import com.dremio.connector.metadata.EntityPath; import com.dremio.connector.metadata.GetDatasetOption; import com.dremio.connector.metadata.GetMetadataOption; import com.dremio.connector.metadata.ListPartitionChunkOption; import com.dremio.connector.metadata.PartitionChunkListing; import com.dremio.connector.metadata.extensions.SupportsListingDatasets; import com.dremio.connector.metadata.extensions.SupportsReadSignature; import com.dremio.connector.metadata.extensions.ValidateMetadataOption; import com.dremio.exec.catalog.CatalogUser; import com.dremio.exec.dotfile.View; import com.dremio.exec.planner.logical.ViewTable; import com.dremio.exec.server.JobResultInfoProvider; import com.dremio.exec.server.SabotContext; import com.dremio.exec.store.SchemaConfig; import com.dremio.exec.store.StoragePlugin; import com.dremio.exec.store.StoragePluginRulesFactory; import com.dremio.exec.store.Views; import com.dremio.exec.util.ViewFieldsHelper; import com.dremio.service.namespace.NamespaceKey; import com.dremio.service.namespace.SourceState; import com.dremio.service.namespace.capabilities.SourceCapabilities; import com.dremio.service.namespace.dataset.proto.DatasetConfig; import com.dremio.service.users.SystemUser; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; public class SystemStoragePlugin implements StoragePlugin, SupportsReadSignature, SupportsListingDatasets { private static final ImmutableMap<EntityPath, SystemTable> DATASET_MAP = ImmutableMap.copyOf(Stream.of(SystemTable.values()) .collect(Collectors.toMap(systemTable -> canonicalize(systemTable.getDatasetPath()), Function.identity()))); private static final String JOB_RESULTS = "job_results"; private static final String JOBS_STORAGE_PLUGIN_NAME = "__jobResultsStore"; private final SabotContext context; private final Predicate<String> userPredicate; private final JobResultInfoProvider jobResultInfoProvider; SystemStoragePlugin(SabotContext context, String name) { this(context, name, s -> true); } SystemStoragePlugin(SabotContext context, String name, Predicate<String> userPredicate) { Preconditions.checkArgument("sys".equals(name)); this.context = context; this.userPredicate = userPredicate; this.jobResultInfoProvider = context.getJobResultInfoProvider(); } SabotContext getSabotContext() { return context; } @Override public boolean hasAccessPermission(String user, NamespaceKey key, DatasetConfig datasetConfig) { // for view permissions, see #getView return userPredicate.test(user); } @Override public SourceState getState() { return SourceState.GOOD; } @Override public ViewTable getView(List<String> tableSchemaPath, SchemaConfig schemaConfig) { if (tableSchemaPath.size() != 3 || !JOB_RESULTS.equalsIgnoreCase(tableSchemaPath.get(1))) { return null; } final String jobId = Iterables.getLast(tableSchemaPath); final Optional<JobResultInfoProvider.JobResultInfo> jobResultInfo = jobResultInfoProvider.getJobResultInfo(jobId, schemaConfig.getUserName()); return jobResultInfo.map(info -> { final View view = Views.fieldTypesToView(jobId, getJobResultsQuery(info.getResultDatasetPath()), ViewFieldsHelper.getBatchSchemaFields(info.getBatchSchema()), null); return new ViewTable(new NamespaceKey(tableSchemaPath), view, CatalogUser.from(SystemUser.SYSTEM_USERNAME), info.getBatchSchema()); }).orElse(null); } private static String getJobResultsQuery(List<String> resultDatasetPath) { return String.format("SELECT * FROM %s", PathUtils.constructFullPath(resultDatasetPath)); } @Override public Class<? extends StoragePluginRulesFactory> getRulesFactoryClass() { return SystemTableRulesFactory.class; } @Override public SourceCapabilities getSourceCapabilities() { return SourceCapabilities.NONE; } @Override public void start() { } @Override public void close() { } @Override public DatasetHandleListing listDatasetHandles(GetDatasetOption... options) { return () -> Stream.of(SystemTable.values()).iterator(); } @Override public Optional<DatasetHandle> getDatasetHandle(EntityPath datasetPath, GetDatasetOption... options) { //noinspection unchecked return (Optional<DatasetHandle>) (Object) getDataset(datasetPath); } @Override public DatasetMetadata getDatasetMetadata( DatasetHandle datasetHandle, PartitionChunkListing chunkListing, GetMetadataOption... options ) { return datasetHandle.unwrap(SystemTable.class); } @Override public PartitionChunkListing listPartitionChunks(DatasetHandle datasetHandle, ListPartitionChunkOption... options) { return datasetHandle.unwrap(SystemTable.class); } @Override public boolean containerExists(EntityPath containerPath) { return false; } @Override public BytesOutput provideSignature(DatasetHandle datasetHandle, DatasetMetadata metadata) { return BytesOutput.NONE; } @Override public MetadataValidity validateMetadata( BytesOutput signature, DatasetHandle datasetHandle, DatasetMetadata metadata, ValidateMetadataOption... options ) { // returning INVALID allows us to refresh system source to apply schema updates. // system source is only refreshed once when CatalogService starts up // and won't be refreshed again since its refresh policy is NEVER_REFRESH_POLICY. return MetadataValidity.INVALID; } private static EntityPath canonicalize(EntityPath entityPath) { return new EntityPath(entityPath.getComponents().stream().map(String::toLowerCase).collect(Collectors.toList())); } public static Optional<SystemTable> getDataset(EntityPath datasetPath) { return Optional.ofNullable(DATASET_MAP.get(canonicalize(datasetPath))); } }
36.304124
118
0.778787
b5578dff28681485cef26651dda803ae9a27f32b
15,249
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.editor.fold.ui; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import org.netbeans.api.editor.fold.Fold; import org.netbeans.api.editor.fold.FoldHierarchy; import org.netbeans.api.editor.fold.FoldHierarchyEvent; import org.netbeans.api.editor.fold.FoldHierarchyListener; import org.netbeans.api.editor.fold.FoldStateChange; import org.netbeans.api.editor.fold.FoldUtilities; import org.netbeans.api.editor.mimelookup.MimeRegistration; import org.netbeans.editor.BaseCaret; import org.netbeans.modules.editor.lib2.caret.CaretFoldExpander; import org.netbeans.spi.editor.fold.FoldHierarchyMonitor; import org.openide.util.Exceptions; /** * Provides adjustments to functions of editor component * based on folding operations. * This code was originally part of editor.lib, in BaseCaret class. * * @author sdedic */ public class FoldingEditorSupport implements FoldHierarchyListener { private static final Logger LOG = Logger.getLogger(FoldingEditorSupport.class.getName()); static { CaretFoldExpander.register(new CaretFoldExpanderImpl()); } /** * Component where the folding takes place */ private final JTextComponent component; /** * Fold hierarchy */ private final FoldHierarchy foldHierarchy; FoldingEditorSupport(FoldHierarchy h, JTextComponent component) { this.component = component; this.foldHierarchy = h; component.putClientProperty("org.netbeans.api.fold.expander", new C()); foldHierarchy.addFoldHierarchyListener(this); } private class C implements Runnable, Callable<Boolean> { private boolean res; private boolean sharp; public void run() { foldHierarchy.lock(); try { int offset = component.getCaret().getDot(); res = false; Fold f = FoldUtilities.findCollapsedFold(foldHierarchy, offset, offset); if (f != null) { if (sharp) { res = f.getStartOffset() < offset && f.getEndOffset() > offset; } else { res = f.getStartOffset() <= offset && f.getEndOffset() >= offset; } if (res) { foldHierarchy.expand(f); } } } finally { foldHierarchy.unlock(); } } public boolean equals(Object whatever) { if (!(whatever instanceof Caret)) { return super.equals(whatever); } sharp = false; final Document doc = component.getDocument(); doc.render(this); return res; } public Boolean call() { sharp = true; final Document doc = component.getDocument(); doc.render(this); return res; } } public @Override void foldHierarchyChanged(final FoldHierarchyEvent evt) { final Caret c = component.getCaret(); // if (!(c instanceof BaseCaret)) { // return; // } // final BaseCaret bc = (BaseCaret)c; if (c == null) { return; } int caretOffset = c.getDot(); final int addedFoldCnt = evt.getAddedFoldCount(); boolean scrollToView = false; if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Received fold hierarchy change {1}, added folds: {0}", new Object[] { addedFoldCnt, evt.hashCode() }); // NOI18N } boolean expand = false; boolean includeEnd = false; int newPosition = -1; FoldHierarchy hierarchy = (FoldHierarchy) evt.getSource(); if (addedFoldCnt > 0) { expand = true; } else { int startOffset = Integer.MAX_VALUE; // Set the caret's offset to the end of just collapsed fold if necessary if (evt.getAffectedStartOffset() <= caretOffset && evt.getAffectedEndOffset() >= caretOffset) { for (int i = 0; i < evt.getFoldStateChangeCount(); i++) { FoldStateChange change = evt.getFoldStateChange(i); if (change.isCollapsedChanged()) { Fold fold = change.getFold(); if (fold.isCollapsed() && fold.getStartOffset() <= caretOffset && fold.getEndOffset() >= caretOffset) { if (fold.getStartOffset() < startOffset) { startOffset = fold.getStartOffset(); LOG.log(Level.FINER, "Moving caret from just collapsed fold {0} to offset {1}; evt=" + evt.hashCode(), new Object[] { fold, startOffset }); } } } else if (change.isStartOffsetChanged()) { // schedule expand iff the caret is in the NEWLY included prefix of the fold Fold fold = change.getFold(); int ostart = change.getOriginalStartOffset(); int nstart = fold.getStartOffset(); int nend = fold.getEndOffset(); int to = Math.max(ostart, nstart); int from = Math.min(ostart, nstart); boolean e = caretOffset >= from && caretOffset <= to && caretOffset >= nstart && caretOffset < nend; if (e && LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINER, "Fold start extended over caret: {0}; evt= " + evt.hashCode(), fold); } expand |= e; } else if (change.isEndOffsetChanged()) { // ... the same check for suffix. Fold fold = change.getFold(); int oend = change.getOriginalEndOffset(); int nend = fold.getEndOffset(); int nstart = fold.getStartOffset(); int to = Math.max(oend, nend); int from = Math.min(oend, nend); boolean e = caretOffset >= from && caretOffset <= to && caretOffset >= nstart && caretOffset <= nend; expand |= e; // the search for collapsed fold uses < not <= to compare fold end. Adjust caretOffset so the fold is found. includeEnd = caretOffset == nend && (nend - nstart) > 1; if (e && LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINER, "Fold end extended over caret: {0}, includeEnd = {1}; evt= " + evt.hashCode(), new Object[] { fold, includeEnd }); } } } if (startOffset != Integer.MAX_VALUE) { newPosition = startOffset; c.setDot(startOffset); expand = false; } } } boolean wasExpanded = false; if (expand) { Fold collapsed = null; if (includeEnd) { // compensate so findCollapsedFold finds something. Also for newly created folds so text does not collapse immediately // after a caret. caretOffset--; } final int dot = caretOffset; while ((collapsed = FoldUtilities.findCollapsedFold(hierarchy, caretOffset, caretOffset)) != null) { boolean shouldExpand = false; EX: if (collapsed.getStartOffset() < caretOffset) { if (collapsed.getEndOffset() > caretOffset) { shouldExpand = true; } else if (addedFoldCnt > 0) { // shortcut: caret immediately following the collapsed fold if (collapsed.getEndOffset() == caretOffset) { shouldExpand = true; } } } if (shouldExpand) { LOG.log(Level.FINER, "Expanding fold {0}; evt= " + evt.hashCode(), collapsed); wasExpanded = true; hierarchy.expand(collapsed); } else { break; } } // prevent unneeded scrolling; the user may have scrolled out using mouse already // so scroll only if the added fold may affect Y axis. Actually it's unclear why // we should reveal the current position on fold events except when caret is positioned in now-collapsed fold } if (!wasExpanded) { // go through folds just created folds, if some of them is _immediately_ preceding the caret && there's just whitespace in between the caret // and fold end - expand it. Fold preceding = caretOffset > 0 ? FoldUtilities.findNearestFold(hierarchy, -caretOffset) : null; if (preceding != null) { int precEnd = preceding.getEndOffset(); for (int i = 0; i < addedFoldCnt; i++) { Fold f = evt.getAddedFold(i); if (f.getStartOffset() > precEnd) { // fail fast break; } if (f == preceding && onlyWhitespacesBetween(f.getEndOffset(), caretOffset)) { LOG.log(Level.FINER, "Expanding fold {0}; evt= " + evt.hashCode(), f); wasExpanded = true; hierarchy.expand(f); break; } } if (!wasExpanded) { // go through changes and detect if the nearest preceding fold was expanded for (int i = 0; i < evt.getFoldStateChangeCount(); i++) { FoldStateChange change = evt.getFoldStateChange(i); Fold f = change.getFold(); int so = f.getStartOffset(); if (so > precEnd) { break; } if (change.isEndOffsetChanged() && f == preceding && f.isCollapsed() && onlyWhitespacesBetween(f.getEndOffset(), caretOffset) && // non empty content added to the fold: !onlyWhitespacesBetween(change.getOriginalEndOffset(), caretOffset)) { LOG.log(Level.FINER, "Expanding fold {0}; evt= " + evt.hashCode(), f); wasExpanded = true; hierarchy.expand(f); break; } } } } } scrollToView = wasExpanded; final int newPositionF = newPosition; // Update caret's visual position // Post the caret update asynchronously since the fold hierarchy is updated before // the view hierarchy and the views so the dispatchUpdate() could be picking obsolete // view information. if (LOG.isLoggable(Level.FINER)) { LOG.log(Level.FINER, "Added folds: {0}, should scroll: {1}, new pos: {2}; evt= " + evt.hashCode(), new Object[] { addedFoldCnt, scrollToView, newPosition }); } if (addedFoldCnt > 1 || scrollToView || newPosition >= 0) { final boolean scroll = scrollToView; SwingUtilities.invokeLater(new Runnable() { public @Override void run() { LOG.fine("Updating after fold hierarchy change; evt= " + evt.hashCode()); // NOI18N // see defect #227531; the caret may be uninstalled before the EDT executes this runnable. if (component == null || component.getCaret() != c) { return; } if (newPositionF >= 0) { c.setDot(newPositionF); } else { /* bc.refresh(addedFoldCnt > 1 && !scroll); */ } } }); } } private boolean onlyWhitespacesBetween(final int endOffset, final int dot) { // autoexpand a fold that was JUST CREATED, if there's no non-whitespace (not lexical, but actual) in between the // fold end and the caret: final String[] cnt = new String[1]; final Document doc = component.getDocument(); doc.render(new Runnable() { public void run() { int dl = doc.getLength(); int from = Math.min(dl, Math.min(endOffset, dot) ); int to = Math.min(dl, Math.max(endOffset, dot )); try { cnt[0] = doc.getText(from, to - from); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } }); return (cnt[0] == null || cnt[0].trim().isEmpty()); } @MimeRegistration(mimeType = "", service = FoldHierarchyMonitor.class) public static class F implements FoldHierarchyMonitor { @Override public void foldsAttached(FoldHierarchy h) { FoldingEditorSupport supp = new FoldingEditorSupport(h, h.getComponent()); // stick as client property to prevent GC: h.getComponent().putClientProperty(F.class, supp); } static { FoldViewFactory.register(); } } }
44.328488
152
0.518067
fc077a571b7e728a4220fea390fbb86ca8646e11
5,953
/** * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * 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.sdl.odata.test.model; import com.sdl.odata.api.edm.annotations.EdmEntity; import com.sdl.odata.api.edm.annotations.EdmEntitySet; import com.sdl.odata.api.edm.annotations.EdmProperty; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalTime; import java.time.Period; import java.time.ZonedDateTime; import java.util.UUID; /** * Primitive Types Sample test model. */ @EdmEntity(namespace = "ODataSample", key = {"ID" }) @EdmEntitySet public class PrimitiveTypesSample { /** * EDM Max Length. */ public static final int EDM_MAX_LENGTH = 80; @EdmProperty(name = "ID", nullable = false) private long id; @EdmProperty(name = "Name", nullable = false, maxLength = EDM_MAX_LENGTH) private String name; @EdmProperty(name = "NullProperty", nullable = true) private String nullProperty; @EdmProperty(name = "BinaryProperty", type = "Edm.Binary") private byte[] binaryProperty; @EdmProperty(name = "BooleanProperty", nullable = false) private boolean booleanProperty; @EdmProperty(name = "ByteProperty", type = "Edm.Byte", nullable = true) private byte byteProperty; @EdmProperty(name = "DateProperty") private LocalDate dateProperty; @EdmProperty(name = "DateTimeOffsetProperty") private ZonedDateTime dateTimeOffsetProperty; @EdmProperty(name = "DurationProperty") private Period durationProperty; @EdmProperty(name = "TimeOfDayProperty") private LocalTime timeOfDayProperty; @EdmProperty(name = "DecimalValueProperty") private BigDecimal decimalValueProperty; @EdmProperty(name = "DoubleProperty", nullable = false) private double doubleProperty; @EdmProperty(name = "SingleProperty", nullable = false) private float singleProperty; @EdmProperty(name = "GuidProperty") private UUID guidProperty; @EdmProperty(name = "Int16Property", nullable = false) private short int16Property; @EdmProperty(name = "Int32Property", nullable = false) private int int32Property; @EdmProperty(name = "SByteProperty", type = "Edm.SByte") private byte sbyteProperty; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNullProperty() { return nullProperty; } public void setNullProperty(String nullProperty) { this.nullProperty = nullProperty; } public byte[] getBinaryProperty() { return binaryProperty; } public void setBinaryProperty(byte[] binaryProperty) { this.binaryProperty = binaryProperty; } public boolean isBooleanProperty() { return booleanProperty; } public void setBooleanProperty(boolean booleanProperty) { this.booleanProperty = booleanProperty; } public byte getByteProperty() { return byteProperty; } public void setByteProperty(byte byteProperty) { this.byteProperty = byteProperty; } public LocalDate getDateProperty() { return dateProperty; } public void setDateProperty(LocalDate dateProperty) { this.dateProperty = dateProperty; } public ZonedDateTime getDateTimeOffsetProperty() { return dateTimeOffsetProperty; } public void setDateTimeOffsetProperty(ZonedDateTime dateTimeOffsetProperty) { this.dateTimeOffsetProperty = dateTimeOffsetProperty; } public Period getDurationProperty() { return durationProperty; } public void setDurationProperty(Period durationProperty) { this.durationProperty = durationProperty; } public LocalTime getTimeOfDayProperty() { return timeOfDayProperty; } public void setTimeOfDayProperty(LocalTime timeOfDayProperty) { this.timeOfDayProperty = timeOfDayProperty; } public BigDecimal getDecimalValueProperty() { return decimalValueProperty; } public void setDecimalValueProperty(float decimalValueProperty) { this.decimalValueProperty = new BigDecimal(decimalValueProperty); } public double getDoubleProperty() { return doubleProperty; } public void setDoubleProperty(double doubleProperty) { this.doubleProperty = doubleProperty; } public float getSingleProperty() { return singleProperty; } public void setSingleProperty(float singleProperty) { this.singleProperty = singleProperty; } public UUID getGuidProperty() { return guidProperty; } public void setGuidProperty(UUID guidProperty) { this.guidProperty = guidProperty; } public short getInt16Property() { return int16Property; } public void setInt16Property(short int16Property) { this.int16Property = int16Property; } public int getInt32Property() { return int32Property; } public void setInt32Property(int int32Property) { this.int32Property = int32Property; } public byte getSbyteProperty() { return sbyteProperty; } public void setSbyteProperty(byte sbyteProperty) { this.sbyteProperty = sbyteProperty; } }
26.22467
81
0.69276
282d0ac24400891f3d0a7d4edacc322654f7af9e
968
package mcjty.lib.worlddata; import net.minecraft.world.World; import net.minecraft.world.server.ServerWorld; import net.minecraft.world.storage.DimensionSavedDataManager; import net.minecraft.world.storage.WorldSavedData; import javax.annotation.Nonnull; import java.util.function.Supplier; /** * Local world data */ public abstract class AbstractLocalWorldData<T extends AbstractLocalWorldData<T>> extends WorldSavedData { protected AbstractLocalWorldData(String name) { super(name); } public void save() { setDirty(); } @Nonnull public static <T extends AbstractLocalWorldData<T>> T getData(World world, Supplier<? extends T> supplier, String name) { if (world.isClientSide) { throw new RuntimeException("Don't access this client-side!"); } DimensionSavedDataManager storage = ((ServerWorld)world).getDataStorage(); return storage.computeIfAbsent(supplier, name); } }
28.470588
125
0.722107
fc6e68b6f8e7e791b0047fdb328eba49180f117f
1,888
/* * Copyright (C) Red Gate Software Ltd 2010-2022 * * 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.flywaydb.core.extensibility; import org.flywaydb.core.api.FlywayException; import org.flywaydb.core.api.output.OperationResult; import java.util.List; import java.util.Map; /** * @apiNote This interface is under development and not recommended for use. */ public interface CommandExtension extends PluginMetadata { /** * @param command The CLI command to check is handled * @return Whether this extension handles the specified command */ boolean handlesCommand(String command); /** * @param flag The CLI flag to get the command for * @return The command, or null if no action is to be taken */ default String getCommandForFlag(String flag) { return null; } /** * @param parameter The parameter to check is handled * @return Whether this extension handles the specified parameter */ boolean handlesParameter(String parameter); /** * @param command The command to handle * @param config The configuration provided to Flyway * @param flags The CLI flags provided to Flyway * @return The result of this command being handled */ OperationResult handle(String command, Map<String, String> config, List<String> flags) throws FlywayException; }
34.327273
114
0.715572
3bef9c4f6e839b9271de70b8e1a56bef3bc1a504
126
package ro.esolacad.microservicesdemo.acounting.service; public interface EmailService { void sendEmail(String info); }
21
56
0.793651
1887fb89b94aa113be3433f4efc534b964cd061d
137
package cn.wao3.rpc.config; import lombok.Data; @Data public class RpcConfig { private String group; private String version; }
13.7
27
0.729927
bb517dd45cf8fcc2f40b2418dc52c72c1857525e
852
package ttr.core.gui.machine.steam; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import ttr.api.gui.SlotOutput; import ttr.core.gui.abstracts.ContainerTPC; import ttr.core.tile.machine.steam.TESteamAlloyFurnace; public class ContainerSteamAlloyFurnace extends ContainerTPC<TESteamAlloyFurnace> { public ContainerSteamAlloyFurnace(EntityPlayer player, TESteamAlloyFurnace inventory) { super(player, inventory); addSlotToContainer(new Slot(inventory, 0, 17, 25)); addSlotToContainer(new Slot(inventory, 1, 35, 25)); addSlotToContainer(new Slot(inventory, 2, 53, 25)); addSlotToContainer(new SlotOutput(inventory, 3, 107, 25)); addSlotToContainer(new Slot(inventory, 4, 80, 63)); locateRecipeInput = new TransLocation("input", 36, 39); locateRecipeOutput = new TransLocation("output", 39); } }
38.727273
86
0.787559
8fc554f9ad7a4529524adc40944daae0983574fc
4,647
package com.bx.erp.model.commodity; import java.util.List; import java.util.Map; import java.util.Random; import org.springframework.test.context.web.WebAppConfiguration; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.bx.erp.action.BaseAction; import com.bx.erp.action.bo.BaseBO; import com.bx.erp.model.BaseModel; import com.bx.erp.model.ErrorInfo.EnumErrorCode; import com.bx.erp.test.BaseMapperTest; import com.bx.erp.test.Shared; import com.bx.erp.util.DataSourceContextHolder; @WebAppConfiguration public class RefCommodityHubMapperTest extends BaseMapperTest { public static class DataInput { private static RefCommodityHub refCommodityHubInput = null; protected static final RefCommodityHub getRefCommodityHub() throws CloneNotSupportedException { refCommodityHubInput = new RefCommodityHub(); refCommodityHubInput.setName("可乐薯片南瓜味" + System.currentTimeMillis() % 1000000); refCommodityHubInput.setBarcode("1231" + System.currentTimeMillis() % 1000000); refCommodityHubInput.setShortName("薯片"); refCommodityHubInput.setSpecification("克"); refCommodityHubInput.setPackageUnitName("瓶"); refCommodityHubInput.setPurchasingUnit("箱"); refCommodityHubInput.setBrandName("默认品牌"); refCommodityHubInput.setCategoryName(""); refCommodityHubInput.setMnemonicCode("SP"); refCommodityHubInput.setPricingType(1); refCommodityHubInput.setPricePurchase(Math.abs(new Random().nextDouble())); refCommodityHubInput.setPriceRetail(Math.abs(new Random().nextDouble())); refCommodityHubInput.setPriceVIP(Math.abs(new Random().nextDouble())); refCommodityHubInput.setPriceWholesale(Math.abs(new Random().nextDouble())); refCommodityHubInput.setShelfLife(Math.abs(new Random().nextInt(18))); refCommodityHubInput.setReturnDays(Math.abs(new Random().nextInt(18)) + 1); refCommodityHubInput.setType(0); return (RefCommodityHub) refCommodityHubInput.clone(); } } @BeforeClass public void setup() { super.setup(); } @AfterClass public void tearDown() { super.tearDown(); } @Test public void retrieveNTest() throws Exception { Shared.printTestMethodStartInfo(); System.out.println("\n------------------------ retrieveN RefCommodityHub Test ------------------------"); Shared.caseLog("case 1:根据完整条形码查找所有有关的参照商品"); RefCommodityHub RefCommodityHub = DataInput.getRefCommodityHub(); RefCommodityHub.setBarcode("123456789"); Map<String, Object> params = RefCommodityHub.getRetrieveNParam(BaseBO.INVALID_CASE_ID, RefCommodityHub); DataSourceContextHolder.setDbName(Shared.StaticDBName_Test); List<BaseModel> retrieveN = refCommodityHubMapper.retrieveN(params); Assert.assertEquals(EnumErrorCode.values()[Integer.parseInt(params.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())], EnumErrorCode.EC_NoError); System.out.println(retrieveN); Shared.caseLog("case 2:根据不完整条形码查找所有有关的参照商品"); RefCommodityHub.setBarcode("1234"); Map<String, Object> params1 = RefCommodityHub.getRetrieveNParam(BaseBO.INVALID_CASE_ID, RefCommodityHub); DataSourceContextHolder.setDbName(Shared.StaticDBName_Test); List<BaseModel> retrieveN1 = refCommodityHubMapper.retrieveN(params1); Assert.assertEquals(EnumErrorCode.values()[Integer.parseInt(params1.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())], EnumErrorCode.EC_NoError); Assert.assertTrue(retrieveN1.size() == 0); Shared.caseLog("case 3:不输入条形码查找所有有关的参照商品"); RefCommodityHub.setBarcode(""); Map<String, Object> params2 = RefCommodityHub.getRetrieveNParam(BaseBO.INVALID_CASE_ID, RefCommodityHub); DataSourceContextHolder.setDbName(Shared.StaticDBName_Test); List<BaseModel> retrieveN2 = refCommodityHubMapper.retrieveN(params2); Assert.assertEquals(EnumErrorCode.values()[Integer.parseInt(params2.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())], EnumErrorCode.EC_NoError); Assert.assertTrue(retrieveN2.size() == 0); Shared.caseLog("case4:公司A可以查询到参考商品a"); // 原本的测试用例是公司A查询到参考商品a,公司B也可以查询到参考商品a,但是没有第二个公司拿来测试 // 公司A RefCommodityHub RefCommodityHubA = DataInput.getRefCommodityHub(); RefCommodityHubA.setBarcode("6926116000106"); Map<String, Object> paramsA = RefCommodityHubA.getRetrieveNParam(BaseBO.INVALID_CASE_ID, RefCommodityHubA); DataSourceContextHolder.setDbName(Shared.StaticDBName_Test); List<BaseModel> retrieveNA = refCommodityHubMapper.retrieveN(paramsA); Assert.assertEquals(EnumErrorCode.values()[Integer.parseInt(paramsA.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())], EnumErrorCode.EC_NoError); Assert.assertTrue(retrieveNA.size() == 1); } }
45.116505
150
0.792124
7658203abd8d3a7c9d1c824288d86d66529e7e10
550
package ru.job4j; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** *Test *@author Maksim Askhaev *@version $id$ *@Since 0.1 */ public class CalculateTest { /** *Тест */ @Test public void whenTakeNameThenThreeEchoPlusName() { String input = "Maksim Askhaev"; String expect = "Echo, echo, echo : Maksim Askhaev"; Calculate calc = new Calculate(); String result = calc.echo(input); assertThat(result, is(expect)); } }
18.333333
53
0.734545
5c69f3a415120dc2e71d80e8644466b5666a1e4a
7,389
/* * Copyright © 2017 CHANGLEI. All rights reserved. */ package net.box.app.library.adapter; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.Filter; import android.widget.Filterable; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerViewCompat; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import java.util.ArrayList; /** * Created by box on 2017/5/16. * <p> * headerView adapter */ @SuppressWarnings("WeakerAccess") public class IHeaderViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable { private final RecyclerView.Adapter<? super RecyclerView.ViewHolder> mAdapter; ArrayList<RecyclerViewCompat.FixedViewInfo> mHeaderViewInfos; ArrayList<RecyclerViewCompat.FixedViewInfo> mFooterViewInfos; static final ArrayList<RecyclerViewCompat.FixedViewInfo> EMPTY_INFO_LIST = new ArrayList<>(); private final boolean isFilterable; private boolean isStaggered; public IHeaderViewAdapter(ArrayList<RecyclerViewCompat.FixedViewInfo> headerViewInfos, ArrayList<RecyclerViewCompat.FixedViewInfo> footerViewInfos, RecyclerView.Adapter<? super RecyclerView.ViewHolder> adapter) { mAdapter = adapter; isFilterable = adapter instanceof Filterable; if (headerViewInfos == null) { mHeaderViewInfos = EMPTY_INFO_LIST; } else { mHeaderViewInfos = headerViewInfos; } if (footerViewInfos == null) { mFooterViewInfos = EMPTY_INFO_LIST; } else { mFooterViewInfos = footerViewInfos; } } public int getHeadersCount() { return mHeaderViewInfos.size(); } public int getFootersCount() { return mFooterViewInfos.size(); } @Override public int getItemCount() { if (mAdapter != null) { return getFootersCount() + getHeadersCount() + mAdapter.getItemCount(); } else { return getFootersCount() + getHeadersCount(); } } public boolean isEmpty() { return mAdapter == null || mAdapter.getItemCount() == 0; } public boolean removeHeader(View v) { for (int i = 0; i < mHeaderViewInfos.size(); i++) { RecyclerViewCompat.FixedViewInfo info = mHeaderViewInfos.get(i); if (info.view == v) { mHeaderViewInfos.remove(i); return true; } } return false; } public boolean removeFooter(View v) { for (int i = 0; i < mFooterViewInfos.size(); i++) { RecyclerViewCompat.FixedViewInfo info = mFooterViewInfos.get(i); if (info.view == v) { mFooterViewInfos.remove(i); return true; } } return false; } @Override public long getItemId(int position) { int numHeaders = getHeadersCount(); if (mAdapter != null && position >= numHeaders) { int adjPosition = position - numHeaders; int adapterCount = mAdapter.getItemCount(); if (adjPosition < adapterCount) { return mAdapter.getItemId(adjPosition); } } return -1; } @Override public int getItemViewType(int position) { int numHeaders = getHeadersCount(); if (position < numHeaders) { return mHeaderViewInfos.get(position).viewType; } int adjPosition = position - numHeaders; int adapterCount = 0; if (mAdapter != null) { adapterCount = mAdapter.getItemCount(); if (adjPosition < adapterCount) { return mAdapter.getItemViewType(adjPosition); } } return mFooterViewInfos.get(position - adapterCount - getHeadersCount()).viewType; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType <= RecyclerViewCompat.ITEM_VIEW_TYPE_HEADER + getHeadersCount()) { return getViewHolder(mHeaderViewInfos.get(viewType - RecyclerViewCompat.ITEM_VIEW_TYPE_HEADER).view); } if (viewType >= RecyclerViewCompat.ITEM_VIEW_TYPE_FOOTER - getFootersCount()) { return getViewHolder(mFooterViewInfos.get(RecyclerViewCompat.ITEM_VIEW_TYPE_FOOTER - viewType).view); } if (mAdapter != null) { return mAdapter.onCreateViewHolder(parent, viewType); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { int numHeaders = getHeadersCount(); if (position < numHeaders) { return; } int adjPosition = position - numHeaders; if (mAdapter != null) { if (adjPosition < mAdapter.getItemCount()) { mAdapter.onBindViewHolder(holder, adjPosition); } } } @Override public void registerAdapterDataObserver(RecyclerView.AdapterDataObserver observer) { if (mAdapter != null) { mAdapter.registerAdapterDataObserver(observer); } } @Override public void unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver observer) { if (mAdapter != null) { mAdapter.unregisterAdapterDataObserver(observer); } } @Override public Filter getFilter() { if (isFilterable) { return ((Filterable) mAdapter).getFilter(); } return null; } public void adjustSpanSize(RecyclerView recyclerView) { if (recyclerView.getLayoutManager() instanceof GridLayoutManager) { final GridLayoutManager manager = (GridLayoutManager) recyclerView.getLayoutManager(); manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { int numHeaders = getHeadersCount(); int adjPosition = position - numHeaders; if (position < numHeaders || adjPosition >= mAdapter.getItemCount()) return manager.getSpanCount(); return 1; } }); } if (recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager) { isStaggered = true; } } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); mAdapter.onAttachedToRecyclerView(recyclerView); } private RecyclerView.ViewHolder getViewHolder(View itemView) { if (isStaggered) { StaggeredGridLayoutManager.LayoutParams params = new StaggeredGridLayoutManager.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); params.setFullSpan(true); itemView.setLayoutParams(params); } return new HeaderFooterViewHolder(itemView); } private class HeaderFooterViewHolder extends RecyclerView.ViewHolder { public HeaderFooterViewHolder(View itemView) { super(itemView); } } }
32.84
159
0.633509
d154ea23f5b89212ec6f11651f42097ae68414c4
333
package com.wenox.uploading.service.listeners.events; import com.wenox.uploading.domain.template.Template; public class MetadataExtractedEvent { private final Template template; public MetadataExtractedEvent(Template template) { this.template = template; } public Template getTemplate() { return template; } }
19.588235
53
0.765766
0b04ab4ac596a8dc4d3cd23e7c6be2df2134ae92
12,475
package com.example.ankit.quickquiz; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.android.volley.DefaultRetryPolicy; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.example.ankit.quickquiz.DataModel.QuestionsModel; import com.example.ankit.quickquiz.Database.CustomContentProvider; import com.example.ankit.quickquiz.HelperClasses.MySingleton; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Random; import butterknife.BindView; import static com.example.ankit.quickquiz.HelperClasses.LogUtils.MY_SOCKET_TIMEOUT_MS; public class DualBattleQuestionsActivity extends AppCompatActivity { private static final String LOG_TAG = DualBattleQuestionsActivity.class.getName(); private static final String BATTLE_QUESTIONS_URL = "http://104.236.57.114:8080/quickquiz/v1/questions/battle/get_questions"; private static final String CORRECT_QUESTIONS_KEY = "numberOfCorrectQuestions"; private static final String INCORRECT_QUESTIONS_KEY = "numberOfInCorrectQuestions"; Context mContext; CustomContentProvider mCustomContentProvider; RequestQueue mRequestQueue; int userCorrectQuestions = 0; int userInCorrectQuestions = 0; int questionsPositions = 0; int correctOption = 0; ArrayList<QuestionsModel> questionsArrayList; /** * Member Variable to temporary store Values of Post */ String question; String option1; String option2; String option3; String option4; int answerOption; /** * AI ALGORITH PARAMETERS POSTED BACK AFTER THE GAME ENDS */ int correctHits; int difficultyLevel; int effeciency; int wrongHits; String category; int categoryId; int questionId; private String message; ProgressBar spinner; @BindView(R.id.activity_dual_battle_questions) CoordinatorLayout mainLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dual_battle_questions); mContext = this; spinner = (ProgressBar) findViewById(R.id.pb_loading_questions); loadBattleQuestions(); } /* private void showCorrectAnswer() { //Get question position from the Array List and the correct ans position QuestionsModel q = new QuestionsModel(); q = questionsArrayList.get(questionsPositions); correctOption = q.getAnswerOption(); if (correctOption == 1) { option1Button.setBackgroundColor(ContextCompat.getColor(mContext, R.color.green)); } else if (correctOption == 2) { option2Button.setBackgroundColor(ContextCompat.getColor(mContext, R.color.green)); } else if (correctOption == 3) { option3Button.setBackgroundColor(ContextCompat.getColor(mContext, R.color.green)); } else if (correctOption == 4) { option4Button.setBackgroundColor(ContextCompat.getColor(mContext, R.color.green)); } else { Toast.makeText(mContext, "OPSEEEE!!!!", Toast.LENGTH_LONG).show(); Log.e(LOG_TAG, "OPTION GALAT BHAI"); } }*/ private void loadBattleQuestions() { mRequestQueue = MySingleton.getInstance(mContext.getApplicationContext()).getRequestQueue(); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(BATTLE_QUESTIONS_URL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { //Log.d(LOG_TAG, response.toString()); //Here start Intent Service that'll parse JsonPostResponse on background Thread /*Intent parseIntent = new Intent(DualBattleQuestionsActivity.this, ParseJsonResponse.class); *//** * Also pass the result JSONObject as Intent extra *//* parseIntent.putExtra(getString(R.string.json_response_battle_response_key), response.toString()); startService(parseIntent);*/ /** * Currently No {@link android.app.IntentService} */ parseJsonResponse(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); //Set Retry Policy for MY_SOCKET_TIMEOUT_MS = 10 SECONDS jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy( MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT )); MySingleton.getInstance(mContext).addToRequestQueue(jsonObjectRequest); } public void parseJsonResponse(JSONObject response) { questionsArrayList = new ArrayList<>(); /** *Start Parsing the list */ try { JSONArray jsonArray = response.getJSONArray("questionList"); int lenght = jsonArray.length(); JSONObject singleQuestionJsonObject; for (int i = 0; i < lenght; i++) { QuestionsModel questionsObject = new QuestionsModel(); singleQuestionJsonObject = jsonArray.getJSONObject(i); question = singleQuestionJsonObject.getString("question"); option1 = singleQuestionJsonObject.getString("optionOne"); option2 = singleQuestionJsonObject.getString("optionTwo"); option3 = singleQuestionJsonObject.getString("optionThree"); option4 = singleQuestionJsonObject.getString("optionFour"); answerOption = singleQuestionJsonObject.getInt("answer"); questionId = singleQuestionJsonObject.getInt("questionId"); correctHits = singleQuestionJsonObject.getInt("correctHits"); wrongHits = singleQuestionJsonObject.getInt("wrongHits"); difficultyLevel = singleQuestionJsonObject.getInt("difficultyLevel"); effeciency = singleQuestionJsonObject.getInt("efficiency"); //Get Category of the question using categoryJsonObject JSONObject categoryJsonObject = singleQuestionJsonObject.getJSONObject("category"); category = categoryJsonObject.getString("category"); categoryId = categoryJsonObject.getInt("categoryId"); /** *Set questions Data Object */ questionsObject.setQuestion(question); questionsObject.setOption1(option1); questionsObject.setOption2(option2); questionsObject.setOption3(option3); questionsObject.setOption4(option4); questionsObject.setAnswerOption(answerOption); questionsObject.setCorrectHits(correctHits); questionsObject.setWrongHits(wrongHits); questionsObject.setDifficultyLevel(difficultyLevel); questionsObject.setEffeciency(effeciency); questionsObject.setCategory(category); questionsObject.setCategoryId(categoryId); questionsArrayList.add(questionsObject); } try { Log.d(LOG_TAG, response.toString()); //message = questionsArrayList.get(1).getQuestion() + "\n" + questionsArrayList.get(1).getAnswerOption(); } catch (Exception e) { e.printStackTrace(); } //Log.d(LOG_TAG, message); //showMesssageOnUiThread(message); } catch (JSONException e) { e.printStackTrace(); } spinner.setVisibility(View.GONE); updateUiwithQusttions(); //Add Questions to Database after parsing addQuestionToDb(); } public void updateUiwithQusttions() { /** *Send question and position of the question to the {@link BattleQuestionsFragment} * and update the posititon of the question in the questionsArrayList */ try { /**If questions position is>=10 then * Game Over Launch Game Over Screenions */ if (questionsPositions >= 10) { //CREATE GAME OVER SCREEN TO DISPLAY RESULT and send Info to display Toast.makeText(mContext, getString(R.string.game_over), Toast.LENGTH_LONG).show(); Intent intent = new Intent(DualBattleQuestionsActivity.this, DualBattleResultActivity.class); intent.putExtra(CORRECT_QUESTIONS_KEY, userCorrectQuestions); intent.putExtra(INCORRECT_QUESTIONS_KEY, userInCorrectQuestions); startActivity(intent); } else { getSupportFragmentManager().beginTransaction() .replace(R.id.activity_dual_battle_questions, new BattleQuestionsFragment()) .commit(); Log.d(LOG_TAG, "FRAGMENT STARTED N0--" + questionsPositions); questionsPositions++; } } catch (Exception e) { e.printStackTrace(); } } private void addQuestionToDb() { try { int questionId = 0; String categoryString; mCustomContentProvider = new CustomContentProvider(mContext); int size = questionsArrayList.size(); QuestionsModel questionsModel = new QuestionsModel(); for (int i = 0; i < size; i++) { questionsModel = questionsArrayList.get(i); questionId = questionsModel.getQuestionId(); categoryString = questionsModel.getCategory(); mCustomContentProvider.addQuestion(questionId, categoryString); } mCustomContentProvider.addQuestionsToDB(); } catch (Exception e) { e.printStackTrace(); } } /** * THIS Method used in Fragment to get Question At questionsPositions * which is incremented after each fragmentTransition * * @return QuestionsModel */ public QuestionsModel questionAtPosition() { QuestionsModel q = new QuestionsModel(); q = questionsArrayList.get(questionsPositions - 1); return q; } public void userCorrectQuestion() { userCorrectQuestions++; } public void userInCorrectQuestions() { userInCorrectQuestions++; } public int getUserCorrectQuestions() { return userCorrectQuestions; } public int getUserInCorrectQuestions() { return userInCorrectQuestions; } public ArrayList<QuestionsModel> getQuestionsArrayList() { return questionsArrayList; } public int getQuestionsPosition() { /** * -1 Because after the start of {@link BattleQuestionsFragment} * questionsPositions is incremented, so 1st question will never be dislayed */ return questionsPositions - 1; } private boolean checkCorrectOption(int correctOption, int clickedOttion) { if (correctOption == clickedOttion) { return true; } else { return false; } } private int opponentPlayerTime() { Random random = new Random(); //Generate random number from 0 to 10 int num = random.nextInt(10) + 1; return num; } }
36.691176
129
0.617956
c61716201d0853ad1818f1f902612632f536e8aa
1,337
/* * Copyright (c) 2000-2007 JetBrains s.r.o. All Rights Reserved. */ package com.intellij.spring.impl.model.aop; import com.intellij.aop.psi.AopReferenceExpression; import com.intellij.aop.psi.PsiPointcutExpression; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiParameter; import com.intellij.psi.PsiRecursiveElementVisitor; import com.intellij.spring.model.xml.aop.SpringPointcut; import java.util.HashSet; import java.util.Set; /** * @author peter */ public abstract class SpringPointcutImpl implements SpringPointcut { public PsiElement getIdentifyingPsiElement() { return getXmlTag(); } public int getParameterCount() { final PsiPointcutExpression expression = getExpression().getValue(); if (expression == null) return -1; final Set<String> paramNames = new HashSet<String>(); expression.acceptChildren(new PsiRecursiveElementVisitor() { @Override public void visitElement(final PsiElement element) { if (element instanceof AopReferenceExpression) { final PsiElement psiElement = ((AopReferenceExpression)element).resolve(); if (psiElement instanceof PsiParameter) { paramNames.add(((PsiParameter)psiElement).getName()); } } super.visitElement(element); } }); return paramNames.size(); } }
30.386364
84
0.722513
64f6182c6d22649875f4d11f7308ff7a665b1d03
5,931
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org) * Copyright (C) 2011-2012 Eugene Fradkin (eugene.fradkin@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.postgresql.tools.maintenance; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkbenchWindow; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.postgresql.model.PostgreDatabase; import org.jkiss.dbeaver.ext.postgresql.model.PostgreObject; import org.jkiss.dbeaver.ext.postgresql.model.PostgreTableBase; import org.jkiss.dbeaver.model.DBPEvaluationContext; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.tools.IExternalTool; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.utils.CommonUtils; import java.util.Collection; import java.util.List; /** * Table vacuum */ public class PostgreToolVacuum implements IExternalTool { @Override public void execute(IWorkbenchWindow window, IWorkbenchPart activePart, Collection<DBSObject> objects) throws DBException { List<PostgreTableBase> tables = CommonUtils.filterCollection(objects, PostgreTableBase.class); if (!tables.isEmpty()) { SQLDialog dialog = new SQLDialog(activePart.getSite(), tables); dialog.open(); } else { List<PostgreDatabase> databases = CommonUtils.filterCollection(objects, PostgreDatabase.class); if (!databases.isEmpty()) { SQLDialog dialog = new SQLDialog(activePart.getSite(), databases.get(0).getDataSource().getDefaultInstance()); dialog.open(); } } } static class SQLDialog extends TableToolDialog { private Button fullCheck; private Button freezeCheck; private Button analyzeCheck; private Button dpsCheck; public SQLDialog(IWorkbenchPartSite partSite, Collection<PostgreTableBase> selectedTables) { super(partSite, "Vacuum table(s)", selectedTables); } public SQLDialog(IWorkbenchPartSite partSite, PostgreDatabase database) { super(partSite, "Vacuum database", database); } @Override protected void generateObjectCommand(List<String> lines, PostgreObject object) { String sql = "VACUUM (VERBOSE"; if (fullCheck.getSelection()) sql += ",FULL"; if (freezeCheck.getSelection()) sql += ",FREEZE"; if (analyzeCheck.getSelection()) sql += ",ANALYZE"; if (dpsCheck.getSelection()) sql += ",DISABLE_PAGE_SKIPPING"; sql += ")"; if (object instanceof PostgreTableBase) { sql += " " + ((PostgreTableBase)object).getFullyQualifiedName(DBPEvaluationContext.DDL); } lines.add(sql); } @Override protected void createControls(Composite parent) { Group optionsGroup = UIUtils.createControlGroup(parent, "Options", 1, 0, 0); optionsGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fullCheck = UIUtils.createCheckbox(optionsGroup, "Full", "Selects \"full\" vacuum, which can reclaim more space, but takes much longer and exclusively locks the table.\nThis method also requires extra disk space, since it writes a new copy of the table and doesn't release the old copy until the operation is complete.\nUsually this should only be used when a significant amount of space needs to be reclaimed from within the table.", false, 0); fullCheck.addSelectionListener(SQL_CHANGE_LISTENER); freezeCheck = UIUtils.createCheckbox(optionsGroup, "Freeze", "Selects aggressive \"freezing\" of tuples. Specifying FREEZE is equivalent to performing VACUUM with the vacuum_freeze_min_age and vacuum_freeze_table_age parameters set to zero.\nAggressive freezing is always performed when the table is rewritten, so this option is redundant when FULL is specified.", false, 0); freezeCheck.addSelectionListener(SQL_CHANGE_LISTENER); analyzeCheck = UIUtils.createCheckbox(optionsGroup, "Analyze", "Updates statistics used by the planner to determine the most efficient way to execute a query.", false, 0); analyzeCheck.addSelectionListener(SQL_CHANGE_LISTENER); dpsCheck = UIUtils.createCheckbox(optionsGroup, "Disable page skipping", "Normally, VACUUM will skip pages based on the visibility map.\nPages where all tuples are known to be frozen can always be skipped, and those where all tuples are known to be visible to all transactions may be skipped except when performing an aggressive vacuum.\nFurthermore, except when performing an aggressive vacuum, some pages may be skipped in order to avoid waiting for other sessions to finish using them.\nThis option disables all page-skipping behavior, and is intended to be used only the contents of the visibility map are thought to be suspect, which should happen only if there is a hardware or software issue causing database corruption.", false, 0); dpsCheck.addSelectionListener(SQL_CHANGE_LISTENER); createObjectsSelector(parent); } } }
53.918182
752
0.721801
87f47171d0c6b2a1d852bcbd816ae4de7f1d1668
230
@ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault package choonster.testmod3.world.level.levelgen.placement; import net.minecraft.MethodsReturnNonnullByDefault; import javax.annotation.ParametersAreNonnullByDefault;
28.75
58
0.895652
692568bffe505e909cce19450828f200bb113778
7,986
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.blockmanagement; import io.hops.common.INodeUtil; import io.hops.exception.StorageException; import io.hops.metadata.HdfsStorageFactory; import io.hops.metadata.hdfs.entity.INodeIdentifier; import io.hops.transaction.handler.HDFSOperationType; import io.hops.transaction.handler.HopsTransactionalRequestHandler; import io.hops.transaction.lock.LockFactory; import io.hops.transaction.lock.TransactionLocks; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.fs.permission.PermissionStatus; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.StorageType; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.server.namenode.INodeFile; import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage; import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static io.hops.transaction.lock.LockFactory.BLK; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * This test makes sure that * CorruptReplicasMap::numBlocksWithCorruptReplicas and * CorruptReplicasMap::getCorruptReplicaBlockIds * return the correct values */ public class TestCorruptReplicaInfo { private static final Log LOG = LogFactory.getLog(TestCorruptReplicaInfo.class); private Map<Integer, BlockInfo> block_map = new HashMap<>(); private BlocksMap blocksMap = new BlocksMap(null); // Allow easy block creation by block id // Return existing block if one with same block id already exists private BlockInfo getBlock(Integer block_id) { if (!block_map.containsKey(block_id)) { block_map .put(block_id, new BlockInfo(new Block(block_id, 0, 0), block_id)); } return block_map.get(block_id); } @Test public void testCorruptReplicaInfo() throws IOException, InterruptedException, StorageException { HdfsStorageFactory.setConfiguration(new HdfsConfiguration()); HdfsStorageFactory.formatStorage(); CorruptReplicasMap crm = new CorruptReplicasMap(null); // Make sure initial values are returned correctly assertEquals("Number of corrupt blocks must initially be 0", 0, crm.size()); assertNull("Param n cannot be less than 0", crm.getCorruptReplicaBlockIds(-1, null)); assertNull("Param n cannot be greater than 100", crm.getCorruptReplicaBlockIds(101, null)); long[] l = crm.getCorruptReplicaBlockIds(0, null); assertNotNull("n = 0 must return non-null", l); assertEquals("n = 0 must return an empty list", 0, l.length); // create a list of block_ids. A list is used to allow easy validation of the // output of getCorruptReplicaBlockIds int NUM_BLOCK_IDS = 140; List<Integer> block_ids = new LinkedList<>(); for (int i = 0; i < NUM_BLOCK_IDS; i++) { block_ids.add(i); } DatanodeDescriptor dn1 = DFSTestUtil.getLocalDatanodeDescriptor(); DatanodeStorage ds1 = new DatanodeStorage("storageid_1", DatanodeStorage.State.NORMAL, StorageType.DEFAULT); DatanodeStorageInfo storage1 = new DatanodeStorageInfo(dn1, ds1); DatanodeDescriptor dn2 = DFSTestUtil.getLocalDatanodeDescriptor(); DatanodeStorage ds2 = new DatanodeStorage("storageid_2", DatanodeStorage.State.NORMAL, StorageType.DEFAULT); DatanodeStorageInfo storage2 = new DatanodeStorageInfo(dn2, ds2); addToCorruptReplicasMap(crm, getBlock(0), storage1, "TEST"); assertEquals("Number of corrupt blocks not returning correctly", 1, crm.size()); addToCorruptReplicasMap(crm, getBlock(1), storage1, "TEST"); assertEquals("Number of corrupt blocks not returning correctly", 2, crm.size()); addToCorruptReplicasMap(crm, getBlock(1), storage2, "TEST"); assertEquals("Number of corrupt blocks not returning correctly", 2, crm.size()); removeFromCorruptReplicasMap(crm, getBlock(1)); assertEquals("Number of corrupt blocks not returning correctly", 1, crm.size()); removeFromCorruptReplicasMap(crm, getBlock(0)); assertEquals("Number of corrupt blocks not returning correctly", 0, crm.size()); for (Integer block_id : block_ids) { addToCorruptReplicasMap(crm, getBlock(block_id), storage1, "TEST"); } assertEquals("Number of corrupt blocks not returning correctly", NUM_BLOCK_IDS, crm.size()); assertTrue("First five block ids not returned correctly ", Arrays .equals(new long[]{0, 1, 2, 3, 4}, crm.getCorruptReplicaBlockIds(5, null))); LOG.info(crm.getCorruptReplicaBlockIds(10, 7L)); LOG.info(block_ids.subList(7, 18)); assertTrue("10 blocks after 7 not returned correctly ", Arrays .equals(new long[]{8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, crm.getCorruptReplicaBlockIds(10, 7L))); } private void addToCorruptReplicasMap(final CorruptReplicasMap crm, final BlockInfo blk, final DatanodeStorageInfo storage, final String reason) throws IOException { new HopsTransactionalRequestHandler( HDFSOperationType.TEST_CORRUPT_REPLICA_INFO) { INodeIdentifier inodeIdentifier; @Override public void setUp() throws StorageException, IOException { inodeIdentifier = INodeUtil.resolveINodeFromBlock(blk); } @Override public void acquireLock(TransactionLocks locks) throws IOException { LockFactory lf = LockFactory.getInstance(); locks.add(lf.getIndividualBlockLock(blk.getBlockId(), inodeIdentifier)) .add(lf.getBlockRelated(BLK.CR)); } @Override public Object performTask() throws StorageException, IOException { blocksMap.addBlockCollection(blk, new INodeFile(new PermissionStatus ("n", "n", FsPermission.getDefault()), null, (short)1, 0, 0, 1)); crm.addToCorruptReplicasMap(blk, storage, reason); return null; } }.handle(); } private void removeFromCorruptReplicasMap(final CorruptReplicasMap crm, final BlockInfo blk) throws IOException { new HopsTransactionalRequestHandler( HDFSOperationType.TEST_CORRUPT_REPLICA_INFO) { INodeIdentifier inodeIdentifier; @Override public void setUp() throws StorageException, IOException { inodeIdentifier = INodeUtil.resolveINodeFromBlock(blk); } @Override public void acquireLock(TransactionLocks locks) throws IOException { LockFactory lf = LockFactory.getInstance(); locks.add(lf.getIndividualBlockLock(blk.getBlockId(), inodeIdentifier)) .add(lf.getBlockRelated(BLK.CR)); } @Override public Object performTask() throws StorageException, IOException { crm.removeFromCorruptReplicasMap(blk); return null; } }.handle(); } }
38.028571
82
0.726146
71de8a9f69155676361b2b7ed6cac40deb76250f
589
// Copyright 2000-2017 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 org.jetbrains.java.decompiler.code; import java.util.LinkedList; import java.util.List; public class ExceptionTable { public static final ExceptionTable EMPTY = new ExceptionTable(new LinkedList<ExceptionHandler>()); private final List<ExceptionHandler> handlers; public ExceptionTable(List<ExceptionHandler> handlers) { this.handlers = handlers; } public List<ExceptionHandler> getHandlers() { return handlers; } }
31
140
0.7691
eef074e8da1f94ff3a03443bfa540f1f1348461d
777
/** * 文 件 名: ModifyAppConfigReq * 版 权: Quanten Teams. Copyright YYYY-YYYY, All rights reserved * 描 述: <描述> * 修 改 人: zhouhaofeng * 修改时间: 2017/11/6 * 跟踪单号: <跟踪单号> * 修改单号: <修改单号> * 修改内容: <修改内容> */ package com.quanteng.gsmp.resource.appconfig.request; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; /** * 修改应用配置请求 * * @author zhouhaofeng * @version 2017/11/6 * @see [相关类/方法] * @since [产品/模块版本] */ @Setter @Getter @ToString public class ModifyAppConfigReq implements Serializable { private static final long serialVersionUID = -1L; private String configId; private String countryId; private String serviceId; private String appId; private String appName; private String originalUrl; }
16.891304
68
0.700129
015d1bcbf61765db8d06f9cfa7a4f6fdc14958f3
2,408
package ch.rasc.wampspring.demo.various.scheduler; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.ObjectMapper; import ch.rasc.wampspring.EventMessenger; import ch.rasc.wampspring.annotation.WampCallListener; import ch.rasc.wampspring.annotation.WampPublishListener; import ch.rasc.wampspring.message.PublishMessage; @Service public class SchedulerHandler { @Autowired private EventMessenger eventMessenger; private final static ObjectMapper mapper = new ObjectMapper(); @WampCallListener(value = "schdemo#doInitialLoad") public Map<String, Collection<CustomEvent>> doInitialLoad() { return Collections.singletonMap("data", CustomEventDb.list()); } @WampPublishListener(value = "schdemo#clientDoUpdate", replyTo = "schdemo#serverDoUpdate", excludeSender = true) public CustomEvent update(CustomEvent record) { CustomEventDb.update(record); return record; } @WampPublishListener(value = "schdemo#clientDoAdd", replyTo = "schdemo#serverDoAdd", excludeSender = true) public Map<String, List<Object>> add(PublishMessage message, List<Map<String, Object>> records) { List<Object> updatedRecords = new ArrayList<>(); List<Map<String, Object>> ids = new ArrayList<>(); for (Map<String, Object> r : records) { @SuppressWarnings("unchecked") Map<String, Object> record = (Map<String, Object>) r.get("data"); String internalId = (String) r.get("internalId"); CustomEvent event = mapper.convertValue(record, CustomEvent.class); CustomEventDb.create(event); updatedRecords.add(event); Map<String, Object> result = new HashMap<>(); result.put("internalId", internalId); result.put("record", event); ids.add(result); } this.eventMessenger.sendTo("schdemo#serverSyncId", Collections.singletonMap("records", ids), message.getWebSocketSessionId()); return Collections.singletonMap("records", updatedRecords); } @WampPublishListener(value = "schdemo#clientDoRemove", replyTo = "schdemo#serverDoRemove", excludeSender = true) public Map<String, List<Integer>> remove(List<Integer> ids) { CustomEventDb.delete(ids); return Collections.singletonMap("ids", ids); } }
31.272727
85
0.758721
b67bb5cf6b7ebe2be3c06b24418f60b932dfe8e8
3,883
package net.emaze.dysfunctional.filtering; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import net.emaze.dysfunctional.dispatching.logic.Always; import net.emaze.dysfunctional.dispatching.logic.Never; import java.util.function.Predicate; import net.emaze.dysfunctional.iterations.ConstantIterator; import org.junit.Assert; import org.junit.Test; /** * * @author rferranti */ public class FilteringIteratorTest { @Test(expected = IllegalArgumentException.class) public void creatingFilteringIteratorWithNullIteratorYieldsException() { new FilteringIterator<Object>(null, new Always<Object>()); } @Test(expected = IllegalArgumentException.class) public void creatingFilteringIteratorWithNullPredicateYieldsException() { new FilteringIterator<Object>(new ConstantIterator<Object>("a"), null); } @Test(expected = NoSuchElementException.class) public void callingNextOnEmptyIteratorYieldsException() { List<Integer> bucket = Collections.<Integer>emptyList(); Iterator<Integer> iter = new FilteringIterator<Integer>(bucket.iterator(), new Always<Integer>()); iter.next(); } @Test(expected = NoSuchElementException.class) public void callingNextOnNeverMatchingIteratorYieldsException() { List<Integer> bucket = Arrays.asList(1, 2, 3); Iterator<Integer> iter = new FilteringIterator<Integer>(bucket.iterator(), new Never<Integer>()); iter.next(); } @Test public void callingHasNextDoesNotConsumeValues() { List<Integer> bucket = Arrays.asList(1); Iterator<Integer> iter = new FilteringIterator<Integer>(bucket.iterator(), new Always<Integer>()); iter.hasNext(); iter.hasNext(); Assert.assertEquals(Integer.valueOf(1), iter.next()); } @Test public void emptyIteratorHasNoNext() { List<Integer> bucket = Collections.emptyList(); Iterator<Integer> iter = new FilteringIterator<Integer>(bucket.iterator(), new Always<Integer>()); Assert.assertFalse(iter.hasNext()); } @Test public void whenPredicateEvaluatesToFalseElementsAreFilteredOut() { List<Integer> bucket = Collections.singletonList(1); Iterator<Integer> iter = new FilteringIterator<Integer>(bucket.iterator(), new Never<Integer>()); Assert.assertFalse(iter.hasNext()); } @Test public void canCallNextMultipleTimesWithoutCallingHasNext() { List<Integer> bucket = Arrays.asList(1, 2); Iterator<Integer> iter = new FilteringIterator<Integer>(bucket.iterator(), new Always<Integer>()); List<Integer> got = new ArrayList<Integer>(); got.add(iter.next()); got.add(iter.next()); Assert.assertEquals(bucket, got); } @Test public void canRemoveFromFilteringIterator() { List<Integer> bucket = new ArrayList<Integer>(); bucket.add(1); bucket.add(2); Iterator<Integer> iter = new FilteringIterator<Integer>(bucket.iterator(), new Always<Integer>()); iter.next(); iter.remove(); Assert.assertEquals(Arrays.asList(2), bucket); } @Test public void filterIsAppliedOncePerElement() { List<Integer> bucket = Arrays.asList(1, 2); SpyPredicate<Integer> spy = new SpyPredicate<Integer>(); Iterator<Integer> iter = new FilteringIterator<Integer>(bucket.iterator(), spy); iter.hasNext(); iter.hasNext(); iter.next(); Assert.assertEquals(1, spy.calls); } private static class SpyPredicate<T> implements Predicate<T> { private int calls = 0; @Override public boolean test(T elem) { calls++; return true; } } }
34.061404
106
0.678084
472b4269e188386f582ad13b710405dd46d6a220
7,610
/* * This project constitutes a work of the United States Government and is * not subject to domestic copyright protection under 17 USC § 105. * * However, because the project utilizes code licensed from contributors * and other third parties, it therefore is licensed under the MIT * License. http://opensource.org/licenses/mit-license.php. Under that * license, permission is 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 conditions that any appropriate copyright notices and this * permission notice are 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 gov.whitehouse.ui.adapters; import com.androidquery.AQuery; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import gov.whitehouse.R; import gov.whitehouse.core.FeedItem; import gov.whitehouse.ui.activities.BaseActivity; import gov.whitehouse.ui.activities.app.VideoGalleryActivity; import gov.whitehouse.utils.DateUtils; import static android.graphics.Color.TRANSPARENT; import static android.view.View.GONE; import static android.view.View.INVISIBLE; import static android.view.View.VISIBLE; public class FeedItemsListAdapter extends BaseAdapter { private static class ViewHolder { TextView date; ImageView thumbnail; LinearLayout metaholder; TextView title; TextView time; } private BaseActivity mContext; private ArrayList<FeedItem> mItems; public FeedItemsListAdapter(final BaseActivity context) { super(); mContext = context; mItems = new ArrayList<FeedItem>(); } @Override public int getCount() { return mItems.size(); } @Override public FeedItem getItem(int i) { return mItems.get(i); } @Override public long getItemId(int i) { return i; } public int determineDateVisibility(final int position, final DisplayMetrics dm, final float widthThreshold) { if (position == 0) { return VISIBLE; } else if (position > 0 && position < getCount()) { final FeedItem item = getItem(position); final FeedItem lastItem = getItem(position - 1); final boolean sameAsLast = DateUtils .isSameDay(item.getPubDate(), lastItem.getPubDate()); boolean sameAsNext = false; if (position + 1 < getCount()) { sameAsNext = DateUtils .isSameDay(item.getPubDate(), getItem(position + 1).getPubDate()); } if (!sameAsLast) { return VISIBLE; } else if (mContext instanceof VideoGalleryActivity && (mContext.isMultipaned() || dm.widthPixels >= widthThreshold)) { final boolean rightSide = (position + 1) % 2 == 0; if (rightSide && determineDateVisibility(position - 1, dm, widthThreshold) == VISIBLE) { return INVISIBLE; } else if (!rightSide && !sameAsNext) { return INVISIBLE; } } } return GONE; } @Override public View getView(int position, View convertView, ViewGroup parent) { final FeedItem item = getItem(position); ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.feedrow, null); holder = new ViewHolder(); holder.date = (TextView) convertView.findViewById(R.id.tv_date); holder.thumbnail = (ImageView) convertView.findViewById(R.id.iv_thumbnail); holder.metaholder = (LinearLayout) convertView.findViewById(R.id.ll_metaholder); holder.title = (TextView) convertView.findViewById(R.id.tv_title); holder.time = (TextView) convertView.findViewById(R.id.tv_time); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final SimpleDateFormat date = new SimpleDateFormat("MMM d, yyyy"); final SimpleDateFormat time = new SimpleDateFormat("h:mm a"); holder.date.setText(date.format(item.getPubDate())); holder.time.setText(time.format(item.getPubDate())); DisplayMetrics dm = mContext.getResources().getDisplayMetrics(); float widthThreshold = TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 500.0f, dm); holder.date.setVisibility(determineDateVisibility(position, dm, widthThreshold)); if (holder.date.getVisibility() != GONE) { if (DateUtils.isToday(item.getPubDate())) { holder.date.setText(R.string.today); } else if (DateUtils.isYesterday(item.getPubDate())) { holder.date.setText(R.string.yesterday); } } final int widthPixels = dm.widthPixels; final URL thumbnailURL = item.getThumbnail(widthPixels); if (thumbnailURL != null) { /* * Load the thumbnail asynchronously. We get a thumbnail of 320px in width because that * translates exactly to the 160dp we need on XHDPI devices. */ final AQuery aq = new AQuery(mContext); aq.id(holder.thumbnail).image(thumbnailURL.toString(), true, true, widthPixels, 0, null, AQuery.FADE_IN_NETWORK); holder.thumbnail.setVisibility(VISIBLE); holder.metaholder.setBackgroundColor( mContext.getResources().getColor(R.color.feed_meta_dark_background)); holder.title.setTextColor(mContext.getResources().getColor(R.color.wh_blue_lighter)); } else { holder.thumbnail.setVisibility(GONE); holder.metaholder.setBackgroundColor(TRANSPARENT); holder.title.setTextColor(mContext.getResources().getColor(R.color.wh_blue)); } holder.title.setText(item.getTitle()); return convertView; } /** * Replaces the existing items in the adapter with a given collection */ public void fillWithItems(Collection<FeedItem> items) { mItems.clear(); mItems.addAll(items); } /** * Appends a given list of FeedItems to the adapter */ public void appendWithItems(Collection<FeedItem> items) { mItems.addAll(items); } }
36.941748
100
0.657162
77a0b3d9d22f1626dcdf895b3bb904a3a593c49a
783
package designpattern.builder; /** * 具体建造者(服务器) * * @author wangdongxing * @since 2020/9/27 3:32 下午 */ public class WaiterBuilder extends Builder { private Product product; public WaiterBuilder() { this.product = new Product(); } @Override Builder buildA(String mes) { product.setBuildA(mes); return this; } @Override Builder buildB(String mes) { product.setBuildB(mes); return this; } @Override Builder buildC(String mes) { product.setBuildC(mes); return this; } @Override Builder buildD(String mes) { product.setBuildD(mes); return this; } @Override Product build() { return product; } }
17.021739
44
0.559387
77b1e05e3fa81c00328fecf9653f138f705662b0
65
package com.pronix.training.us; public class TaxCalculator { }
10.833333
31
0.769231
465105cca1abcbacfced43f5835892b3fb20e427
1,387
package com.hedera.demo.auction.app.api; import com.hedera.demo.auction.app.domain.Bid; import com.hedera.demo.auction.app.repository.BidsRepository; import io.vertx.core.Handler; import io.vertx.core.json.Json; import io.vertx.ext.web.RoutingContext; import lombok.extern.log4j.Log4j2; import java.sql.SQLException; import java.util.List; /** * Gets all the bids for a given auction id */ @Log4j2 public class GetBidsHandler implements Handler<RoutingContext> { private final BidsRepository bidsRepository; private final int bidsToReturn; GetBidsHandler(BidsRepository bidsRepository, int bidsToReturn) { this.bidsRepository = bidsRepository; this.bidsToReturn = bidsToReturn; } /** * Given an auction id, get the last 50 bids from the database * * @param routingContext the RoutingContext */ @Override public void handle(RoutingContext routingContext) { int auctionId = Integer.parseInt(routingContext.pathParam("auctionid")); try { List<Bid> bids = bidsRepository.getLastBids(auctionId, bidsToReturn); routingContext.response() .putHeader("content-type", "application/json") .end(Json.encodeToBuffer(bids)); } catch (SQLException e) { log.error(e, e); routingContext.fail(500, e); } } }
29.510638
81
0.679164
517af35e4872f378a5d8a2126b77893b172f101d
907
package com.flytxt.security.jwtoauthserver.authBuilder; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; /** * * @author shiju.john * */ @Configuration public class DBAuthenticationBuilder implements AuthenticationType{ @Autowired DataSource dataSource; @Override public void setAuthenticationManager(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().dataSource(dataSource) .usersByUsernameQuery("select username,password, enabled from users where username=?") .authoritiesByUsernameQuery("select username, role from user_roles where username=?"); } }
29.258065
108
0.793826
f35bb6c8bc55ed3b526ce8403d7488dcd8fc5dad
380
package xml.m2; import xml.m0.Tag; public interface EXML<FX,FT,FD> extends xml.m0.XML<FX,FT,FD>, EFactory<FX,FT,FD> { default java.util.Optional<Tag<FX,FT,FD>> asTag() { return java.util.Optional.empty(); } default java.util.Optional<String> validate(Tag<FX,FT,FD> toValidate) { return java.util.Optional.of("Invalid validation request."); } }
25.333333
82
0.668421
2a05e51f9b07196decc198cdde789b8f1dfbb5f7
4,575
package com.google.cloud.hadoop.io.bigquery.mapred; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.apache.hadoop.mapred.JobContext; import org.apache.hadoop.mapred.TaskAttemptContext; import org.apache.hadoop.mapreduce.JobStatus.State; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.IOException; /** * Unit tests for {@link BigQueryMapredOutputCommitter}. */ @RunWith(JUnit4.class) public class BigQueryMapredOutputCommitterTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private JobContext mockJobContext; @Mock private TaskAttemptContext mockTaskAttemptContext; @Mock private org.apache.hadoop.mapreduce.OutputCommitter mockOutputCommitter; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @After public void tearDown() { verifyNoMoreInteractions(mockJobContext); verifyNoMoreInteractions(mockTaskAttemptContext); verifyNoMoreInteractions(mockOutputCommitter); } @Test public void testAbortJob() throws IOException { BigQueryMapredOutputCommitter outputCommitter = new BigQueryMapredOutputCommitter(); int status = 1; outputCommitter.setMapreduceOutputCommitter(mockOutputCommitter); outputCommitter.abortJob(mockJobContext, status); verify(mockOutputCommitter).abortJob( any(JobContext.class), any(State.class)); } @Test public void testAbortJobBadStatus() throws IOException { BigQueryMapredOutputCommitter outputCommitter = new BigQueryMapredOutputCommitter(); int status = -1; outputCommitter.setMapreduceOutputCommitter(mockOutputCommitter); expectedException.expect(IllegalArgumentException.class); outputCommitter.abortJob(mockJobContext, status); } @Test public void testAbortTask() throws IOException { BigQueryMapredOutputCommitter outputCommitter = new BigQueryMapredOutputCommitter(); outputCommitter.setMapreduceOutputCommitter(mockOutputCommitter); outputCommitter.abortTask(mockTaskAttemptContext); verify(mockOutputCommitter).abortTask(any(TaskAttemptContext.class)); } @Test public void testCleanupJob() throws IOException { BigQueryMapredOutputCommitter outputCommitter = new BigQueryMapredOutputCommitter(); outputCommitter.setMapreduceOutputCommitter(mockOutputCommitter); outputCommitter.cleanupJob(mockJobContext); verify(mockOutputCommitter).cleanupJob(any(JobContext.class)); } @Test public void testCommitJob() throws IOException { BigQueryMapredOutputCommitter outputCommitter = new BigQueryMapredOutputCommitter(); outputCommitter.setMapreduceOutputCommitter(mockOutputCommitter); outputCommitter.commitJob(mockJobContext); verify(mockOutputCommitter).commitJob(any(JobContext.class)); } @Test public void testCommitTask() throws IOException { BigQueryMapredOutputCommitter outputCommitter = new BigQueryMapredOutputCommitter(); outputCommitter.setMapreduceOutputCommitter(mockOutputCommitter); outputCommitter.commitTask(mockTaskAttemptContext); verify(mockOutputCommitter).commitTask(any(TaskAttemptContext.class)); } @Test public void testNeedsTaskCommit() throws IOException { BigQueryMapredOutputCommitter outputCommitter = new BigQueryMapredOutputCommitter(); outputCommitter.setMapreduceOutputCommitter(mockOutputCommitter); outputCommitter.needsTaskCommit(mockTaskAttemptContext); verify(mockOutputCommitter).needsTaskCommit(any(TaskAttemptContext.class)); } @Test public void testSetupJob() throws IOException { BigQueryMapredOutputCommitter outputCommitter = new BigQueryMapredOutputCommitter(); outputCommitter.setMapreduceOutputCommitter(mockOutputCommitter); outputCommitter.setupJob(mockJobContext); verify(mockOutputCommitter).setupJob(any(JobContext.class)); } @Test public void testSetupTask() throws IOException { BigQueryMapredOutputCommitter outputCommitter = new BigQueryMapredOutputCommitter(); outputCommitter.setMapreduceOutputCommitter(mockOutputCommitter); outputCommitter.setupTask(mockTaskAttemptContext); verify(mockOutputCommitter).setupTask(any(TaskAttemptContext.class)); } }
33.639706
80
0.794317
1c581ff8519347cb65e3a6d949e2592dec8871c9
2,742
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krad.util; import org.apache.log4j.Logger; import org.apache.ojb.broker.PBKey; import org.apache.ojb.broker.TransactionAbortedException; import org.apache.ojb.broker.TransactionInProgressException; import org.apache.ojb.broker.TransactionNotInProgressException; import org.apache.ojb.broker.core.PersistenceBrokerFactoryIF; import org.apache.ojb.broker.core.PersistenceBrokerImpl; public class KualiPersistenceBrokerImpl extends PersistenceBrokerImpl { private static final Logger LOG = Logger.getLogger(KualiPersistenceBrokerImpl.class); private boolean fresh = true; public KualiPersistenceBrokerImpl(PBKey key, PersistenceBrokerFactoryIF pbf) { super(key, pbf); } public boolean isFresh() { return fresh; } /** * @see org.apache.ojb.broker.core.PersistenceBrokerImpl#beginTransaction() */ public synchronized void beginTransaction() throws TransactionInProgressException, TransactionAbortedException { LOG.debug("beginning transaction for persistenceBroker " + getClass().getName() + "@" + hashCode()); super.beginTransaction(); } /** * @see org.apache.ojb.broker.core.PersistenceBrokerImpl#abortTransaction() */ public synchronized void abortTransaction() throws TransactionNotInProgressException { LOG.debug("aborting transaction for persistenceBroker " + getClass().getName() + "@" + hashCode()); super.abortTransaction(); } /** * @see org.apache.ojb.broker.core.PersistenceBrokerImpl#commitTransaction() */ public synchronized void commitTransaction() throws TransactionNotInProgressException, TransactionAbortedException { LOG.debug("committing transaction for persistenceBroker " + getClass().getName() + "@" + hashCode()); super.commitTransaction(); } /** * @see org.apache.ojb.broker.core.PersistenceBrokerImpl#close() */ public boolean close() { LOG.debug("closing persistenceBroker " + getClass().getName() + "@" + hashCode()); fresh = false; return super.close(); } }
35.153846
120
0.723195
c3efab3c60c8dcea747bd8d67605a79161660841
3,384
// Copyright 2006-2018, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship acknowledged. // Any commercial use must be negotiated with the Office of Technology Transfer // at the California Institute of Technology. // // This software is subject to U. S. export control laws and regulations // (22 C.F.R. 120-130 and 15 C.F.R. 730-774). To the extent that the software // is subject to U.S. export control laws and regulations, the recipient has // the responsibility to obtain export licenses or other export authority as // may be required before exporting such information to foreign countries or // providing access to foreign nationals. // // $Id$ package gov.nasa.pds.tools.validate.content.array; import java.net.URL; import java.util.Arrays; import gov.nasa.pds.tools.label.ExceptionType; import gov.nasa.pds.tools.validate.ContentProblem; import gov.nasa.pds.tools.validate.ProblemDefinition; import gov.nasa.pds.tools.validate.ProblemType; /** * Class that stores problems related to Array data objects. * * @author mcayanan * */ public class ArrayContentProblem extends ContentProblem { private Integer array; private int[] location; /** * Constructor. * * @param exceptionType The severity level. * @param problemType The problem type. * @param message The problem message. * @param source The url of the data file associated with this message. * @param label The url of the label file. * @param array The index of the array associated with this message. * @param location The location associated with the message. */ public ArrayContentProblem(ExceptionType exceptionType, ProblemType problemType, String message, URL source, URL label, int array, int[] location) { this( new ProblemDefinition(exceptionType, problemType, message), source, label, array, location); } /** * Constructor. * * @param defn The problem definition. * @param source The url of the data file associated with this message. * @param label The url of the label file. * @param array The index of the array associated with this message. * @param location The location associated with the message. */ public ArrayContentProblem(ProblemDefinition defn, URL source, URL label, int array, int[] location) { super(defn, source, label); this.array = array; if (location != null) { this.location = location; } else { this.location = null; } } /** * Constructor. * * @param defn The problem definition. * @param source The url of the data file associated with this message. */ public ArrayContentProblem(ProblemDefinition defn, URL source) { this(defn, source, null, -1, null); } /** * @return the index of the array. */ public Integer getArray() { return this.array; } /** * * @return the array location. */ public String getLocation() { String loc = null; if (this.location != null) { loc = Arrays.toString(this.location); if (this.location.length > 1) { loc = loc.replaceAll("\\[", "\\("); loc = loc.replaceAll("\\]", "\\)"); } else { loc = loc.replaceAll("\\[", ""); loc = loc.replaceAll("\\]", ""); } } return loc; } }
29.426087
79
0.66844
1bda45f8289da39b5f23a4680a72d941995bf61e
967
package website.julians.juliansmod.blocks; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import website.julians.juliansmod.JuliansMod; import website.julians.juliansmod.init.ModBlocks; import website.julians.juliansmod.init.ModItems; import website.julians.juliansmod.util.IHasModel; public class BlockBase extends Block implements IHasModel { public BlockBase(String name, Material material) { super(material); setUnlocalizedName(name); setRegistryName(name); setCreativeTab(CreativeTabs.BUILDING_BLOCKS); ModBlocks.BLOCKS.add(this); ModItems.ITEMS.add(new ItemBlock(this).setRegistryName(getRegistryName())); } public void registerModels() { JuliansMod.proxy.registerItemRenderer(Item.getItemFromBlock(this), 0, "inventory"); } }
30.21875
91
0.759049
4fa602a1083dba1a4c4fe10e160219ae580ca4fb
8,675
/* * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ package com.microsoft.azure.sdk.iot.service.transport.amqps; import com.azure.core.credential.AzureSasCredential; import com.azure.core.credential.TokenCredential; import com.microsoft.azure.sdk.iot.service.IotHubServiceClientProtocol; import com.microsoft.azure.sdk.iot.service.Message; import com.microsoft.azure.sdk.iot.service.ProxyOptions; import com.microsoft.azure.sdk.iot.service.Tools; import com.microsoft.azure.sdk.iot.service.exceptions.IotHubException; import lombok.extern.slf4j.Slf4j; import javax.net.ssl.SSLContext; import java.io.IOException; import java.util.Objects; /** * Instance of the QPID-Proton-J BaseHandler class * overriding the events what are needed to handle * high level open, close and send methods. * Initialize and use AmqpsSendHandler class for low level ampqs operations. */ @Slf4j public class AmqpSend { protected final String hostName; protected String userName; protected String sasToken; private TokenCredential credential; private AzureSasCredential sasTokenProvider; protected AmqpSendHandler amqpSendHandler; protected IotHubServiceClientProtocol iotHubServiceClientProtocol; private final ProxyOptions proxyOptions; private final SSLContext sslContext; /** * Constructor to set up connection parameters * @param hostName The address string of the service (example: AAA.BBB.CCC) * @param userName The username string to use SASL authentication (example: user@sas.service) * @param sasToken The SAS token string * @param iotHubServiceClientProtocol protocol to use */ public AmqpSend( String hostName, String userName, String sasToken, IotHubServiceClientProtocol iotHubServiceClientProtocol) { this(hostName, userName, sasToken, iotHubServiceClientProtocol, null); } /** * Constructor to set up connection parameters * @param hostName The address string of the service (example: AAA.BBB.CCC) * @param userName The username string to use SASL authentication (example: user@sas.service) * @param sasToken The SAS token string * @param iotHubServiceClientProtocol protocol to use * @param proxyOptions the proxy options to tunnel through, if a proxy should be used. */ public AmqpSend( String hostName, String userName, String sasToken, IotHubServiceClientProtocol iotHubServiceClientProtocol, ProxyOptions proxyOptions) { this(hostName, userName, sasToken, iotHubServiceClientProtocol, proxyOptions, null); } /** * Constructor to set up connection parameters * @param hostName The address string of the service (example: AAA.BBB.CCC) * @param userName The username string to use SASL authentication (example: user@sas.service) * @param sasToken The SAS token string * @param iotHubServiceClientProtocol protocol to use * @param proxyOptions the proxy options to tunnel through, if a proxy should be used. * @param sslContext the custom SSL context to open the connection with. */ public AmqpSend( String hostName, String userName, String sasToken, IotHubServiceClientProtocol iotHubServiceClientProtocol, ProxyOptions proxyOptions, SSLContext sslContext) { if (Tools.isNullOrEmpty(hostName)) { throw new IllegalArgumentException("hostName can not be null or empty"); } if (Tools.isNullOrEmpty(sasToken)) { throw new IllegalArgumentException("sasToken can not be null or empty"); } if (iotHubServiceClientProtocol == null) { throw new IllegalArgumentException("iotHubServiceClientProtocol cannot be null"); } this.hostName = hostName; this.userName = userName; this.sasToken = sasToken; this.iotHubServiceClientProtocol = iotHubServiceClientProtocol; this.proxyOptions = proxyOptions; this.sslContext = sslContext; } public AmqpSend( String hostName, TokenCredential credential, IotHubServiceClientProtocol iotHubServiceClientProtocol, ProxyOptions proxyOptions, SSLContext sslContext) { if (Tools.isNullOrEmpty(hostName)) { throw new IllegalArgumentException("hostName can not be null or empty"); } Objects.requireNonNull(iotHubServiceClientProtocol); Objects.requireNonNull(credential); this.hostName = hostName; this.credential = credential; this.iotHubServiceClientProtocol = iotHubServiceClientProtocol; this.proxyOptions = proxyOptions; this.sslContext = sslContext; } public AmqpSend( String hostName, AzureSasCredential sasTokenProvider, IotHubServiceClientProtocol iotHubServiceClientProtocol, ProxyOptions proxyOptions, SSLContext sslContext) { if (Tools.isNullOrEmpty(hostName)) { throw new IllegalArgumentException("hostName can not be null or empty"); } Objects.requireNonNull(iotHubServiceClientProtocol); Objects.requireNonNull(sasTokenProvider); this.hostName = hostName; this.sasTokenProvider = sasTokenProvider; this.iotHubServiceClientProtocol = iotHubServiceClientProtocol; this.proxyOptions = proxyOptions; this.sslContext = sslContext; } /** * Create AmqpsSendHandler and store it in a member variable */ @SuppressWarnings("EmptyMethod") public void open() { } /** * Invalidate AmqpsSendHandler member variable */ @SuppressWarnings("EmptyMethod") public void close() { } /** * Create binary message * Initialize and start Proton reactor * Send the created message * @param deviceId The device name string * @param moduleId The module name string * @param message The message to be sent * @throws IOException This exception is thrown if the AmqpSend object is not initialized * @throws IotHubException If IotHub rejects the message for any reason */ public void send(String deviceId, String moduleId, Message message) throws IOException, IotHubException { synchronized(this) { if (this.credential != null) { amqpSendHandler = new AmqpSendHandler( this.hostName, this.credential, this.iotHubServiceClientProtocol, this.proxyOptions, this.sslContext); } else if (this.sasTokenProvider != null) { amqpSendHandler = new AmqpSendHandler( this.hostName, this.sasTokenProvider, this.iotHubServiceClientProtocol, this.proxyOptions, this.sslContext); } else { amqpSendHandler = new AmqpSendHandler( this.hostName, this.userName, this.sasToken, this.iotHubServiceClientProtocol, this.proxyOptions, this.sslContext); } if (moduleId == null) { amqpSendHandler.createProtonMessage(deviceId, message); log.info("Sending cloud to device message"); } else { amqpSendHandler.createProtonMessage(deviceId, moduleId, message); log.info("Sending cloud to device module message"); } String reactorRunnerPrefix = this.hostName + "-" + "Cxn" + this.amqpSendHandler.getConnectionId(); new ReactorRunner(amqpSendHandler, reactorRunnerPrefix,"AmqpSend").run(); log.trace("Amqp send reactor stopped, checking that the connection opened, and that the message was sent"); amqpSendHandler.verifySendSucceeded(); } } }
36.297071
119
0.628242
22ec68070aeda71db08a4a311dfac57d6fac7cf1
5,386
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.content.crosswalk; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import org.dspace.authorize.AuthorizeException; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.content.MetadataField; import org.dspace.content.MetadataSchemaEnum; import org.dspace.content.MetadataValue; import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.service.ItemService; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.SelfNamedPlugin; import org.jdom.Element; import org.jdom.Namespace; /** * Disseminator for Simple Dublin Core metadata in XML format. * Logic stolen from OAIDCCrosswalk. This is mainly intended * as a proof-of-concept, to use crosswalk plugins in the OAI-PMH * server. * * @author Larry Stone * @version $Revision$ */ public class SimpleDCDisseminationCrosswalk extends SelfNamedPlugin implements DisseminationCrosswalk { // namespaces of interest. // XXX FIXME: may also want http://www.openarchives.org/OAI/2.0/oai_dc/ for OAI private static final Namespace DC_NS = Namespace.getNamespace("dc", "http://purl.org/dc/elements/1.1/"); // simple DC schema for OAI private static final String DC_XSD = "http://dublincore.org/schemas/xmls/simpledc20021212.xsd"; //"http://www.openarchives.org/OAI/2.0/oai_dc.xsd"; private static final String schemaLocation = DC_NS.getURI() + " " + DC_XSD; private static final Namespace namespaces[] = {DC_NS, XSI_NS}; private static final String aliases[] = {"SimpleDC", "DC"}; protected final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); public static String[] getPluginNames() { return (String[]) ArrayUtils.clone(aliases); } @Override public Element disseminateElement(Context context, DSpaceObject dso) throws CrosswalkException, IOException, SQLException, AuthorizeException { Element root = new Element("simpledc", DC_NS); root.setAttribute("schemaLocation", schemaLocation, XSI_NS); root.addContent(disseminateListInternal(dso, false)); return root; } /** * Returns object's metadata as XML elements. * Simple-minded copying of elements: convert contributor.author to * "creator" but otherwise just grab element name without qualifier. * * @param context context * @throws CrosswalkException if crosswalk error * @throws IOException if IO error * @throws SQLException if database error * @throws AuthorizeException if authorization error */ @Override public List<Element> disseminateList(Context context, DSpaceObject dso) throws CrosswalkException, IOException, SQLException, AuthorizeException { return disseminateListInternal(dso, true); } public List<Element> disseminateListInternal(DSpaceObject dso, boolean addSchema) throws CrosswalkException, IOException, SQLException, AuthorizeException { if (dso.getType() != Constants.ITEM) { throw new CrosswalkObjectNotSupported("SimpleDCDisseminationCrosswalk can only crosswalk an Item."); } Item item = (Item) dso; List<MetadataValue> allDC = itemService .getMetadata(item, MetadataSchemaEnum.DC.getName(), Item.ANY, Item.ANY, Item.ANY); List<Element> dcl = new ArrayList<Element>(allDC.size()); for (MetadataValue metadataValue : allDC) { // Do not include description.provenance MetadataField metadataField = metadataValue.getMetadataField(); if (!(metadataField.getElement().equals("description") && (metadataField.getQualifier() != null && metadataField.getQualifier().equals("provenance")))) { String element; // contributor.author exposed as 'creator' if (metadataField.getElement().equals("contributor") && (metadataField.getQualifier() != null) && metadataField.getQualifier().equals("author")) { element = "creator"; } else { element = metadataField.getElement(); } Element field = new Element(element, DC_NS); field.addContent(metadataValue.getValue()); if (addSchema) { field.setAttribute("schemaLocation", schemaLocation, XSI_NS); } dcl.add(field); } } return dcl; } @Override public Namespace[] getNamespaces() { return (Namespace[]) ArrayUtils.clone(namespaces); } @Override public String getSchemaLocation() { return schemaLocation; } @Override public boolean canDisseminate(DSpaceObject dso) { return dso.getType() == Constants.ITEM; } @Override public boolean preferList() { return true; } }
34.974026
112
0.667843
20eabfe64a8533789b0ec7f8b1c215d943e3e1fc
2,320
package ru.majordomo.hms.rc.user.resources; import com.cronutils.descriptor.CronDescriptor; import com.cronutils.model.Cron; import com.cronutils.model.definition.CronDefinition; import com.cronutils.model.definition.CronDefinitionBuilder; import com.cronutils.parser.CronParser; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Locale; public class CronTask { private String execTime; private String execTimeDescription; private String command; private Boolean switchedOn = true; public String getExecTime() { return execTime; } public void setExecTime(String execTime) { CronDescriptor descriptor = CronDescriptor.instance(new Locale("ru")); CronDefinition cronDefinition = CronDefinitionBuilder.defineCron() .withMinutes().and() .withHours().and() .withDayOfMonth().and() .withMonth().and() .withDayOfWeek().withValidRange(0,7).withMondayDoWValue(1).withIntMapping(0,7).and() .enforceStrictRanges() .instance(); CronParser cronParser = new CronParser(cronDefinition); Cron cron = cronParser.parse(execTime); this.execTimeDescription = descriptor.describe(cron); this.execTime = cron.asString(); } @JsonIgnore public void setRawExecTime(String execTime) { this.execTime = execTime; } public String getExecTimeDescription() { return execTimeDescription; } public void setExecTimeDescription(String execTimeDescription) { this.execTimeDescription = execTimeDescription; } public String getCommand() { return command; } public void setCommand(String command) { this.command = command; } public Boolean getSwitchedOn() { return switchedOn; } public void setSwitchedOn(Boolean switchedOn) { this.switchedOn = switchedOn; } public void switchResource() { switchedOn = !switchedOn; } @Override public String toString() { return "CronTask{" + "execTime='" + execTime + '\'' + ", execTimeDescription='" + execTimeDescription + '\'' + ", command='" + command + '\'' + '}'; } }
28.641975
100
0.638362
31e1973c93d4f325eac3a4ffc28cce2225881f2d
1,401
/** * Copyright (C) 2011-2018 ARM Limited. All rights reserved. * SPDX-License-Identifier: Apache-2.0 * 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.mbed.coap.packet; import com.mbed.coap.exception.CoapException; public enum MessageType { Confirmable, NonConfirmable, Acknowledgement, Reset; public static MessageType valueOf(int transactionMessage) throws CoapException { switch (transactionMessage) { case 0: return Confirmable; case 1: return NonConfirmable; case 2: return Acknowledgement; case 3: return Reset; default: throw new CoapException("Wrong transaction message code"); } } @Override public String toString() { return super.toString().substring(0, 3).toUpperCase(); } }
30.456522
84
0.660956
9924d9d7e0adeb62198a153ee3e516a4215a51df
29,871
package com.teradata.connector.common.utils; import com.teradata.connector.common.*; import org.apache.commons.codec.binary.*; import com.teradata.connector.common.exception.*; import java.io.*; import org.apache.commons.codec.binary.Base64; import org.apache.hadoop.hive.serde2.io.*; import java.lang.reflect.*; import java.util.Date; import java.util.regex.*; import org.apache.hadoop.hive.serde2.io.ByteWritable; import org.apache.hadoop.hive.serde2.io.DoubleWritable; import org.apache.hadoop.hive.serde2.io.ShortWritable; import org.codehaus.jackson.map.*; import org.codehaus.jackson.node.*; import org.apache.hadoop.io.*; import java.math.*; import java.util.*; import com.teradata.jdbc.*; import java.sql.*; import com.teradata.connector.common.converter.*; import org.apache.hadoop.conf.*; public class ConnectorSchemaUtils { public static final String PATTERN_MAP_TYPE = "\\s*(map\\s*[<].*[>])"; public static final String PATTERN_ARRAY_TYPE = "\\s*(array\\s*[<].*[>])"; public static final String PATTERN_STRUCT_TYPE = "\\s*(struct\\s*[<].*[>])"; public static final String PATTERN_UNION_TYPE = "\\s*(union\\s*[<].*[>])"; private static final String PATTERN_CALENDAR_TIME_TYPE = "\\s*time\\s*with\\s*time\\s*zone\\s*"; private static final String PATTERN_CALENDAR_TIMESTAMP_TYPE = "\\s*timestamp\\s*with\\s*time\\s*zone\\s*"; protected static final String PATTERN_DECIMAL_TYPE = "\\s*DECIMAL\\s*\\(\\s*(\\d+)\\s*(,\\s*(\\d+)\\s*)?\\)"; protected static final String PATTERN_VARCHAR_TYPE = "\\s*VARCHAR\\s*\\(\\s*(\\d+)\\s*\\)"; protected static final String PATTERN_CHAR_TYPE = "\\s*CHAR\\s*\\(\\s*(\\d+)\\s*\\)"; private static final String PATTERN_DATE_TYPE = "\\s*date"; private static final String PATTERN_TIME_TYPE = "\\s*time"; public static final String LIST_COLUMNS = "columns"; public static final String LIST_COLUMN_TYPES = "columns.types"; private static final char ESCAPE_CHAR = '\\'; private static final char SPACE_CHAR = ' '; private static final char DOT_CHAR = '.'; private static final char COMMA_CHAR = ','; private static final char SINGLE_QUOTE = '\''; private static final char DOUBLE_QUOTE = '\"'; private static final String REPLACE_DOUBLE_QUOTE = "\\\""; private static final String REPLACE_SINGLE_QUOTE = "\\'"; public static List<String> parseColumns(final String schema) { final ConnectorSchemaParser parser = new ConnectorSchemaParser(); parser.setEscapeChar('\\'); return parser.tokenizeKeepEscape(schema); } public static List<String> parseFields(final String fields) { final ConnectorSchemaParser parser = new ConnectorSchemaParser(); parser.setEscapeChar('\\'); return parser.tokenize(fields); } public static List<String> parseColumnNames(final List<String> fields) { final ConnectorSchemaParser parser = new ConnectorSchemaParser(); parser.setDelimChar(' '); parser.setEscapeChar('\\'); parser.setIgnoreContinousDelim(true); final List<String> result = new ArrayList<String>(); for (final String field : fields) { final List<String> tokens = parser.tokenize(field.trim(), 2, false); if (tokens.size() >= 1) { result.add(tokens.get(0).trim().replaceAll("\"", "")); } else { result.add(""); } } return result; } public static List<String> parseColumnTypes(final List<String> fields) { final ConnectorSchemaParser parser = new ConnectorSchemaParser(); parser.setDelimChar(' '); parser.setEscapeChar('\\'); parser.setIgnoreContinousDelim(true); final List<String> result = new ArrayList<String>(); for (final String field : fields) { final List<String> tokens = parser.tokenize(field.trim(), 2, false); if (tokens.size() == 2) { result.add(tokens.get(1).trim()); } else { result.add(""); } } return result; } public static String[] convertFieldNamesToArray(final String fieldNames) { final List<String> fields = parseFields(fieldNames); return fields.toArray(new String[0]); } public static String concatFieldNamesArray(final String[] fieldNamesArray) { if (fieldNamesArray == null || fieldNamesArray.length == 0) { return ""; } final StringBuilder builder = new StringBuilder(); for (final String fieldName : fieldNamesArray) { builder.append(fieldName).append(','); } if (builder.length() > 0) { builder.setLength(builder.length() - 1); } return builder.toString(); } public static String quoteFieldName(final String fieldName) { return quoteFieldName(fieldName, "\\\""); } public static String quoteFieldName(final String fieldName, final String replaceQuoteString) { if (fieldName == null || fieldName.isEmpty()) { return String.format("%c%c", '\"', '\"'); } final ConnectorSchemaParser parser = new ConnectorSchemaParser(); parser.setDelimChar('.'); parser.setEscapeChar('\\'); final List<String> tokens = parser.tokenize(fieldName); final StringBuilder builder = new StringBuilder(); for (String token : tokens) { if (token.length() > 1) { final char begin = token.charAt(0); final char end = token.charAt(token.length() - 1); if ((begin == '\'' || begin == '\"') && begin == end) { token = token.substring(1, token.length() - 1); } } builder.append('\"').append(token.replace(String.valueOf('\"'), replaceQuoteString)).append('\"').append('.'); } if (builder.length() > 0) { builder.setLength(builder.length() - 1); } return builder.toString(); } public static String quoteFieldNames(final String fieldNames) { if (fieldNames == null || fieldNames.isEmpty()) { return ""; } final String[] fieldNamesArray = convertFieldNamesToArray(fieldNames); final String[] quotedFieldNamesArray = quoteFieldNamesArray(fieldNamesArray); final StringBuilder builder = new StringBuilder(); for (final String fieldName : quotedFieldNamesArray) { builder.append(fieldName).append(','); } if (builder.length() > 0) { builder.setLength(builder.length() - 1); } return builder.toString(); } public static String[] quoteFieldNamesArray(final String[] fieldNamesArray) { if (fieldNamesArray == null) { return new String[0]; } final String[] newFieldNamesArray = new String[fieldNamesArray.length]; for (int i = 0; i < newFieldNamesArray.length; ++i) { final String fieldName = fieldNamesArray[i].trim(); newFieldNamesArray[i] = quoteFieldName(fieldName); } return newFieldNamesArray; } public static String quoteFieldValue(final String fieldValue) { return quoteFieldValue(fieldValue, "\\'"); } public static String quoteFieldValue(String fieldValue, final String replaceQuoteString) { if (fieldValue == null || fieldValue.isEmpty()) { return String.format("%c%c", '\'', '\''); } if (fieldValue.length() > 1) { final char begin = fieldValue.charAt(0); final char end = fieldValue.charAt(fieldValue.length() - 1); if ((begin == '\'' || begin == '\"') && begin == end) { fieldValue = fieldValue.substring(1, fieldValue.length() - 1); } } return '\'' + fieldValue.replace(String.valueOf('\''), replaceQuoteString) + '\''; } public static String unquoteFieldValue(final String fieldValue) { return unquoteFieldValue(fieldValue, "\\'"); } public static String unquoteFieldValue(String fieldValue, final String replaceQuoteString) { if (fieldValue == null || fieldValue.isEmpty()) { return ""; } if (fieldValue.length() > 1) { final char begin = fieldValue.charAt(0); final char end = fieldValue.charAt(fieldValue.length() - 1); if ((begin == '\'' || begin == '\"') && begin == end) { fieldValue = fieldValue.substring(1, fieldValue.length() - 1); } } return fieldValue.replace(replaceQuoteString, String.valueOf('\'')); } public static String unquoteFieldName(final String fieldName) { if (fieldName == null || fieldName.isEmpty()) { return ""; } final ConnectorSchemaParser parser = new ConnectorSchemaParser(); parser.setDelimChar('.'); parser.setEscapeChar('\\'); final List<String> tokens = parser.tokenize(fieldName); final StringBuilder builder = new StringBuilder(); for (String token : tokens) { if (token.length() > 1) { final char begin = token.charAt(0); final char end = token.charAt(token.length() - 1); if ((begin == '\'' || begin == '\"') && begin == end) { token = token.substring(1, token.length() - 1); } } token = token.replace("\\\"", String.valueOf('\"')); builder.append(token).append('.'); } if (builder.length() > 0) { builder.setLength(builder.length() - 1); } return builder.toString(); } public static String[] unquoteFieldNamesArray(final String[] fieldNamesArray) { if (fieldNamesArray == null) { return new String[0]; } final String[] newFieldNamesArray = new String[fieldNamesArray.length]; for (int i = 0; i < newFieldNamesArray.length; ++i) { final String fieldName = fieldNamesArray[i].trim(); newFieldNamesArray[i] = unquoteFieldName(fieldName); } return newFieldNamesArray; } public static ConnectorRecordSchema recordSchemaFromString(final String recordSchema) throws ConnectorException { if (recordSchema == null || recordSchema.isEmpty()) { return null; } ByteArrayInputStream input; try { input = new ByteArrayInputStream(Base64.decodeBase64(recordSchema)); } catch (Exception e1) { e1.printStackTrace(); throw new ConnectorException(e1.getMessage(), e1); } final DataInputStream in = new DataInputStream(input); final ConnectorRecordSchema result = new ConnectorRecordSchema(); try { result.readFields(in); } catch (IOException e2) { throw new ConnectorException(e2.getMessage(), e2); } return result; } public static String recordSchemaToString(final ConnectorRecordSchema recordSchema) throws ConnectorException { if (recordSchema == null || recordSchema.getLength() == 0) { return ""; } final ByteArrayOutputStream output = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(output); try { recordSchema.write(out); return Base64.encodeBase64String(output.toByteArray()); } catch (IOException e) { throw new ConnectorException(e.getMessage(), e); } } public static String getHivePathString(final Object object) { if (object instanceof Timestamp) { return new TimestampWritable((Timestamp)object).toString(); } if (object instanceof Double) { return new DoubleWritable((double)object).toString(); } if (object instanceof Float) { return new FloatWritable((float)object).toString(); } if (object instanceof Integer) { return new IntWritable((int)object).toString(); } if (object instanceof Boolean) { return new BooleanWritable((boolean)object).toString(); } if (object instanceof Short) { return new ShortWritable((short)object).toString(); } if (object instanceof Byte) { return new ByteWritable((byte)object).toString(); } if (object instanceof Long) { return new LongWritable((long)object).toString(); } return object.toString(); } public static int[] getHivePartitionMapping(final String[] schemaFieldNames, final String sourcePartitionSchema) throws ConnectorException { final List<String> fields = parseColumns(sourcePartitionSchema); final List<String> fieldNames = parseColumnNames(fields); final Map<String, Integer> columnMap = new HashMap<String, Integer>(); for (int i = 0; i < schemaFieldNames.length; ++i) { columnMap.put(schemaFieldNames[i].toLowerCase(), i); } final int[] mapping = new int[fieldNames.size()]; for (int j = 0; j < fieldNames.size(); ++j) { final Integer position = columnMap.get(fieldNames.get(j).trim().toLowerCase()); if (position == null) { throw new ConnectorException(14005); } mapping[j] = position; } return mapping; } public static ConnectorDataTypeConverter lookupUDF(final ConnectorRecordSchema sourceRecordSchema, final int i) throws ConnectorException { try { final Class<?> baseClass = ConnectorDataTypeConverter.class; String converterClassString = sourceRecordSchema.getDataTypeConverter(i); if (!converterClassString.contains(".")) { converterClassString = baseClass.getName() + "$" + sourceRecordSchema.getDataTypeConverter(i); } Class<?> converterClass; try { converterClass = Class.forName(converterClassString); } catch (ClassNotFoundException e8) { converterClass = Class.forName(sourceRecordSchema.getDataTypeConverter(i)); } final Constructor<?>[] constructors2; final Constructor<?>[] constructors = constructors2 = converterClass.getConstructors(); for (final Constructor<?> constructor : constructors2) { final Class<?>[] parameterTypes = constructor.getParameterTypes(); final int parameterLength = sourceRecordSchema.getParameters(i).length; if (parameterTypes.length == parameterLength) { int j; for (j = 0; j < parameterLength && parameterTypes[j].isAssignableFrom(String.class); ++j) {} if (j == parameterLength && baseClass.isAssignableFrom(converterClass)) { return (ConnectorDataTypeConverter)constructor.newInstance((Object[])sourceRecordSchema.getParameters(i)); } } } return null; } catch (SecurityException e) { throw new ConnectorException(e.getMessage(), e); } catch (ConnectorException e2) { throw new ConnectorException(e2.getMessage(), e2); } catch (ClassNotFoundException e3) { throw new ConnectorException(e3.getMessage(), e3); } catch (IllegalArgumentException e4) { throw new ConnectorException(e4.getMessage(), e4); } catch (InstantiationException e5) { throw new ConnectorException(e5.getMessage(), e5); } catch (IllegalAccessException e6) { throw new ConnectorException(e6.getMessage(), e6); } catch (InvocationTargetException e7) { throw new ConnectorException(e7.getMessage(), e7); } } public static int convertNullDataTypeByName(String typeName) throws ConnectorException { typeName = typeName.toUpperCase(); if (typeName.equals("INT") || typeName.equals("INTEGER")) { return 4; } if (typeName.equals("BIGINT") || typeName.equals("LONG")) { return -5; } if (typeName.equals("SMALLINT")) { return 5; } if (typeName.equals("STRING")) { return 12; } if (Pattern.matches("\\s*VARCHAR\\s*\\(\\s*(\\d+)\\s*\\)", typeName)) { return 12; } if (typeName.equals("DATE")) { return 91; } if (Pattern.matches("\\s*CHAR\\s*\\(\\s*(\\d+)\\s*\\)", typeName)) { return 1; } if (typeName.equals("DOUBLE") || typeName.equals("DOUBLE PRECISION")) { return 8; } if (typeName.equals("BOOLEAN")) { return 16; } if (typeName.equals("TIMESTAMP")) { return 93; } if (typeName.equals("MAP") || Pattern.matches("\\s*(map\\s*[<].*[>])", typeName.toLowerCase())) { return -1000; } if (typeName.equals("ARRAY") || Pattern.matches("\\s*(array\\s*[<].*[>])", typeName.toLowerCase())) { return -1001; } if (typeName.equals("STRUCT") || Pattern.matches("\\s*(struct\\s*[<].*[>])", typeName.toLowerCase())) { return -1002; } if (typeName.equals("TINYINT")) { return -6; } if (typeName.equals("FLOAT")) { return 6; } if (typeName.equals("BINARY")) { return -2; } if (typeName.equals("DECIMAL") || Pattern.matches("\\s*DECIMAL\\s*\\(\\s*(\\d+)\\s*(,\\s*(\\d+)\\s*)?\\)", typeName)) { return 3; } throw new ConnectorException(14006, new Object[] { typeName }); } public static int lookupDataTypeAndValidate(String typeName) throws ConnectorException { typeName = typeName.toUpperCase(); if (typeName.equals("INT") || typeName.equals("INTEGER")) { return 4; } if (typeName.equals("BIGINT") || typeName.equals("LONG")) { return -5; } if (typeName.equals("SMALLINT")) { return 5; } if (typeName.equals("STRING") || typeName.equals("VARCHAR")) { return 12; } if (typeName.equals("FLOAT")) { return 6; } if (typeName.equals("DOUBLE") || typeName.equals("DOUBLE PRECISION")) { return 8; } if (typeName.equals("DECIMAL")) { return 3; } if (typeName.equals("BOOLEAN")) { return 16; } if (typeName.equals("DATE")) { return 91; } if (typeName.equals("TIME")) { return 92; } if (typeName.equals("TIMESTAMP")) { return 93; } if (Pattern.matches("\\s*time\\s*with\\s*time\\s*zone\\s*", typeName.toLowerCase())) { return 1885; } if (Pattern.matches("\\s*timestamp\\s*with\\s*time\\s*zone\\s*", typeName.toLowerCase())) { return 1886; } if (typeName.startsWith("PERIOD")) { return 2002; } if (typeName.startsWith("INTERVAL")) { return 1111; } if (typeName.equals("CHAR")) { return 1; } if (typeName.equals("MAP") || Pattern.matches("\\s*(map\\s*[<].*[>])", typeName.toLowerCase())) { return 12; } if (typeName.equals("ARRAY") || Pattern.matches("\\s*(array\\s*[<].*[>])", typeName.toLowerCase())) { return 12; } if (typeName.equals("STRUCT") || typeName.equals("RECORD") || Pattern.matches("\\s*(struct\\s*[<].*[>])", typeName.toLowerCase())) { return 12; } if (typeName.equals("TINYINT")) { return -6; } if (typeName.equals("LONGVARCHAR")) { return -1; } if (typeName.equals("CLOB")) { return 2005; } if (typeName.equals("BLOB")) { return 2004; } if (typeName.equals("BINARY") || typeName.equals("VARBINARY") || typeName.equals("BYTES")) { return -2; } if (typeName.equals("REAL")) { return 8; } if (typeName.equals("ENUM")) { return 12; } if (typeName.equals("NULL")) { return 12; } if (typeName.equals("UNION")) { return 1882; } if (typeName.equals("FIXED")) { return 12; } if (typeName.equals("NUMERIC")) { return 3; } if (typeName.equals("OTHER")) { return 1882; } return 1883; } public static String[] getUdfParameters(final String udf) { final int start = udf.indexOf("("); final int end = udf.indexOf(")"); if (start == -1 || end == -1) { return new String[] { "" }; } if (end - start == 1) { return new String[0]; } final String parameters = udf.substring(start + 1, end); return parameters.split(","); } public static String[] fieldNamesFromJson(final String fieldNamesJson) { if (fieldNamesJson == null || fieldNamesJson.trim().length() == 0) { return new String[0]; } String[] fieldNames = new String[0]; try { final ObjectMapper objectMapper = new ObjectMapper(); final Map<String, Object> tableMap = (Map<String, Object>)objectMapper.readValue(fieldNamesJson, (Class)Map.class); final String database = (String) tableMap.get("database"); final String table = (String) tableMap.get("table"); final ArrayList<Map<String, Object>> columnList = (ArrayList<Map<String, Object>>) tableMap.get("columns"); fieldNames = new String[columnList.size()]; for (int i = 0; i < columnList.size(); ++i) { final Map<String, Object> columnMap = columnList.get(i); fieldNames[i] = (String) columnMap.get("name"); } } catch (Exception ex) {} return fieldNames; } public static String fieldNamesToJson(final String[] fieldNames) { final ObjectMapper objectMapper = new ObjectMapper(); final ObjectNode table = objectMapper.createObjectNode(); table.put("database", ""); table.put("table", ""); final ArrayNode columns = table.putArray("columns"); for (int i = 0; i < fieldNames.length; ++i) { final ObjectNode column = columns.addObject(); column.put("name", fieldNames[i]); } return table.toString(); } public static boolean isConnectorDefinitionDataType(final int type) { return type == 4 || type == -5 || type == 5 || type == -6 || type == 6 || type == 7 || type == 8 || type == 16 || type == 2 || type == 3 || type == 2005 || type == 2004 || type == 1 || type == 12 || type == -1 || type == -2 || type == -3 || type == 91 || type == 92 || type == 93 || type == 2003 || type == 2002 || type == 1111 || type == 1882 || type == 1885 || type == 1886 || type == 1883; } public static ConnectorRecordSchema formalizeConnectorRecordSchema(final ConnectorRecordSchema r) throws ConnectorException { for (int i = 0; i < r.getLength(); ++i) { if (!isConnectorDefinitionDataType(r.getFieldType(i))) { r.setFieldType(i, 12); } } return r; } public static int getWritableObjectType(final Object object) throws ConnectorException { if (object instanceof IntWritable) { return 4; } if (object instanceof LongWritable) { return -5; } if (object instanceof ShortWritable) { return 5; } if (object instanceof ByteWritable) { return -6; } if (object instanceof FloatWritable) { return 6; } if (object instanceof DoubleWritable) { return 7; } if (object instanceof BooleanWritable) { return 16; } if (object instanceof ConnectorDataWritable.BigDecimalWritable) { return 2; } if (object instanceof ConnectorDataWritable.ClobWritable) { return 2005; } if (object instanceof ConnectorDataWritable.BlobWritable) { return 2004; } if (object instanceof Text) { return 12; } if (object instanceof BytesWritable) { return -2; } if (object instanceof ConnectorDataWritable.DateWritable) { return 91; } if (object instanceof ConnectorDataWritable.TimeWritable) { return 92; } if (object instanceof TimestampWritable) { return 93; } if (object instanceof ConnectorDataWritable.PeriodWritable) { return 2002; } if (object instanceof ConnectorDataWritable.CalendarWritable) { return 1886; } throw new ConnectorException(15028, new Object[] { object.getClass() }); } public static int getGenericObjectType(final Object object) { if (object == null) { return 1884; } if (object instanceof Integer) { return 4; } if (object instanceof Long) { return -5; } if (object instanceof Short) { return 5; } if (object instanceof Byte) { return -6; } if (object instanceof Float) { return 6; } if (object instanceof Double) { return 7; } if (object instanceof Boolean) { return 16; } if (object instanceof BigDecimal) { return 2; } if (object instanceof Clob) { return 2005; } if (object instanceof Blob) { return 2004; } if (object instanceof String) { return 12; } if (object instanceof byte[]) { return -2; } if (object instanceof Date) { return 91; } if (object instanceof Time) { return 92; } if (object instanceof Timestamp) { return 93; } if (object instanceof Calendar) { return 1886; } if (object instanceof ResultStruct) { final ResultStruct rs = (ResultStruct)object; try { if (rs.getSQLTypeName().startsWith("PERIOD")) { return 2002; } } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } } return 12; } public static Map<Long, ConnectorDataTypeConverter> constructConvertMap(final ConnectorConverter connectorConverter, final Configuration configuration, final int targetScale, final int targetPrecision, final int targetLength) throws ConnectorException { final int[] connectorType = { 4, -5, 5, -6, 6, 7, 8, 16, 2, 3, 2005, 2004, 1, 12, -1, -2, -3, 91, 92, 93, 2003, 2002, 1111, 1885, 1886 }; final Map<Integer, Object> defaultVal = connectorConverter.initializeDefaultValue(); final Map<Integer, Object> falseDefVal = connectorConverter.initializeFalseDefaultValue(); final Map<Integer, Object> trueDefVal = connectorConverter.initializeTrueDefaultValue(); final Map<Long, ConnectorDataTypeConverter> map = new HashMap<Long, ConnectorDataTypeConverter>(); for (int i = 0; i < connectorType.length; ++i) { final int sourceType = connectorType[i]; for (int j = 0; j < connectorType.length; ++j) { final int targetType = connectorType[j]; final long mapKey = genConnectorMapKey(sourceType, targetType); if (map.get(mapKey) != null) { throw new ConnectorException(15027); } try { final ConnectorDataTypeConverter c = connectorConverter.lookupDataTypeConverter(sourceType, targetType, targetScale, targetPrecision, targetLength, defaultVal, falseDefVal, trueDefVal, configuration); map.put(mapKey, c); } catch (ConnectorException e) {} } } return map; } public static long genConnectorMapKey(int sourceType, int targetType) { if (sourceType < 0) { sourceType = -1 * sourceType * 100000; } if (targetType < 0) { targetType = -1 * targetType * 10000; } return sourceType * 1000000000 + targetType; } public static boolean isTimeWithTimeZoneType(final String typeName) { return Pattern.matches("\\s*time\\s*with\\s*time\\s*zone\\s*", typeName.toLowerCase()); } public static boolean isTimestampWithTimeZoneType(final String typeName) { return Pattern.matches("\\s*timestamp\\s*with\\s*time\\s*zone\\s*", typeName.toLowerCase()); } public static boolean isDateType(final String typeName) { return Pattern.matches("\\s*date", typeName.toLowerCase()); } public static boolean isTimeType(final String typeName) { return Pattern.matches("\\s*time", typeName.toLowerCase()); } }
38.793506
400
0.56677
e0f1e0874f7469d840b07b407bffb9f366535592
1,092
package me.egg82.tcpp.api.trolls; import co.aikar.commands.CommandIssuer; import me.egg82.tcpp.api.BukkitTroll; import me.egg82.tcpp.api.TrollType; import me.egg82.tcpp.enums.Message; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import java.util.UUID; public class SwapTroll extends BukkitTroll { private UUID playerID2; public SwapTroll(UUID playerID, UUID playerID2, TrollType type) { super(playerID, type); this.playerID2 = playerID2; } public void start(CommandIssuer issuer) throws Exception { Player player = Bukkit.getPlayer(playerID); Player player2 = Bukkit.getPlayer(playerID2); if (player == null || player2 == null) { api.stopTroll(this, issuer); return; } Location loc = player.getLocation(); player.teleportAsync(player2.getLocation()); player2.teleportAsync(loc); issuer.sendInfo(Message.SWAP__START, "{player}", player.getName(), "{player2}", player2.getName()); api.stopTroll(this, issuer); } }
30.333333
107
0.680403
108e9399cab4c18e9b407ab85752715db0f526f9
997
package cn.hikyson.godeye.core.internal.modules.sm.core; /** * Created by kysonchao on 2017/11/22. */ public class ShortBlockInfo { //卡顿开始时间 public long timeStart; //卡顿结束时间 public long timeEnd; public long threadTimeCost; public long blockTime; public MemoryInfo memoryDetailInfo; public ShortBlockInfo(long timeStart, long timeEnd, long threadTimeCost, long blockTime, MemoryInfo memoryDetailInfo) { this.timeStart = timeStart; this.timeEnd = timeEnd; this.threadTimeCost = threadTimeCost; this.blockTime = blockTime; this.memoryDetailInfo = memoryDetailInfo; } @Override public String toString() { return "ShortBlockInfo{" + "timeStart=" + timeStart + ", timeEnd=" + timeEnd + ", threadTimeCost=" + threadTimeCost + ", blockTime=" + blockTime + ", memoryDetailInfo=" + memoryDetailInfo + '}'; } }
28.485714
123
0.613842
a28b37531ea05d0a9a55e78aba9c3c1585b6c096
3,203
package lv.kauguri.iepirkumi.files; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.function.BiConsumer; import java.util.stream.Stream; import static lv.kauguri.iepirkumi.Iepirkumi.SEP; import static lv.kauguri.iepirkumi.Iepirkumi.WORK_DIR; public class FileOperations { public static void createIfNeeded(String dirPath) throws IOException { createIfNeeded(new File(dirPath)); } public static void createIfNeeded(File dir) throws IOException { if(!dir.exists()) { dir.mkdir(); } } public static void forceDelete(File file) { if(file.isDirectory()) { for(File child : file.listFiles()) { forceDelete(child); } file.delete(); } else { file.delete(); } } public static String readFile(File file) { try { String content = readFile(file.getCanonicalPath()); return content; } catch (IOException e) { e.printStackTrace(); } return null; } public static String readFile(String path) { try { String content = new String(Files.readAllBytes(Paths.get(path))); return content; } catch (IOException e) { e.printStackTrace(); } return null; } public static void writeFile(Path path, String contents) { try { Files.write(path, contents.getBytes()); } catch (IOException e) { e.printStackTrace(); } } public static void visitEachSubSubDirectory(String dir, BiConsumer<String, String> consumer) { File xmlDir = new File(dir); for(File yearDir : xmlDir.listFiles()) { for (File monthDir : yearDir.listFiles()) { try { consumer.accept(yearDir.getName(), monthDir.getName()); } catch (Exception e) { e.printStackTrace(); } } } } public static List<Dir> visitEachSubSubDirectory2(String dir) { List<Dir> dirList = new ArrayList<>(); File xmlDir = new File(dir); for(File yearDir : xmlDir.listFiles()) { for (File monthDir : yearDir.listFiles()) { dirList.add(new Dir(yearDir.getName(), monthDir.getName())); } } return dirList; } public static String getDir(String dir, String year, String month) { return dir + SEP + year + SEP + month; } public static void run(String command) { Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec(command); InputStream is = process.getInputStream(); int i = 0; while( (i = is.read() ) != -1) { // System.out.print((char)i); } process.waitFor(); } catch (InterruptedException | IOException e) { e.printStackTrace(); } } }
27.852174
98
0.564471
0d25c0b66bdac2f5f3ac3f46377cfef97bb410a7
3,276
/* * (C) Copyright 2016 Nuxeo SA (http://nuxeo.com/) and others. * * 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. * * Contributors: */ package org.nuxeo.ecm.platform.rendition.automation; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.nuxeo.ecm.automation.core.Constants; import org.nuxeo.ecm.automation.core.annotations.Operation; import org.nuxeo.ecm.automation.core.annotations.OperationMethod; import org.nuxeo.ecm.automation.core.annotations.Param; import org.nuxeo.ecm.core.api.Blob; import org.nuxeo.ecm.core.api.Blobs; import org.nuxeo.ecm.platform.rendition.service.RenditionDefinition; import org.nuxeo.ecm.platform.rendition.service.RenditionService; import org.nuxeo.ecm.platform.ui.select2.common.Select2Common; import org.nuxeo.runtime.api.Framework; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * @since 8.3 */ @Operation(id = SuggestRenditionDefinitionEntry.ID, category = Constants.CAT_SERVICES, label = "Get rendition definition suggestion", description = "Get rendition definition suggestion") public class SuggestRenditionDefinitionEntry { public static final String ID = "RenditionDefinition.Suggestion"; public static final int MAX_SUGGESTIONS = 10; public static final Comparator<RenditionDefinition> LABEL_COMPARATOR = new RenditionDefinitionComparator(); @Param(name = "searchTerm", required = false) protected String searchTerm; @OperationMethod public Blob run() { JSONArray result = new JSONArray(); if (!StringUtils.isBlank(searchTerm)) { for (RenditionDefinition def : getSuggestions(searchTerm)) { JSONObject obj = new JSONObject(); String name = def.getName(); obj.element(Select2Common.ID, name); obj.element(Select2Common.LABEL, name); result.add(obj); } } return Blobs.createJSONBlob(result.toString()); } protected List<RenditionDefinition> getSuggestions(String searchTerm) { RenditionService renditionService = Framework.getService(RenditionService.class); List<RenditionDefinition> defs = renditionService.getDeclaredRenditionDefinitions(); return defs.stream().filter(def -> def.getName().startsWith(searchTerm)).sorted(LABEL_COMPARATOR).limit( MAX_SUGGESTIONS).collect(Collectors.toList()); } protected static class RenditionDefinitionComparator implements Comparator<RenditionDefinition> { @Override public int compare(RenditionDefinition o1, RenditionDefinition o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } } }
39
186
0.729548
d42457a9f16427fb47a8fd71df047cbc97c112f9
814
package T09regularExpressions.moreExercises; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; public class P02RageQuitv2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String input = scan.nextLine(); Pattern pattern = Pattern.compile("([^\\d]+)([\\d]{1,2})"); Matcher matcher = pattern.matcher(input); StringBuilder output = new StringBuilder(); while (matcher.find()) { IntStream.range(0, Integer.parseInt(matcher.group(2))) .mapToObj(i -> matcher.group(1).toUpperCase()).forEach(output::append); } System.out.printf("Unique symbols used: %d%n%s", output.chars().distinct().count(), output); } }
37
100
0.644963
150c15434b0b50f3ff18518d9c2798179625fc2c
6,409
package com.jlkj.project.ws.intelligence.mapper; import com.jlkj.project.ws.domain.WsProject; import com.jlkj.project.ws.intelligence.domain.WsElevatorDriverInfo; import com.jlkj.project.ws.intelligence.domain.WsElevatorManager; import com.jlkj.project.ws.intelligence.domain.WsElevatorManagerDTO; import com.jlkj.project.ws.intelligence.domain.vo.WsElevatorManagerStatisticsVO; import com.jlkj.project.ws.intelligence.domain.vo.WsElevatorManagerVO; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 施工电梯设备管理Mapper接口 * * @author liujie * @date 2020-07-03 */ public interface WsElevatorManagerMapper { /** * 查询施工电梯设备管理 * * @param id 施工电梯设备管理ID * @return 施工电梯设备管理 */ public WsElevatorManager selectWsElevatorManagerById(Integer id); /** * 查询施工电梯设备管理列表 * * @param wsElevatorManager 施工电梯设备管理,dataScope 数据范围 * @return 施工电梯设备管理集合 */ public List<WsElevatorManagerVO> selectWsElevatorManagerList(@Param("wsElevatorManager") WsElevatorManager wsElevatorManager,@Param("dataScope") List<WsProject> dataScope); /** * 新增施工电梯设备管理 * * @param wsElevatorManager 施工电梯设备管理 * @return 结果 */ public int insertWsElevatorManager(WsElevatorManager wsElevatorManager); /** * 修改施工电梯设备管理 * * @param wsElevatorManager 施工电梯设备管理 * @return 结果 */ public int updateWsElevatorManager(WsElevatorManager wsElevatorManager); /** * 删除施工电梯设备管理 * * @param id 施工电梯设备管理ID * @return 结果 */ public int deleteWsElevatorManagerById(Integer id); /** * 批量删除施工电梯设备管理 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteWsElevatorManagerByIds(Integer[] ids); /** * @Author liujie * @Description 施工电梯设备管理集合 * @Date 2020/7/3 23:16 * @Param [ElevatorManager],dataScope 数据范围 * @Return java.util.List<com.jlkj.project.ws.intelligence.domain.WsElevatorManagerVO> **/ List<WsElevatorManagerVO> selectWsElevatorManagerVOList(@Param("wsElevatorManager") WsElevatorManager wsElevatorManager,@Param("dataScope") List<WsProject>dataScope); /** * @Author liujie * @Description 获取施工电梯设备列表 * @Date 2020/7/9 18:08 * @Param [wsElevatorManagerDTO],dataScope 数据范围 * @Return java.util.List<com.jlkj.project.ws.intelligence.domain.vo.WsElevatorManagerVO> **/ List<WsElevatorManagerVO> selectWsElevatorManagerVOListByDTO(@Param("wsElevatorManagerDTO") WsElevatorManagerDTO wsElevatorManagerDTO,@Param("dataScope") List<WsProject> dataScope); /** * @Author liujie * @Description //获取进出场列表selectWsElevatorManagerVOListByDTO * @Date 2020/7/10 9:41 * @Param [wsElevatorManagerDTO],dataScope数据范围 * @Return java.util.List<com.jlkj.project.ws.intelligence.domain.vo.WsElevatorManagerVO> **/ List<WsElevatorManagerVO> selectInAndOutList(@Param("wsElevatorManagerDTO") WsElevatorManagerDTO wsElevatorManagerDTO,@Param("dataScope") List<WsProject> dataScope); /** * @Author liujie * @Description 查询升降机监控设备列表 * @Date 2020/7/13 15:51 * @Param [wsElevatorManagerDTO],dataScope数据范围 * @Return java.util.List<com.jlkj.project.ws.intelligence.domain.vo.WsElevatorManagerVO> **/ List<WsElevatorManagerVO> selectWsElevatorMonitorDeviceListByDTO(@Param("wsElevatorManagerDTO") WsElevatorManagerDTO wsElevatorManagerDTO,@Param("dataScope") List<WsProject> dataScope); /** * @Author liujie * @Description 获取人脸认证司机详情列表 * @Date 2020/7/13 20:45 * @Param [wsElevatorDriverInfo] * @Return java.util.List<com.jlkj.project.ws.intelligence.domain.WsElevatorDriverInfo> **/ List<WsElevatorDriverInfo> selectDriverRecognitionListByDriver(WsElevatorDriverInfo wsElevatorDriverInfo); /** * @Author liujie * @Description 获取最新人员认证信息 * @Date 2020/7/13 20:47 * @Param [serialNumber] * @Return com.jlkj.project.ws.intelligence.domain.WsElevatorDriverInfo **/ WsElevatorDriverInfo findNewestRecognitionBySerialNumber(@Param("serialNumber") String serialNumber); /** * @Author liujie * @Description 获取所有设备统计数据 * @Date 2020/7/14 16:58 * @Param [wsElevatorManagerDTO] * @Return com.jlkj.project.ws.intelligence.domain.vo.WsElevatorManagerStatisticsVO **/ WsElevatorManagerStatisticsVO statisticsAllDeviceData(@Param("wsElevatorManagerDTO") WsElevatorManagerDTO wsElevatorManagerDTO,@Param("dataScope") List<WsProject> dataScope); /** * @Author liujie * @Description 获取区域下的升降机设备列表 * @Date 2020/7/23 10:59 * @Param [wsElevatorManagerDTO] * @Return java.util.List<com.jlkj.project.ws.intelligence.domain.vo.WsElevatorManagerVO> **/ List<WsElevatorManagerVO> selectDeviceListByArea(@Param("wsElevatorManagerDTO") WsElevatorManagerDTO wsElevatorManagerDTO,@Param("dataScope") List<WsProject> dataScope); /** * @Author liujie * @Description 获取监控设备序列号列表 * @Date 2020/7/28 9:18 * @Param [wsElevatorManagerDTO] * @Return java.util.List<java.lang.String> **/ List<String> selectMonitorDeviceSerialNumberList (WsElevatorManagerDTO wsElevatorManagerDTO); /** * @Author liujie * @Description 获取项目设备统计列表 * @Date 2020/7/28 9:21 * @Param [wsElevatorManagerDTO],dataScope数据范围 * @Return java.util.List<com.jlkj.project.ws.intelligence.domain.vo.WsElevatorManagerStatisticsVO> **/ List<WsElevatorManagerStatisticsVO> statisticsProjectDeviceList(@Param("wsElevatorManagerDTO") WsElevatorManagerDTO wsElevatorManagerDTO,@Param("dataScope") List<WsProject> dataScope); /** * @Author liujie * @Description 批量更新 * @Date 2020/8/25 11:00 * @Param [elevators] * @Return int **/ int batchUpdate(List<WsElevatorManager> elevators); /** * @Author liujie * @Description 删除设备标记点位 * @Date 2020/8/26 23:45 * @Param [id] * @Return int **/ int unSignPoint(Integer id); /** * @Author liujie * @Description 统计升降机数量 * @Date 2020/8/28 11:46 * @Param [wsElevatorManager] * @Return int **/ int countWsElevatorManager(WsElevatorManager wsElevatorManager); }
34.272727
191
0.68591
04dc394aee88c9a43b7d092c6375eaf2da7294e9
1,906
package com.beeceptor.tests.models; import com.google.gson.annotations.SerializedName; /** * Created by @Boki on Mar, 2020 */ public class User { @SerializedName("birthDate") private String mBirthDate; @SerializedName("email") private String mEmail; @SerializedName("firstName") private String mFirstName; @SerializedName("lastName") private String mLastName; @SerializedName("loginName") private String mLoginName; @SerializedName("mobileNumber") private String mMobileNumber; @SerializedName("password") private String mPassword; @SerializedName("salutation") private String mSalutation; public String getBirthDate() { return mBirthDate; } public void setBirthDate(String birthDate) { mBirthDate = birthDate; } public String getEmail() { return mEmail; } public void setEmail(String email) { mEmail = email; } public String getFirstName() { return mFirstName; } public void setFirstName(String firstName) { mFirstName = firstName; } public String getLastName() { return mLastName; } public void setLastName(String lastName) { mLastName = lastName; } public String getLoginName() { return mLoginName; } public void setLoginName(String loginName) { mLoginName = loginName; } public String getMobileNumber() { return mMobileNumber; } public void setMobileNumber(String mobileNumber) { mMobileNumber = mobileNumber; } public String getPassword() { return mPassword; } public void setPassword(String password) { mPassword = password; } public String getSalutation() { return mSalutation; } public void setSalutation(String salutation) { mSalutation = salutation; } }
20.717391
54
0.645855
e2af2a0ecf8d1d9082308f869ad6c1059c8fcca0
540
package com.attendance.data.model; import java.util.Date; public class Attendence { private String date; private boolean present; public Attendence(String date, boolean present) { this.date = date; this.present = present; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public boolean isPresent() { return present; } public void setPresent(boolean present) { this.present = present; } }
18
53
0.612963
550af0ae5ac3b4373e63c925d18089b464c72a9a
1,951
package net.cabezudo.sofia.core.schedule; import java.util.Objects; /** * @author <a href="http://cabezudo.net">Esteban Cabezudo</a> * @version 0.01.00, 2020.09.16 */ public class Hour implements Comparable<Hour> { private final int time; private final int hour; private final int minutes; private final int seconds; public Hour(String time) { // TODO check time and values String[] parts = time.split(":"); this.hour = Integer.parseInt(parts[0]); this.minutes = Integer.parseInt(parts[1]); if (parts.length > 2) { this.seconds = Integer.parseInt(parts[2]); } else { this.seconds = 0; } this.time = ((hour * 60) + minutes) * 60 + seconds; } public Hour(int time) { this.time = time; int secondsRemaind = time / 60; seconds = time % 60; int minutesRemaind = secondsRemaind / 60; minutes = minutesRemaind % 60; int houresRemaind = minutesRemaind / 60; hour = houresRemaind % 60; } public Hour(int hour, int minutes, int seconds) { this.hour = hour; this.minutes = minutes; this.seconds = seconds; this.time = ((hour * 60) + minutes) * 60 + seconds; } public int getTime() { return time; } public String toHHmm() { return (hour > 9 ? hour : "0" + hour) + ":" + (minutes > 9 ? minutes : "0" + minutes); } public String toHHmmss() { return (hour > 9 ? hour : "0" + hour) + ":" + (minutes > 9 ? minutes : "0" + minutes) + ":" + (seconds > 9 ? seconds : "0" + seconds); } @Override public int compareTo(Hour h) { if (time < h.time) { return -1; } else { return (time == h.time) ? 0 : 1; } } @Override public boolean equals(Object o) { if (o instanceof Hour) { Hour h = (Hour) o; return time == h.time; } return false; } @Override public int hashCode() { int hash = 7; hash = 53 * hash + Objects.hashCode(this.time); return hash; } }
23.506024
138
0.587904
68dcf3eb187f307498ebff33fbd83baeb0927183
52,435
package camzup.pfriendly; import java.util.Iterator; import camzup.core.Bounds3; import camzup.core.Color; import camzup.core.Curve3; import camzup.core.CurveEntity3; import camzup.core.Experimental; import camzup.core.IUtils; import camzup.core.Knot3; import camzup.core.MaterialSolid; import camzup.core.Mesh3; import camzup.core.MeshEntity3; import camzup.core.Quaternion; import camzup.core.Transform3; import camzup.core.TransformOrder; import camzup.core.Utils; import camzup.core.Vec2; import camzup.core.Vec3; import processing.core.PApplet; import processing.core.PConstants; import processing.core.PGraphics; import processing.core.PMatrix3D; import processing.opengl.PGraphicsOpenGL; /** * An abstract parent class for 3D renderers. */ public abstract class Up3 extends UpOgl implements IUpOgl, IUp3, ITextDisplay2 { /** * A vector to store the x axis (first column) when creating a camera * look-at matrix. */ protected final Vec3 i = Vec3.right(new Vec3()); /** * A vector to store the y axis (second column) when creating a camera * look-at matrix. */ protected final Vec3 j = Vec3.forward(new Vec3()); /** * A vector to store the z axis (third column) when creating a camera * look-at matrix. */ protected final Vec3 k = Vec3.up(new Vec3()); /** * A vector to store the unnormalized look direction when creating a camera * look-at matrix. */ protected final Vec3 lookDir = Vec3.forward(new Vec3()); /** * A vector to store the target at which a camera looks. */ protected final Vec3 lookTarget = new Vec3(); /** * The reference or "world" up vector against which a camera look-at matrix * is created. */ protected final Vec3 refUp = Vec3.up(new Vec3()); /** * The default constructor. */ protected Up3 ( ) {} /** * A constructor for manually initializing the renderer. * * @param width renderer width * @param height renderer height * @param parent parent applet * @param path applet path * @param isPrimary is the renderer primary */ protected Up3 ( final int width, final int height, final PApplet parent, final String path, final boolean isPrimary ) { super(width, height, parent, path, isPrimary); } /** * Begins the heads-up display section of the sketch. Turns off lighting, * disables depth testing and depth masking. Sets the camera origin to the * center of the screen and establishes an orthographic projection. */ @Experimental public void beginHud ( ) { /* * Loose camera variables (cameraX, cameraY, cameraZ, refUp, etc.) should * not be changed, as that would impact default arguments for camera(); * method. This is intended to be a temporary element within draw! */ // QUERY Should there be a boolean flag to signal HUD has begun so that a // warning is thrown if beginHud and endHud aren't called in pairs? final float z = -this.height * IUp.DEFAULT_CAM_DIST_FAC; final float w = 1.0f / Utils.max(128, this.width); final float h = 1.0f / Utils.max(128, this.height); final float d = 1.0f / ( IUp.DEFAULT_FAR_CLIP - IUp.DEFAULT_NEAR_CLIP ); final float am00 = w + w; final float am11 = h + h; final float am22 = - ( d + d ); final float am23 = -d * ( IUp.DEFAULT_FAR_CLIP + IUp.DEFAULT_NEAR_CLIP ); this.disableDepthTest(); this.disableDepthMask(); this.noLights(); this.camera.set(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, z, 0.0f, 0.0f, 0.0f, 1.0f); this.cameraInv.set(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, -z, 0.0f, 0.0f, 0.0f, 1.0f); this.modelview.set(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, z, 0.0f, 0.0f, 0.0f, 1.0f); this.modelviewInv.set(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, -z, 0.0f, 0.0f, 0.0f, 1.0f); this.projection.set(am00, 0.0f, 0.0f, 0.0f, 0.0f, am11, 0.0f, 0.0f, 0.0f, 0.0f, am22, am23, 0.0f, 0.0f, 0.0f, 1.0f); this.projmodelview.set(am00, 0.0f, 0.0f, 0.0f, 0.0f, am11, 0.0f, 0.0f, 0.0f, 0.0f, am22, am22 * z + am23, 0.0f, 0.0f, 0.0f, 1.0f); } /** * Draws a single Bezier curve. * * @param ap0 the first anchor point * @param cp0 the first control point * @param cp1 the second control point * @param ap1 the second anchor point */ @Override public void bezier ( final Vec3 ap0, final Vec3 cp0, final Vec3 cp1, final Vec3 ap1 ) { this.bezier(ap0.x, ap0.y, ap0.z, cp0.x, cp0.y, cp0.z, cp1.x, cp1.y, cp1.z, ap1.x, ap1.y, ap1.z); } /** * Draws a bezier vertex with three vectors: the following control point, * the rear control point of the ensuing point, and the ensuing anchor * point. * * @param cp0 the first control point * @param cp1 the second control point * @param ap1 the next anchor point */ @Override public void bezierVertex ( final Vec3 cp0, final Vec3 cp1, final Vec3 ap1 ) { this.bezierVertexImpl(cp0.x, cp0.y, cp0.z, cp1.x, cp1.y, cp1.z, ap1.x, ap1.y, ap1.z); } /** * Draws a bounding volume * * @param b the bounds */ @Override public void bounds ( final Bounds3 b ) { final Vec3 min = b.min; final float x0 = min.x; final float y0 = min.y; final float z0 = min.z; final Vec3 max = b.max; final float x1 = max.x; final float y1 = max.y; final float z1 = max.z; /* Left. */ this.beginShape(PConstants.POLYGON); this.normalPerShape(-1.0f, 0.0f, 0.0f); this.vertexImpl(x0, y0, z0, 1.0f, 1.0f); this.vertexImpl(x0, y0, z1, 1.0f, 0.0f); this.vertexImpl(x0, y1, z1, 0.0f, 0.0f); this.vertexImpl(x0, y1, z0, 0.0f, 1.0f); this.endShape(PConstants.CLOSE); /* Right. */ this.beginShape(PConstants.POLYGON); this.normalPerShape(1.0f, 0.0f, 0.0f); this.vertexImpl(x1, y1, z0, 1.0f, 1.0f); this.vertexImpl(x1, y1, z1, 1.0f, 0.0f); this.vertexImpl(x1, y0, z1, 0.0f, 0.0f); this.vertexImpl(x1, y0, z0, 0.0f, 1.0f); this.endShape(PConstants.CLOSE); /* Back. */ this.beginShape(PConstants.POLYGON); this.normalPerShape(0.0f, -1.0f, 0.0f); this.vertexImpl(x1, y0, z0, 1.0f, 1.0f); this.vertexImpl(x1, y0, z1, 1.0f, 0.0f); this.vertexImpl(x0, y0, z1, 0.0f, 0.0f); this.vertexImpl(x0, y0, z0, 0.0f, 1.0f); this.endShape(PConstants.CLOSE); /* Front. */ this.beginShape(PConstants.POLYGON); this.normalPerShape(0.0f, 1.0f, 0.0f); this.vertexImpl(x0, y1, z0, 1.0f, 1.0f); this.vertexImpl(x0, y1, z1, 1.0f, 0.0f); this.vertexImpl(x1, y1, z1, 0.0f, 0.0f); this.vertexImpl(x1, y1, z0, 0.0f, 1.0f); this.endShape(PConstants.CLOSE); /* Down. */ this.beginShape(PConstants.POLYGON); this.normalPerShape(0.0f, 0.0f, -1.0f); this.vertexImpl(x0, y1, z0, 0.0f, 1.0f); this.vertexImpl(x1, y1, z0, 1.0f, 1.0f); this.vertexImpl(x1, y0, z0, 1.0f, 0.0f); this.vertexImpl(x0, y0, z0, 0.0f, 0.0f); this.endShape(PConstants.CLOSE); /* Up. */ this.beginShape(PConstants.POLYGON); this.normalPerShape(0.0f, 0.0f, 1.0f); this.vertexImpl(x1, y1, z1, 0.0f, 1.0f); this.vertexImpl(x0, y1, z1, 1.0f, 1.0f); this.vertexImpl(x0, y0, z1, 1.0f, 0.0f); this.vertexImpl(x1, y0, z1, 0.0f, 0.0f); this.endShape(PConstants.CLOSE); } /** * Places the camera on the negative x axis, such that it is looking East * toward the world origin. */ public abstract void camEast ( ); /** * Places camera on the axis perpendicular to its world up axis such that * it is looking North toward the world origin. */ public abstract void camNorth ( ); /** * Places camera on the axis perpendicular to its world up axis such that * it is looking South toward the world origin. */ public abstract void camSouth ( ); /** * Places the camera on the positive x axis, such that it is looking West * toward the world origin. */ public abstract void camWest ( ); /** * Draws a curve between four vectors. * * @param a the first vector * @param b the second vector * @param c the third vector * @param d the fourth vector */ public void curve ( final Vec3 a, final Vec3 b, final Vec3 c, final Vec3 d ) { super.curve(a.x, a.y, a.z, b.x, b.y, b.z, c.x, c.y, c.z, d.x, d.y, d.z); } /** * Draws a curve vertex to a vector. * * @param a the vector. */ public void curveVertex ( final Vec3 a ) { super.curveVertex(a.x, a.y, a.z); } /** * Establishes the default perspective arguments. * * @see PGraphicsOpenGL#defCameraAspect * @see PGraphicsOpenGL#defCameraFOV * @see PGraphicsOpenGL#defCameraNear * @see PGraphicsOpenGL#defCameraFar */ @Override public void defaultPerspective ( ) { this.cameraAspect = this.defCameraAspect = IUp.DEFAULT_ASPECT; this.cameraFOV = this.defCameraFOV = IUp.DEFAULT_FOV; this.cameraNear = this.defCameraNear = IUp.DEFAULT_NEAR_CLIP; this.cameraFar = this.defCameraFar = IUp.DEFAULT_FAR_CLIP; this.ortho(); } /** * Dollies the camera, moving it on its local z axis, backward or forward. * This is done by multiplying the z magnitude by the camera inverse, then * adding the local coordinates to the camera location and look target. * * @param z the z magnitude */ @Override public void dolly ( final float z ) { final float w = this.cameraInv.m32 * z + this.cameraInv.m33; if ( w != 0.0f ) { final float zwInv = z / w; final float xLocal = this.cameraInv.m02 * zwInv; final float yLocal = this.cameraInv.m12 * zwInv; final float zLocal = this.cameraInv.m22 * zwInv; this.camera(this.cameraX + xLocal, this.cameraY + yLocal, this.cameraZ + zLocal, this.lookTarget.x + xLocal, this.lookTarget.y + yLocal, this.lookTarget.z + zLocal, this.refUp.x, this.refUp.y, this.refUp.z); } } /** * Concludes the heads-up display section of the sketch by enabling the * depth mask and depth test. This should happen at the end of a draw call; * any display following this method should call camera and projection * methods and set lights. */ @Experimental public void endHud ( ) { this.enableDepthMask(); this.enableDepthTest(); } /** * Gets the eye distance of the camera. * * @return the eye distance */ public float getEyeDist ( ) { return this.eyeDist; } /** * Gets the x axis of the camera transform. * * @param target the output vector * * @return the x axis */ public Vec3 getI ( final Vec3 target ) { return target.set(this.i); } /** * Gets the y axis of the camera transform. * * @param target the output vector * * @return the y axis */ public Vec3 getJ ( final Vec3 target ) { return target.set(this.j); } /** * Gets the z axis of the camera transform. * * @param target the output vector * * @return the z axis */ public Vec3 getK ( final Vec3 target ) { return target.set(this.k); } /** * Gets the renderer camera's 3D location. * * @param target the output vector * * @return the location */ @Override public Vec3 getLocation ( final Vec3 target ) { return target.set(this.cameraX, this.cameraY, this.cameraZ); } /** * Gets the direction in which the camera is looking. * * @param target the output vector * * @return the look direction */ public Vec3 getLookDir ( final Vec3 target ) { return target.set(this.lookDir); } /** * Gets the point at which the camera is looking. * * @param target the output vector * * @return the look target */ public Vec3 getLookTarget ( final Vec3 target ) { return target.set(this.lookTarget); } /** * Gets the camera's look target x. * * @return the look target x */ @Override public float getLookTargetX ( ) { return this.lookTarget.x; } /** * Gets the camera's look target y. * * @return the look target y */ @Override public float getLookTargetY ( ) { return this.lookTarget.y; } /** * Gets the camera's look target z. * * @return the look target z */ @Override public float getLookTargetZ ( ) { return this.lookTarget.z; } /** * Gets the renderer model view matrix. * * @return the model view */ @Override public PMatrix3D getMatrix ( ) { return this.getMatrix(new PMatrix3D()); } /** * Gets the reference up axis of the camera. * * @param target the output vector * * @return the reference up */ public Vec3 getRefUp ( final Vec3 target ) { return target.set(this.refUp); } /** * Gets the width and height of the renderer as a vector. * * @return the size */ @Override public Vec2 getSize ( final Vec2 target ) { return target.set(this.width, this.height); } /** * Gets the renderer's size. The z component is set to zero. * * @param target the output vector * * @return the size */ public Vec3 getSize ( final Vec3 target ) { return target.set(this.width, this.height, 0.0f); } /** * Displays the handles of a curve entity. The stroke weight is determined * by {@link IUp#DEFAULT_STROKE_WEIGHT}, {@value IUp#DEFAULT_STROKE_WEIGHT} * . * * @param ce the curve entity */ public void handles ( final CurveEntity3 ce ) { this.handles(ce, IUp.DEFAULT_STROKE_WEIGHT); } /** * Displays the handles of a curve entity. * <ul> * <li>The color for lines between handles defaults to * {@link IUp#DEFAULT_HANDLE_COLOR};</li> * <li>the rear handle point, to * {@link IUp#DEFAULT_HANDLE_REAR_COLOR};</li> * <li>the fore handle point, to * {@link IUp#DEFAULT_HANDLE_FORE_COLOR};</li> * <li>the coordinate point, to * {@link IUp#DEFAULT_HANDLE_COORD_COLOR}.</li> * </ul> * * @param ce the curve entity * @param sw the stroke weight */ public void handles ( final CurveEntity3 ce, final float sw ) { this.handles(ce, sw, IUp.DEFAULT_HANDLE_COLOR, IUp.DEFAULT_HANDLE_REAR_COLOR, IUp.DEFAULT_HANDLE_FORE_COLOR, IUp.DEFAULT_HANDLE_COORD_COLOR); } /** * Displays the handles of a curve entity. * * @param ce the curve entity * @param sw the stroke weight * @param lineColor the color of handle lines * @param rearColor the color of the rear handle * @param foreColor the color of the fore handle * @param coordColor the color of the coordinate */ public void handles ( final CurveEntity3 ce, final float sw, final int lineColor, final int rearColor, final int foreColor, final int coordColor ) { final float swRear = sw * IUp.HANDLE_REAR_WEIGHT; final float swFore = sw * IUp.HANDLE_FORE_WEIGHT; final float swCoord = sw * IUp.HANDLE_COORD_WEIGHT; final Transform3 tr = ce.transform; final Iterator < Curve3 > curveItr = ce.iterator(); final Vec3 rh = new Vec3(); final Vec3 co = new Vec3(); final Vec3 fh = new Vec3(); this.disableDepthMask(); this.disableDepthTest(); this.pushStyle(); while ( curveItr.hasNext() ) { final Curve3 curve = curveItr.next(); final Iterator < Knot3 > knItr = curve.iterator(); while ( knItr.hasNext() ) { final Knot3 knot = knItr.next(); Transform3.mulPoint(tr, knot.rearHandle, rh); Transform3.mulPoint(tr, knot.coord, co); Transform3.mulPoint(tr, knot.foreHandle, fh); this.strokeWeight(sw); this.stroke(lineColor); this.lineImpl(rh.x, rh.y, rh.z, co.x, co.y, co.z); this.lineImpl(co.x, co.y, co.z, fh.x, fh.y, fh.z); this.strokeWeight(swRear); this.stroke(rearColor); this.pointImpl(rh.x, rh.y, rh.z); this.strokeWeight(swCoord); this.stroke(coordColor); this.pointImpl(co.x, co.y, co.z); this.strokeWeight(swFore); this.stroke(foreColor); this.pointImpl(fh.x, fh.y, fh.z); } } this.popStyle(); this.enableDepthTest(); this.enableDepthMask(); } /** * Draws a 3D image entity. * * @param entity the text entity */ public void image ( final ImageEntity3 entity ) { this.shape(entity, entity.material); } /** * Returns whether or not the renderer is 2D (false). */ @Override public boolean is2D ( ) { return false; } /** * Returns whether or not the renderer is 3D (true). */ @Override public boolean is3D ( ) { return true; } /** * Gets whether or not depth sorting is enabled. * * @return the depth sorting */ public boolean isDepthSorted ( ) { return this.isDepthSortingEnabled; } /** * Draws a line between two coordinates. * * @param origin the origin coordinate * @param dest the destination coordinate */ @Override public void line ( final Vec3 origin, final Vec3 dest ) { this.lineImpl(origin.x, origin.y, origin.z, dest.x, dest.y, dest.z); } /** * Sets the renderer's stroke, stroke weight and fill to a material's. Due * to stroke flickering in perspective, currently a material with a fill * may not also use a stroke. * * @param material the material */ @Override public void material ( final MaterialSolid material ) { /* * Due to stroke flickering issues, a material in 3D will not have both a * stroke and a fill. */ if ( material.useFill ) { this.noStroke(); this.fill(material.fill); } else { this.noFill(); if ( material.useStroke ) { this.strokeWeight(material.strokeWeight); this.stroke(Color.toHexIntWrap(material.stroke)); } else { this.noStroke(); } } } /** * Moves the camera by the given vector then updates the camera. * * @param x the vector x * @param y the vector y * @param z the vector z * * @see IUp3#moveTo(float, float, float) */ @Override public void moveBy ( final float x, final float y, final float z ) { this.moveByLocal(x, y, z); } /** * Moves the camera by the given vector then updates the camera. * * @param v the vector * * @see IUp3#moveByGlobal(float, float, float) */ @Override public void moveBy ( final Vec3 v ) { this.moveByLocal(v.x, v.y, v.z); } /** * Moves the renderer's camera by a vector relative to its orientation; * causes the camera to orbit around the locus at which it is looking. * * @param x the vector x * @param y the vector y * @param z the vector z */ @Experimental public void moveByLocal ( final float x, final float y, final float z ) { final PMatrix3D m = this.cameraInv; final float w = m.m30 * x + m.m31 * y + m.m32 * z + m.m33; if ( w != 0.0f ) { final float wInv = 1.0f / w; final float xLocal = ( m.m00 * x + m.m01 * y + m.m02 * z ) * wInv; final float yLocal = ( m.m10 * x + m.m11 * y + m.m12 * z ) * wInv; final float zLocal = ( m.m20 * x + m.m21 * y + m.m22 * z ) * wInv; this.moveTo(this.cameraX + xLocal, this.cameraY + yLocal, this.cameraZ + zLocal); } } /** * Moves the renderer's camera by a vector relative to its orientation; * causes the camera to orbit around the locus at which it is looking. * * @param v the vector */ public void moveByLocal ( final Vec3 v ) { this.moveByLocal(v.x, v.y, v.z); } /** * Sets the current normal and normal mode used by the renderer. * * @param nx the x component * @param ny the y component * @param nz the z component */ @Override public void normal ( final float nx, final float ny, final float nz ) { this.normalX = nx; this.normalY = ny; this.normalZ = nz; if ( this.shape != 0 ) { if ( this.normalMode == PGraphics.NORMAL_MODE_AUTO ) { /* One normal per begin/end shape. */ this.normalMode = PGraphics.NORMAL_MODE_SHAPE; } else if ( this.normalMode == PGraphics.NORMAL_MODE_SHAPE ) { /* A separate normal for each vertex. */ this.normalMode = PGraphics.NORMAL_MODE_VERTEX; } } } /** * Draws the world origin. The length of the axes is determined by * multiplying {@link IUp#DEFAULT_IJK_LINE_FAC}, * {@value IUp#DEFAULT_IJK_LINE_FAC}, with the renderer's short edge. */ @Override public void origin ( ) { this.origin(IUp.DEFAULT_IJK_LINE_FAC * Utils.min(this.width, this.height)); } /** * Draws the world origin. The axes stroke weight defaults to * {@link IUp#DEFAULT_IJK_SWEIGHT}, {@value IUp#DEFAULT_IJK_SWEIGHT}. * * @param lineLength the line length */ public void origin ( final float lineLength ) { this.origin(lineLength, IUp.DEFAULT_IJK_SWEIGHT); } /** * Draws the world origin. Colors the axes according to * {@link IUp#DEFAULT_I_COLOR}, {@link IUp#DEFAULT_J_COLOR} and * {@link IUp#DEFAULT_K_COLOR}. * * @param lineLength the line length * @param sw the stroke weight */ public void origin ( final float lineLength, final float sw ) { this.origin(lineLength, sw, IUp.DEFAULT_I_COLOR, IUp.DEFAULT_J_COLOR, IUp.DEFAULT_K_COLOR); } /** * Draws the world origin. * * @param lineLength the line length * @param sw the stroke weight * @param xColor the color of the x axis * @param yColor the color of the y axis * @param zColor the color of the z axis */ public void origin ( final float lineLength, final float sw, final int xColor, final int yColor, final int zColor ) { final float vl = Utils.max(IUtils.EPSILON, lineLength); this.disableDepthMask(); this.disableDepthTest(); this.pushStyle(); this.strokeWeight(sw); this.stroke(zColor); this.lineImpl(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, vl); this.stroke(yColor); this.lineImpl(0.0f, 0.0f, 0.0f, 0.0f, vl, 0.0f); this.stroke(xColor); this.lineImpl(0.0f, 0.0f, 0.0f, vl, 0.0f, 0.0f); this.popStyle(); this.enableDepthTest(); this.enableDepthMask(); } /** * Draws a transform origin. * * @param tr the transform * @param lineLength the line length * @param sw the stroke weight * @param xColor the color of the x axis * @param yColor the color of the y axis * @param zColor the color of the z axis */ public void origin ( final Transform3 tr, final float lineLength, final float sw, final int xColor, final int yColor, final int zColor ) { final Vec3 origin = new Vec3(); final Vec3 right = new Vec3(); final Vec3 forward = new Vec3(); final Vec3 up = new Vec3(); tr.getLocation(origin); tr.getAxes(right, forward, up); final float vl = lineLength > IUtils.EPSILON ? lineLength : IUtils.EPSILON; Vec3.mul(right, vl, right); Vec3.add(right, origin, right); Vec3.mul(forward, vl, forward); Vec3.add(forward, origin, forward); Vec3.mul(up, vl, up); Vec3.add(up, origin, up); this.disableDepthMask(); this.disableDepthTest(); this.pushStyle(); this.strokeWeight(sw); this.stroke(zColor); this.lineImpl(origin.x, origin.y, origin.z, up.x, up.y, up.z); this.stroke(yColor); this.lineImpl(origin.x, origin.y, origin.z, forward.x, forward.y, forward.z); this.stroke(xColor); this.lineImpl(origin.x, origin.y, origin.z, right.x, right.y, right.z); this.popStyle(); this.enableDepthTest(); this.enableDepthMask(); } /** * Boom or pedestal the camera, moving it on its local y axis, up or down. * This is done by multiplying the y magnitude by the camera inverse, then * adding the local coordinates to both the camera location and look * target. * * @param y the y magnitude */ @Override public void pedestal ( final float y ) { final float w = this.cameraInv.m31 * y + this.cameraInv.m33; if ( w != 0.0f ) { final float ywInv = y / w; final float xLocal = this.cameraInv.m01 * ywInv; final float yLocal = this.cameraInv.m11 * ywInv; final float zLocal = this.cameraInv.m21 * ywInv; this.camera(this.cameraX + xLocal, this.cameraY + yLocal, this.cameraZ + zLocal, this.lookTarget.x + xLocal, this.lookTarget.y + yLocal, this.lookTarget.z + zLocal, this.refUp.x, this.refUp.y, this.refUp.z); } } /** * Draws a point at a given coordinate * * @param v the coordinate */ @Override public void point ( final Vec3 v ) { this.pointImpl(v.x, v.y, v.z); } /** * Initializes a point light at a location. * * @param clr the color * @param loc the location */ public void pointLight ( final int clr, final Vec3 loc ) { this.pointLight(clr, loc.x, loc.y, loc.z); } /** * Draws a quadratic Bezier curve segment to the next anchor point; the * control point shapes the curve segment. * * @param cp the control point * @param ap1 the next anchor point */ @Override public void quadraticVertex ( final Vec3 cp, final Vec3 ap1 ) { super.quadraticVertex(cp.x, cp.y, cp.z, ap1.x, ap1.y, ap1.z); } /** * Resets the model view and camera matrices to the identity. Resets * projection model view to the projection. Resets camera axes vectors to * the default. */ @Override public void resetMatrix ( ) { super.resetMatrix(); Vec3.right(this.i); Vec3.forward(this.j); Vec3.up(this.k); Vec3.forward(this.lookDir); Vec3.zero(this.lookTarget); } /** * Rotates the model view matrix around an arbitrary axis by an angle in * radians. * * @param angle the angle in radians * @param xAxis the axis x coordinate * @param yAxis the axis y coordinate * @param zAxis the axis z coordinate */ @Override public void rotate ( final float angle, final float xAxis, final float yAxis, final float zAxis ) { this.rotateImpl(angle, xAxis, yAxis, zAxis); } /** * Rotates the sketch by an angle in radians around an arbitrary axis. * * @param angle the angle * @param axis the axis */ public void rotate ( final float angle, final Vec3 axis ) { this.rotateImpl(angle, axis.x, axis.y, axis.z); } /** * Rotates the renderer by a quaternion. * * @param q the quaternion */ public void rotate ( final Quaternion q ) { PMatAux.rotate(q, this.modelview); PMatAux.invRotate(q, this.modelviewInv); this.updateProjmodelview(); } /** * Scales the renderer by a dimension. * * @param dim the dimensions */ public void scale ( final Vec3 dim ) { this.scaleImpl(dim.x, dim.y, dim.z); } /** * Sets whether or not depth sorting is enabled. Flushes the geometry. * * @param ds the depth sorting */ public void setDepthSorting ( final boolean ds ) { this.flush(); this.isDepthSortingEnabled = ds; } /** * Sets the eye distance of the camera. The value is usually set by the * camera function, and to calculate the far clip plane of perspective * functions, but is exposed for public access. * * @param ed the eye distance */ public void setEyeDist ( final float ed ) { this.eyeDist = ed; } /** * Resets the {@link PGraphicsOpenGL#camera} and * {@link PGraphicsOpenGL#cameraInv} matrices, sets the model view to the * input values, calculates the inverse model view, then recalculates the * projection model view. * * @param m00 row 0, column 0 * @param m01 row 0, column 1 * @param m02 row 0, column 2 * @param m03 row 0, column 3 * @param m10 row 1, column 0 * @param m11 row 1, column 1 * @param m12 row 1, column 2 * @param m13 row 1, column 3 * @param m20 row 2, column 0 * @param m21 row 2, column 1 * @param m22 row 2, column 2 * @param m23 row 2, column 3 * @param m30 row 3, column 0 * @param m31 row 3, column 1 * @param m32 row 3, column 2 * @param m33 row 3, column 3 */ @Override public void setMatrix ( final float m00, final float m01, final float m02, final float m03, final float m10, final float m11, final float m12, final float m13, final float m20, final float m21, final float m22, final float m23, final float m30, final float m31, final float m32, final float m33 ) { super.setMatrix(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); Vec3.right(this.i); Vec3.forward(this.j); Vec3.up(this.k); Vec3.forward(this.lookDir); Vec3.zero(this.lookTarget); } /** * Draws a 3D curve entity. * * @param entity the curve entity */ public void shape ( final CurveEntity3 entity ) { final Transform3 tr = entity.transform; final Iterator < Curve3 > itr = entity.iterator(); final Vec3 fh = new Vec3(); final Vec3 rh = new Vec3(); final Vec3 co = new Vec3(); while ( itr.hasNext() ) { this.drawCurve3(itr.next(), tr, fh, rh, co); } } /** * Draws a 3D curve entity. * * @param entity the curve entity * @param material the material */ public void shape ( final CurveEntity3 entity, final MaterialSolid material ) { this.pushStyle(); this.material(material); this.shape(entity); this.popStyle(); } /** * Draws a 3D curve entity. * * @param entity the curve entity * @param materials the array of materials */ public void shape ( final CurveEntity3 entity, final MaterialSolid[] materials ) { final Transform3 tr = entity.transform; final Iterator < Curve3 > itr = entity.iterator(); final Vec3 fh = new Vec3(); final Vec3 rh = new Vec3(); final Vec3 co = new Vec3(); while ( itr.hasNext() ) { final Curve3 curve = itr.next(); this.pushStyle(); this.material(materials[curve.materialIndex]); this.drawCurve3(curve, tr, fh, rh, co); this.popStyle(); } } /** * Draws a 3D mesh entity. * * @param entity the mesh entity */ public void shape ( final MeshEntity3 entity ) { final Transform3 tr = entity.transform; final Iterator < Mesh3 > meshItr = entity.iterator(); final Vec3 v = new Vec3(); final Vec3 vn = new Vec3(); /* * With perspective projection, using stroke and fill together leads to * flickering issues. */ final boolean oldStroke = this.stroke; if ( this.fill ) { this.stroke = false; } while ( meshItr.hasNext() ) { this.drawMesh3(meshItr.next(), tr, v, vn); } this.stroke = oldStroke; } /** * Draws a 3D mesh entity. * * @param entity the mesh entity * @param material the material */ public void shape ( final MeshEntity3 entity, final MaterialPImage material ) { final Transform3 tr = entity.transform; final Iterator < Mesh3 > meshItr = entity.iterator(); final Vec3 v = new Vec3(); final Vec2 vt = new Vec2(); final Vec3 vn = new Vec3(); this.pushStyle(); this.noStroke(); while ( meshItr.hasNext() ) { this.drawMesh3(meshItr.next(), tr, material, v, vt, vn); } this.popStyle(); } /** * Draws a 3D mesh entity. * * @param entity the mesh entity * @param materials the materials */ public void shape ( final MeshEntity3 entity, final MaterialPImage[] materials ) { final Transform3 tr = entity.transform; final Iterator < Mesh3 > meshItr = entity.iterator(); final Vec3 v = new Vec3(); final Vec2 vt = new Vec2(); final Vec3 vn = new Vec3(); this.pushStyle(); this.noStroke(); while ( meshItr.hasNext() ) { final Mesh3 mesh = meshItr.next(); this.drawMesh3(mesh, tr, materials[mesh.materialIndex], v, vt, vn); } this.popStyle(); } /** * Draws a 3D mesh entity. * * @param entity the mesh entity * @param material the material */ public void shape ( final MeshEntity3 entity, final MaterialSolid material ) { this.pushStyle(); this.material(material); this.shape(entity); this.popStyle(); } /** * Draws a mesh entity. * * @param entity the mesh entity * @param materials the materials */ public void shape ( final MeshEntity3 entity, final MaterialSolid[] materials ) { final Transform3 tr = entity.transform; final Iterator < Mesh3 > meshItr = entity.iterator(); final Vec3 v = new Vec3(); final Vec3 vn = new Vec3(); while ( meshItr.hasNext() ) { final Mesh3 mesh = meshItr.next(); this.pushStyle(); this.material(materials[mesh.materialIndex]); this.drawMesh3(mesh, tr, v, vn); this.popStyle(); } } /** * Moves the renderer's camera and its look target by a vector relative to * its orientation. * * @param x the vector x * @param y the vector y * @param z the vector z */ public void strafe ( final float x, final float y, final float z ) { final PMatrix3D ci = this.cameraInv; final float w = ci.m30 * x + ci.m31 * y + ci.m32 * z + ci.m33; if ( w != 0.0f ) { final float wInv = 1.0f / w; final float xLocal = ( ci.m00 * x + ci.m01 * y + ci.m02 * z ) * wInv; final float yLocal = ( ci.m10 * x + ci.m11 * y + ci.m12 * z ) * wInv; final float zLocal = ( ci.m20 * x + ci.m21 * y + ci.m22 * z ) * wInv; this.camera(this.cameraX + xLocal, this.cameraY + yLocal, this.cameraZ + zLocal, this.lookTarget.x + xLocal, this.lookTarget.y + yLocal, this.lookTarget.z + zLocal, this.refUp.x, this.refUp.y, this.refUp.z); } } /** * Moves the renderer's camera and its look target by a vector relative to * its orientation. * * @param v the vector */ public void strafe ( final Vec3 v ) { this.strafe(v.x, v.y, v.z); } /** * This parent function attempts to translate the text and then undo the * translation. * * @param chars the characters array * @param start the start index * @param stop the stop index * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ @Override public void text ( final char[] chars, final int start, final int stop, final float x, final float y, final float z ) { this.text(chars, start, stop, x, y); } /** * This parent function attempts to translate the text and then undo the * translation. * * @param str the string * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ @Override public void text ( final String str, final float x, final float y, final float z ) { this.text(str, x, y); } /** * Draws a 3D text entity. * * @param entity the text entity */ public void text ( final TextEntity3 entity ) { this.shape(entity, entity.material); } /** * Returns the string representation of this renderer. * * @return the string */ @Override public String toString ( ) { return Up3.PATH_STR; } /** * Applies a transform to the renderer's matrix. * * @param tr3 the transform */ public void transform ( final Transform3 tr3 ) { this.transform(tr3, IUp.DEFAULT_ORDER); } /** * Applies a transform to the renderer's matrix. * * @param tr3 the transform * @param order the transform order */ public void transform ( final Transform3 tr3, final TransformOrder order ) { /* * This is not as redundant to Convert's Transform to PMatrix3D as it * looks, because this also adjusts the inverses and updates the model * view. */ final Vec3 tr3Scl = tr3.getScale(new Vec3()); final Vec3 tr3Loc = tr3.getLocation(new Vec3()); final Quaternion tr3Rot = tr3.getRotation(new Quaternion()); switch ( order ) { case RST: this.rotate(tr3Rot); this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); return; case RTS: this.rotate(tr3Rot); this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); return; case SRT: this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); this.rotate(tr3Rot); this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); return; case STR: this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); this.rotate(tr3Rot); return; case TSR: this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); this.rotate(tr3Rot); return; case R: this.rotate(tr3Rot); return; case RS: this.rotate(tr3Rot); this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); return; case RT: this.rotate(tr3Rot); this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); return; case S: this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); return; case SR: this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); this.rotate(tr3Rot); return; case ST: this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); return; case T: this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); return; case TR: this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); this.rotate(tr3Rot); return; case TS: this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); return; case TRS: default: this.translateImpl(tr3Loc.x, tr3Loc.y, tr3Loc.z); this.rotate(tr3Rot); this.scaleImpl(tr3Scl.x, tr3Scl.y, tr3Scl.z); } } /** * Translates the renderer by a vector. * * @param v the vector */ public void translate ( final Vec3 v ) { this.translateImpl(v.x, v.y, v.z); } /** * Trucks the camera, moving it on its local x axis, left or right. This is * done by multiplying the x magnitude by the camera inverse, then adding * the local coordinates to both the camera location and look target. * * @param x the x magnitude */ @Override public void truck ( final float x ) { final float w = this.cameraInv.m30 * x + this.cameraInv.m33; if ( w != 0.0f ) { final float xwInv = x / w; final float xLocal = this.cameraInv.m00 * xwInv; final float yLocal = this.cameraInv.m10 * xwInv; final float zLocal = this.cameraInv.m20 * xwInv; this.camera(this.cameraX + xLocal, this.cameraY + yLocal, this.cameraZ + zLocal, this.lookTarget.x + xLocal, this.lookTarget.y + yLocal, this.lookTarget.z + zLocal, this.refUp.x, this.refUp.y, this.refUp.z); } } /** * Adds another vertex to a shape between the beginShape and endShape * commands. * * @param v the coordinate */ @Override public void vertex ( final Vec3 v ) { this.vertexImpl(v.x, v.y, v.z, this.textureU, this.textureV); } /** * Adds another vertex to a shape between the beginShape and endShape * commands. Includes texture coordinates. * * @param v the coordinate * @param vt the texture coordinate */ public void vertex ( final Vec3 v, final Vec2 vt ) { this.vertexImpl(v.x, v.y, v.z, vt.x, vt.y); } /** * Initializes an ambient light with the default ambient color. The * camera's look target is used as the location. Ambient light illuminates * an object evenly from all sides. */ void ambientLight ( ) { this.aTemp.set(IUpOgl.DEFAULT_AMB_R, IUpOgl.DEFAULT_AMB_G, IUpOgl.DEFAULT_AMB_B, 1.0f); this.ambientLight(this.aTemp); } /** * Initializes an ambient light with a color. The camera's look target is * used as the location. Ambient light illuminates an object evenly from * all sides. * * @param clr the color */ void ambientLight ( final Color clr ) { this.ambientLight(Color.toHexIntWrap(clr), this.lookTarget.x, this.lookTarget.y, this.lookTarget.z); } /** * Initializes an ambient light with a color and location. Ambient light * illuminates an object evenly from all sides. * * @param clr the color * @param loc the location */ void ambientLight ( final Color clr, final Vec3 loc ) { this.ambientLight(Color.toHexIntWrap(clr), loc.x, loc.y, loc.z); } /** * Initializes an ambient light with a color. The camera's look target is * used as the location. Ambient light illuminates an object evenly from * all sides. * * @param clr the color */ void ambientLight ( final int clr ) { this.ambientLight(clr, this.lookTarget.x, this.lookTarget.y, this.lookTarget.z); } /** * Initializes an ambient light with a color and location. Ambient light * illuminates an object evenly from all sides. * * @param clr the color * @param xLoc the location x * @param yLoc the location y * @param zLoc the location z */ @Experimental void ambientLight ( final int clr, final float xLoc, final float yLoc, final float zLoc ) { this.enableLighting(); if ( this.lightCount >= IUpOgl.MAX_LIGHTS ) { return; } this.lightType[this.lightCount] = PConstants.AMBIENT; this.lightPosition(this.lightCount, xLoc, yLoc, zLoc, false); this.lightNormal(this.lightCount, 0.0f, 0.0f, 0.0f); this.lightAmbient(this.lightCount, clr); this.noLightDiffuse(this.lightCount); this.noLightSpecular(this.lightCount); this.noLightSpot(this.lightCount); this.lightFalloff(this.lightCount, this.currentLightFalloffConstant, this.currentLightFalloffLinear, this.currentLightFalloffQuadratic); ++this.lightCount; } /** * Initializes an ambient light with a color and location. Ambient light * illuminates an object evenly from all sides. * * @param clr the color * @param loc the location */ void ambientLight ( final int clr, final Vec3 loc ) { this.ambientLight(clr, loc.x, loc.y, loc.z); } /** * Initialize a directional light with a color and a direction. * * @param clr the color * @param dir the direction */ void directionalLight ( final Color clr, final Vec3 dir ) { this.directionalLight(Color.toHexIntWrap(clr), dir.x, dir.y, dir.z); } /** * Initialize a directional light with a color and a direction. * * @param clr the color * @param xDir the x direction * @param yDir the y direction * @param zDir the z direction */ @Experimental void directionalLight ( final int clr, final float xDir, final float yDir, final float zDir ) { // These are all package level because overridden lights functions // cause major glitches on graphics renderer.... this.enableLighting(); if ( this.lightCount >= IUpOgl.MAX_LIGHTS ) { return; } this.lightType[this.lightCount] = PConstants.DIRECTIONAL; this.lightPosition(this.lightCount, 0.0f, 0.0f, 0.0f, true); this.lightNormal(this.lightCount, xDir, yDir, zDir); this.noLightAmbient(this.lightCount); this.lightDiffuse(this.lightCount, clr); this.lightSpecular(this.lightCount, this.currentLightSpecular[0], this.currentLightSpecular[1], this.currentLightSpecular[2]); this.noLightSpot(this.lightCount); this.noLightFalloff(this.lightCount); ++this.lightCount; } /** * Initialize a directional light with a color and a direction. * * @param clr the color * @param dir the direction */ void directionalLight ( final int clr, final Vec3 dir ) { this.directionalLight(clr, dir.x, dir.y, dir.z); } /** * Initializes a point light at a location. * * @param clr the color * @param loc the location */ void pointLight ( final Color clr, final Vec3 loc ) { this.pointLight(Color.toHexIntWrap(clr), loc.x, loc.y, loc.z); } /** * Initializes a point light at a location. * * @param clr the color * @param xLoc the location x * @param yLoc the location y * @param zLoc the location z */ @Experimental void pointLight ( final int clr, final float xLoc, final float yLoc, final float zLoc ) { this.enableLighting(); if ( this.lightCount >= IUpOgl.MAX_LIGHTS ) { return; } this.lightType[this.lightCount] = PConstants.POINT; this.lightPosition(this.lightCount, xLoc, yLoc, zLoc, false); this.lightNormal(this.lightCount, 0.0f, 0.0f, 0.0f); this.noLightAmbient(this.lightCount); this.lightDiffuse(this.lightCount, clr); this.lightSpecular(this.lightCount, this.currentLightSpecular[0], this.currentLightSpecular[1], this.currentLightSpecular[2]); this.noLightSpot(this.lightCount); this.lightFalloff(this.lightCount, this.currentLightFalloffConstant, this.currentLightFalloffLinear, this.currentLightFalloffQuadratic); ++this.lightCount; } /** * Initializes a spot light. The location positions the spotlight in space * while the direction determines where the light points. The angle * parameter affects angle of the spotlight cone, while concentration sets * the bias of light focusing toward the center of that cone. * * @param clr the color * @param loc the location * @param dir the direction * @param angle the angle * @param concentration cone center bias */ void spotLight ( final Color clr, final Vec3 loc, final Vec3 dir, final float angle, final float concentration ) { this.spotLight(Color.toHexIntWrap(this.aTemp), loc.x, loc.y, loc.z, dir.x, dir.y, dir.z, angle, concentration); } /** * Initializes a spot light. The location positions the spotlight in space * while the direction determines where the light points. The angle * parameter affects angle of the spotlight cone, while concentration sets * the bias of light focusing toward the center of that cone. * * @param clr the color * @param xLoc the location x * @param yLoc the location y * @param zLoc the location z * @param xDir the direction x * @param yDir the direction y * @param zDir the direction z * @param angle spotlight cone angle * @param concentration cone center bias */ void spotLight ( final int clr, final float xLoc, final float yLoc, final float zLoc, final float xDir, final float yDir, final float zDir, final float angle, final float concentration ) { this.enableLighting(); if ( this.lightCount >= IUpOgl.MAX_LIGHTS ) { return; } this.lightType[this.lightCount] = PConstants.SPOT; this.lightPosition(this.lightCount, xLoc, yLoc, zLoc, false); this.lightNormal(this.lightCount, xDir, yDir, zDir); this.noLightAmbient(this.lightCount); this.lightDiffuse(this.lightCount, clr); this.lightSpecular(this.lightCount, this.currentLightSpecular[0], this.currentLightSpecular[1], this.currentLightSpecular[2]); this.lightSpot(this.lightCount, angle, concentration); this.lightFalloff(this.lightCount, this.currentLightFalloffConstant, this.currentLightFalloffLinear, this.currentLightFalloffQuadratic); ++this.lightCount; } /** * Initializes a spot light. The location positions the spotlight in space * while the direction determines where the light points. The angle * parameter affects angle of the spotlight cone, while concentration sets * the bias of light focusing toward the center of that cone. * * @param clr the color * @param loc the location * @param dir the direction * @param angle the angle * @param concentration cone center bias */ void spotLight ( final int clr, final Vec3 loc, final Vec3 dir, final float angle, final float concentration ) { this.spotLight(clr, loc.x, loc.y, loc.z, dir.x, dir.y, dir.z, angle, concentration); } /** * A helper function for the renderer camera. Updates the camera matrix, * its inverse, the model view and its inverse, and updates the projection * model view. */ protected void updateCameraInv ( ) { final float m00 = this.i.x; final float m01 = this.i.y; final float m02 = this.i.z; final float m10 = this.j.x; final float m11 = this.j.y; final float m12 = this.j.z; final float m20 = this.k.x; final float m21 = this.k.y; final float m22 = this.k.z; /* Set inverse by column. */ /* @formatter:off */ this.cameraInv.set( m00, m10, m20, this.cameraX, m01, m11, m21, this.cameraY, m02, m12, m22, this.cameraZ, 0.0f, 0.0f, 0.0f, 1.0f); /* * Set matrix to axes by row. Translate by a negative location after the * rotation. */ this.camera.set( m00, m01, m02, -this.cameraX * m00 - this.cameraY * m01 - this.cameraZ * m02, m10, m11, m12, -this.cameraX * m10 - this.cameraY * m11 - this.cameraZ * m12, m20, m21, m22, -this.cameraX * m20 - this.cameraY * m21 - this.cameraZ * m22, 0.0f, 0.0f, 0.0f, 1.0f); /* @formatter:on */ /* Set model view to camera. */ this.modelview.set(this.camera); this.modelviewInv.set(this.cameraInv); PMatAux.mul(this.projection, this.modelview, this.projmodelview); } /** * Default look at target x component. */ public static final float DEFAULT_TARGET_X = 0.0f; /** * Default look at target y component. */ public static final float DEFAULT_TARGET_Y = 0.0f; /** * Default look at target z component. */ public static final float DEFAULT_TARGET_Z = 0.0f; /** * The path string for this renderer. */ @SuppressWarnings ( "hiding" ) public static final String PATH_STR = "camzup.pfriendly.Up3"; }
28.953617
80
0.60677
32757a304e8085443546c8ec6b8bfc9439d0c00b
3,622
package edu.cmu.cs.relab.tortoise; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.TreeMap; /** * Provides a naive reader for CSV files to acquire privacy risk score data. * * @author CMU RELAB * @version 1.0 * */ public class DataSource { private TreeMap<String,Integer> headers = new TreeMap<String,Integer>(); private ArrayList<String[]> data = new ArrayList<String[]>(); private DataSource(String[] header) { for (int i = 0; i < header.length; i++) { headers.put(header[i], i); } } /** * Returns the list of header names for this data source. * @return the list of header names. */ public String[] getHeaders() { return headers.keySet().toArray(new String[headers.size()]); } /** * Returns the desired value in the given row and header name. * * @param row the row containing the desired value * @param header the header name describing the desired value * @return the desired value */ public String get(int row, String header) { if (row < data.size()) { return data.get(row)[headers.get(header)]; } else { return null; } } /** * Returns a data source that assumes a comma delimiter. The delimiter * is assumed to separate values in each row of the file. * * @param file the file containing the data * @return the data source acquired from the given file * @throws IOException thrown, if an error occurs reading the given file */ public static DataSource read(File file) throws IOException { return read(file, ","); } /** * Returns a data source using the given delimiter. The delimiter * is assumed to separate values in each row of the file. * * @param file the file containing the data * @param delim the delimiter to use when reading the file * @return the data source acquired from the given file * @throws IOException thrown, if an error occurs reading the given file */ public static DataSource read(File file, String delim) throws IOException { BufferedReader in = new BufferedReader(new FileReader(file)); String line; // read the first row as the data source headers line = in.readLine(); if (line == null) { in.close(); return null; } DataSource src = new DataSource(split(line, delim)); // read each record until the file ends while ((line = in.readLine()) != null) { String[] record = split(line, delim); src.data.add(record); } in.close(); return src; } /** * Returns the number of rows in this data source. * @return the numer of rows in this data source. */ public int size() { return data.size(); } /** * Splits a line from the file using the given delimiter. This method * attempts to split values that may contain the delimiter and that * may contain quotes, or be quoted. * * @param line the line from the file to split * @param delim the delimiter that separates values * @return the separated values */ private static String[] split(String line, String delim) { ArrayList<String> splits = new ArrayList<String>(); String[] split = line.split(delim); for (int i = 0; i < split.length; i++) { if (split[i].startsWith("\"")) { String join = split[i].substring(1); int j = i; while (!split[j].endsWith("\"")) { j++; join += delim + split[j]; } i = j; join = join.substring(0, join.length() - 1).replaceAll("\"\"", "\""); splits.add(join); } else { splits.add(split[i]); } } return splits.toArray(new String[splits.size()]); } }
25.871429
76
0.662617
e31e616efa475f38f2bf093ae771357c1ea2ea29
2,980
/** * Copyright 2005-2017 Dozer Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dozer.loader.api; import org.dozer.BeanFactory; import org.dozer.loader.DozerBuilder; /** * @author Dmitry Buzdin */ public class TypeDefinition { private String name; private String beanFactory; private String createMethod; private String factoryBeanId; private Boolean mapEmptyString; private String mapGetMethod; private String mapSetMethod; private Boolean mapNull; private Boolean isAccessible; public TypeDefinition(Class<?> type) { this.name = type.getName(); } public TypeDefinition(String name) { this.name = name; } public void build(DozerBuilder.ClassDefinitionBuilder typeBuilder) { typeBuilder.beanFactory(this.beanFactory); typeBuilder.createMethod(this.createMethod); typeBuilder.factoryBeanId(this.factoryBeanId); typeBuilder.mapEmptyString(this.mapEmptyString); typeBuilder.mapNull(this.mapNull); typeBuilder.mapGetMethod(this.mapGetMethod); typeBuilder.mapSetMethod(this.mapSetMethod); typeBuilder.isAccessible(this.isAccessible); } public TypeDefinition mapMethods(String getMethod, String setMethod) { this.mapGetMethod = getMethod; this.mapSetMethod = setMethod; return this; } public TypeDefinition beanFactory(Class<? extends BeanFactory> type) { this.beanFactory = type.getName(); return this; } public TypeDefinition beanFactory(String name) { this.beanFactory = name; return this; } public TypeDefinition createMethod(String method) { this.createMethod = method; return this; } public TypeDefinition mapMethods(String factoryBeanId) { this.factoryBeanId = factoryBeanId; return this; } public TypeDefinition mapEmptyString() { return mapEmptyString(true); } public TypeDefinition mapEmptyString(boolean value) { this.mapEmptyString = value; return this; } public TypeDefinition mapNull() { return mapNull(true); } public TypeDefinition mapNull(boolean value) { this.mapNull = value; return this; } public TypeDefinition accessible() { return accessible(true); } public TypeDefinition accessible(boolean value) { this.isAccessible = value; return this; } public String getName() { return name; } }
25.689655
76
0.701007
c1b95ab3182571f3cb217e20cfee4ff8da8c5618
2,024
package ca.team2706.scouting.mcmergemanager.gui; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import ca.team2706.scouting.mcmergemanager.R; public class GetTeamNumberDialog { private Activity launchActivity; private EditText editText; private String title; private String inputHint; private int inputType; public boolean accepted = false; public boolean canceled = false; public String inputResult = "-1"; public GetTeamNumberDialog(String title, String inputHint, int inputType, Activity launchActivity) { this.title = title; this.inputHint = inputHint; this.inputType = inputType; this.launchActivity = launchActivity; } public int getTeamNumber() { return Integer.parseInt(inputResult); } public void displayAlertDialog() { LayoutInflater inflater = launchActivity.getLayoutInflater(); View alertLayout = inflater.inflate(R.layout.layout_custom_dialog, null); AlertDialog.Builder alert = new AlertDialog.Builder(launchActivity); alert.setTitle(title); alert.setView(alertLayout); alert.setCancelable(false); editText = (EditText) alertLayout.findViewById(R.id.inputHint); editText.setHint(inputHint); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { canceled = true; } }); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { accepted = true; inputResult = editText.getText().toString(); } }); AlertDialog dialog = alert.create(); dialog.show(); } }
29.333333
104
0.668478
8bc68341eb95ed54fd63860945e06d177dca0772
1,274
package at.ac.tuwien.dsg.scaledom.io.impl; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import at.ac.tuwien.dsg.scaledom.io.NodeLocation; public class FileNodeLocation extends NodeLocation { /** Special value, indicating the offset is not known yet. */ public final static long OFFSET_UNKNOWN = Long.MIN_VALUE; private long startOffset; private long endOffset; FileNodeLocation(final long startOffset, final long endOffset) { this.startOffset = startOffset; this.endOffset = endOffset; } public long getStartOffset() { return startOffset; } public long getEndOffset() { return endOffset; } @Override public void setEndLocation(final NodeLocation location) { checkNotNull(location, "Argument location must not be null"); checkArgument(location instanceof FileNodeLocation, "Argument location must be of type FileNodeLocation"); if (endOffset == OFFSET_UNKNOWN) { final FileNodeLocation fileNodeLocation = (FileNodeLocation) location; endOffset = fileNodeLocation.getStartOffset(); } } @Override public String toString() { // for debug use return "[" + startOffset + "/" + endOffset + "]"; } }
28.311111
109
0.733909
2c3452c0ae0bc8f1eeb08b275e8b0c6bd3cee48a
3,079
/** * Copyright 2014 PubNative GmbH * * 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 net.pubnative.library.tester.activity; import net.pubnative.library.tester.R; import net.pubnative.library.model.request.AdRequest; import org.droidparts.activity.legacy.Activity; import org.droidparts.annotation.inject.InjectBundleExtra; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; public abstract class AbstractResponseActivity extends Activity { private static final String AD_REQUEST = "ad_request"; @InjectBundleExtra(key = AD_REQUEST) protected AdRequest req; protected static Intent getIntent(Context ctx, AdRequest req, Class<? extends AbstractResponseActivity> cls) { Intent intent = new Intent(ctx, cls); intent.putExtra(AD_REQUEST, req); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getTitle() + " - " + getString(R.string.response)); } // private ProgressDialog loadingDialog; protected final void showLoading() { dismissLoading(null); loadingDialog = ProgressDialog.show(this, null, getString(R.string.loading___), true); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); } protected final void dismissLoading(Exception ex) { if (loadingDialog != null) { loadingDialog.dismiss(); if (ex != null) { Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show(); } } loadingDialog = null; } // }
34.211111
112
0.698603
e066897703b9e50cccfe3c924837d4793af2c575
338
package usi.si.seart.gseapp.db_access_service; import usi.si.seart.gseapp.dto.AccessTokenDto; import usi.si.seart.gseapp.dto.AccessTokenDtoList; import usi.si.seart.gseapp.model.AccessToken; public interface AccessTokenService { AccessTokenDtoList getAll(); AccessTokenDto create(AccessToken token); void delete(Long id); }
28.166667
50
0.795858
72336562b91ce180c7b862a0172a356ee3972a32
1,517
/** * Jooby https://jooby.io * Apache License Version 2.0 https://jooby.io/LICENSE.txt * Copyright 2014 Edgar Espina */ package io.jooby.internal.converter; import io.jooby.Value; import io.jooby.ValueConverter; import io.jooby.SneakyThrows; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; public class ValueOfConverter implements ValueConverter, BiFunction<Class, Method, Method> { private Map<Class, Method> cache = new ConcurrentHashMap<>(); @Override public boolean supports(Class type) { return cache.compute(type, this) != null; } @Override public Object convert(Value value, Class type) { try { return cache.compute(type, this).invoke(null, value.value()); } catch (InvocationTargetException x) { throw SneakyThrows.propagate(x.getTargetException()); } catch (IllegalAccessException x) { throw SneakyThrows.propagate(x); } } @Override public Method apply(Class type, Method method) { if (method == null) { try { Method valueOf = type.getDeclaredMethod("valueOf", String.class); if (Modifier.isStatic(valueOf.getModifiers()) && Modifier .isPublic(valueOf.getModifiers())) { return valueOf; } return null; } catch (NoSuchMethodException x) { return null; } } return method; } }
28.622642
92
0.694133
613387433ed110578f1d623cc0f65e3d29b01697
6,716
/** * Copyright 2019 Huawei Technologies Co.,Ltd. * 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.obs.services.model; import java.util.List; /** * Request parameters of restoring Archive objects in a batch. The "prefix" and * "keyAndVersions" parameters cannot be set in the same request. If both * parameters are empty, all Archive objects in the bucket are restored. */ public class RestoreObjectsRequest extends AbstractBulkRequest { private int days; private RestoreTierEnum tier; private String prefix; private boolean versionRestored; private String encodingType; private List<KeyAndVersion> keyAndVersions; private TaskCallback<RestoreObjectResult, RestoreObjectRequest> callback; public RestoreObjectsRequest() { } /** * Constructor * * @param bucketName * Bucket name */ public RestoreObjectsRequest(String bucketName) { super(bucketName); } /** * Constructor * * @param bucketName * Bucket name * @param days * Retention period of the restored objects * @param tier * Restore option */ public RestoreObjectsRequest(String bucketName, int days, RestoreTierEnum tier) { super(bucketName); this.days = days; this.tier = tier; } /** * Constructor * * @param bucketName * Bucket name * @param days * Retention period of the restored objects * @param tier * Restore option * @param encodingType * The encoding type use for encode objectKey. */ public RestoreObjectsRequest(String bucketName, int days, RestoreTierEnum tier, String encodingType) { super(bucketName); this.days = days; this.tier = tier; this.encodingType = encodingType; } /** * Obtain the retention period of the restored objects. The value ranges * from 1 to 30 (in days). * * @return Retention period of the restored objects */ public int getDays() { return days; } /** * Set the retention period of the restored objects. The value ranges from 1 * to 30 (in days). * * @param days * Retention period of the restored objects */ public void setDays(int days) { this.days = days; } /** * Obtain the restore option. * * @return Restore option */ public RestoreTierEnum getRestoreTier() { return tier; } /** * Set the restore option. * * @param tier * Restore option */ public void setRestoreTier(RestoreTierEnum tier) { this.tier = tier; } /** * Set the name prefix of the objects to be restored in a batch. * * @param prefix * Object name prefix */ public void setPrefix(String prefix) { this.prefix = prefix; } /** * Obtain the name prefix of the objects to be restored in a batch. * * @return Object name prefix */ public String getPrefix() { return prefix; } /** * Obtain whether to restore all versions of Archive objects. The default * value is "false", indicating that only latest versions of Archive objects * are restored. * * @return Identifier of version restore */ public boolean isVersionRestored() { return versionRestored; } /** * Set whether to restore all versions of Archive objects. * * @param versionRestored * Identifier of version restore */ public void setVersionRestored(boolean versionRestored) { this.versionRestored = versionRestored; } /** * Set the list of objects to be restored. * * @param keyAndVersions * List of objects to be restored */ public void setKeyAndVersions(List<KeyAndVersion> keyAndVersions) { this.keyAndVersions = keyAndVersions; } /** * Obtain the list of objects to be restored. * * @return List of objects to be restored */ public List<KeyAndVersion> getKeyAndVersions() { return this.keyAndVersions; } /** * Add an object to be restored. * * @param objectKey * Object name * @param versionId * Object version * @return Object that has been added to be restored */ public KeyAndVersion addKeyAndVersion(String objectKey, String versionId) { KeyAndVersion kv = new KeyAndVersion(objectKey, versionId); this.getKeyAndVersions().add(kv); return kv; } /** * Add an object to be restored. * * @param objectKey * Object name * @return Object that has been added to be restored */ public KeyAndVersion addKeyAndVersion(String objectKey) { return this.addKeyAndVersion(objectKey, null); } /** * Obtain the callback object of a batch task. * * @return Callback object */ public TaskCallback<RestoreObjectResult, RestoreObjectRequest> getCallback() { return callback; } /** * Set the callback object of a batch task. * * @param callback * Callback object */ public void setCallback(TaskCallback<RestoreObjectResult, RestoreObjectRequest> callback) { this.callback = callback; } /** * Set the encoding type that used for encode objectkey * * @param encodingType * could chose url. */ public void setEncodingType(String encodingType) { this.encodingType = encodingType; } /** * Obtain the list of to-be-deleted objects. * * @return List of to-be-deleted objects */ public String getEncodingType() { return encodingType; } @Override public String toString() { return "RestoreObjectsRequest [bucketName=" + bucketName + ", days=" + days + ", tier=" + tier + ", encodingType=" + encodingType + "]"; } }
25.930502
106
0.606313
12cf88a94ebe6efa6d31609a8e1fe1a4dd5db9e4
926
package com.dailystudio.job; public abstract class Job implements Runnable { public interface OnFinishedListener { public void onFinished(JobExecutor executor, Job job); } private volatile boolean mRunInCreatorThread; private OnFinishedListener mOnFinishedListener = null; public Job() { this(false); } public Job(boolean runInCreatorThread) { mRunInCreatorThread = runInCreatorThread; } public void setRunInCreatorThread(boolean runInCreatorThread) { mRunInCreatorThread = runInCreatorThread; } public boolean isRunInCreatorThread() { return mRunInCreatorThread; } public void setOnFinishedListener(OnFinishedListener l) { mOnFinishedListener = l; } public OnFinishedListener getOnFinishedListener() { return mOnFinishedListener; } @Override public void run() { doJob(); synchronized (this) { this.notifyAll(); } } abstract protected void doJob(); }
18.156863
64
0.7473
880b159c81482642fa13e57e9ca74736c9209dcd
11,258
/* * Copyright 2014-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.kafka.config; import java.util.Arrays; import java.util.Collection; import java.util.regex.Pattern; import org.springframework.beans.BeanUtils; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.listener.AbstractMessageListenerContainer; import org.springframework.kafka.listener.AfterRollbackProcessor; import org.springframework.kafka.listener.BatchErrorHandler; import org.springframework.kafka.listener.ContainerProperties; import org.springframework.kafka.listener.ErrorHandler; import org.springframework.kafka.listener.GenericErrorHandler; import org.springframework.kafka.listener.adapter.RecordFilterStrategy; import org.springframework.kafka.support.TopicPartitionInitialOffset; import org.springframework.kafka.support.converter.MessageConverter; import org.springframework.retry.RecoveryCallback; import org.springframework.retry.support.RetryTemplate; /** * Base {@link KafkaListenerContainerFactory} for Spring's base container implementation. * * @param <C> the {@link AbstractMessageListenerContainer} implementation type. * @param <K> the key type. * @param <V> the value type. * * @author Stephane Nicoll * @author Gary Russell * @author Artem Bilan * * @see AbstractMessageListenerContainer */ public abstract class AbstractKafkaListenerContainerFactory<C extends AbstractMessageListenerContainer<K, V>, K, V> implements KafkaListenerContainerFactory<C>, ApplicationEventPublisherAware { private final ContainerProperties containerProperties = new ContainerProperties((Pattern) null); private GenericErrorHandler<?> errorHandler; private ConsumerFactory<K, V> consumerFactory; private Boolean autoStartup; private Integer phase; private MessageConverter messageConverter; private RecordFilterStrategy<K, V> recordFilterStrategy; private Boolean ackDiscarded; private RetryTemplate retryTemplate; private RecoveryCallback<? extends Object> recoveryCallback; private Boolean statefulRetry; private Boolean batchListener; private ApplicationEventPublisher applicationEventPublisher; private KafkaTemplate<K, V> replyTemplate; private AfterRollbackProcessor<K, V> afterRollbackProcessor; /** * Specify a {@link ConsumerFactory} to use. * @param consumerFactory The consumer factory. */ public void setConsumerFactory(ConsumerFactory<K, V> consumerFactory) { this.consumerFactory = consumerFactory; } public ConsumerFactory<K, V> getConsumerFactory() { return this.consumerFactory; } /** * Specify an {@code autoStartup boolean} flag. * @param autoStartup true for auto startup. * @see AbstractMessageListenerContainer#setAutoStartup(boolean) */ public void setAutoStartup(Boolean autoStartup) { this.autoStartup = autoStartup; } /** * Specify a {@code phase} to use. * @param phase The phase. * @see AbstractMessageListenerContainer#setPhase(int) */ public void setPhase(int phase) { this.phase = phase; } /** * Set the message converter to use if dynamic argument type matching is needed. * @param messageConverter the converter. */ public void setMessageConverter(MessageConverter messageConverter) { this.messageConverter = messageConverter; } /** * Set the record filter strategy. * @param recordFilterStrategy the strategy. */ public void setRecordFilterStrategy(RecordFilterStrategy<K, V> recordFilterStrategy) { this.recordFilterStrategy = recordFilterStrategy; } /** * Set to true to ack discards when a filter strategy is in use. * @param ackDiscarded the ackDiscarded. */ public void setAckDiscarded(Boolean ackDiscarded) { this.ackDiscarded = ackDiscarded; } /** * Set a retryTemplate. * @param retryTemplate the template. */ public void setRetryTemplate(RetryTemplate retryTemplate) { this.retryTemplate = retryTemplate; } /** * Set a callback to be used with the {@link #setRetryTemplate(RetryTemplate) * retryTemplate}. * @param recoveryCallback the callback. */ public void setRecoveryCallback(RecoveryCallback<? extends Object> recoveryCallback) { this.recoveryCallback = recoveryCallback; } /** * When using a {@link RetryTemplate} Set to true to enable stateful retry. Use in * conjunction with a * {@link org.springframework.kafka.listener.SeekToCurrentErrorHandler} when retry can * take excessive time; each failure goes back to the broker, to keep the Consumer * alive. * @param statefulRetry true to enable stateful retry. * @since 2.1.3 */ public void setStatefulRetry(boolean statefulRetry) { this.statefulRetry = statefulRetry; } /** * Return true if this endpoint creates a batch listener. * @return true for a batch listener. * @since 1.1 */ public Boolean isBatchListener() { return this.batchListener; } /** * Set to true if this endpoint should create a batch listener. * @param batchListener true for a batch listener. * @since 1.1 */ public void setBatchListener(Boolean batchListener) { this.batchListener = batchListener; } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } /** * Set the {@link KafkaTemplate} to use to send replies. * @param replyTemplate the template. * @since 2.0 */ public void setReplyTemplate(KafkaTemplate<K, V> replyTemplate) { this.replyTemplate = replyTemplate; } /** * Set the error handler to call when the listener throws an exception. * @param errorHandler the error handler. * @since 2.2 */ public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Set the batch error handler to call when the listener throws an exception. * @param errorHandler the error handler. * @since 2.2 */ public void setBatchErrorHandler(BatchErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Set a processor to invoke after a transaction rollback; typically will * seek the unprocessed topic/partition to reprocess the records. * The default does so, including the failed record. * @param afterRollbackProcessor the processor. * @since 1.3.5 */ public void setAfterRollbackProcessor(AfterRollbackProcessor<K, V> afterRollbackProcessor) { this.afterRollbackProcessor = afterRollbackProcessor; } /** * Obtain the properties template for this factory - set properties as needed * and they will be copied to a final properties instance for the endpoint. * @return the properties. */ public ContainerProperties getContainerProperties() { return this.containerProperties; } @SuppressWarnings("unchecked") @Override public C createListenerContainer(KafkaListenerEndpoint endpoint) { C instance = createContainerInstance(endpoint); if (endpoint.getId() != null) { instance.setBeanName(endpoint.getId()); } if (endpoint instanceof AbstractKafkaListenerEndpoint) { AbstractKafkaListenerEndpoint<K, V> aklEndpoint = (AbstractKafkaListenerEndpoint<K, V>) endpoint; if (this.recordFilterStrategy != null) { aklEndpoint.setRecordFilterStrategy(this.recordFilterStrategy); } if (this.ackDiscarded != null) { aklEndpoint.setAckDiscarded(this.ackDiscarded); } if (this.retryTemplate != null) { aklEndpoint.setRetryTemplate(this.retryTemplate); } if (this.recoveryCallback != null) { aklEndpoint.setRecoveryCallback(this.recoveryCallback); } if (this.statefulRetry != null) { aklEndpoint.setStatefulRetry(this.statefulRetry); } if (this.batchListener != null) { aklEndpoint.setBatchListener(this.batchListener); } if (this.replyTemplate != null) { aklEndpoint.setReplyTemplate(this.replyTemplate); } } endpoint.setupListenerContainer(instance, this.messageConverter); initializeContainer(instance); instance.getContainerProperties().setGroupId(endpoint.getGroupId()); instance.getContainerProperties().setClientId(endpoint.getClientIdPrefix()); return instance; } /** * Create an empty container instance. * @param endpoint the endpoint. * @return the new container instance. */ protected abstract C createContainerInstance(KafkaListenerEndpoint endpoint); /** * Further initialize the specified container. * <p>Subclasses can inherit from this method to apply extra * configuration if necessary. * @param instance the container instance to configure. */ protected void initializeContainer(C instance) { ContainerProperties properties = instance.getContainerProperties(); BeanUtils.copyProperties(this.containerProperties, properties, "topics", "topicPartitions", "topicPattern", "messageListener", "ackCount", "ackTime"); if (this.afterRollbackProcessor != null) { instance.setAfterRollbackProcessor(this.afterRollbackProcessor); } if (this.containerProperties.getAckCount() > 0) { properties.setAckCount(this.containerProperties.getAckCount()); } if (this.containerProperties.getAckTime() > 0) { properties.setAckTime(this.containerProperties.getAckTime()); } if (this.errorHandler != null) { instance.setGenericErrorHandler(this.errorHandler); } if (this.autoStartup != null) { instance.setAutoStartup(this.autoStartup); } if (this.phase != null) { instance.setPhase(this.phase); } if (this.applicationEventPublisher != null) { instance.setApplicationEventPublisher(this.applicationEventPublisher); } } @Override public C createContainer(final Collection<TopicPartitionInitialOffset> topicPartitions) { C container = createContainerInstance(new KafkaListenerEndpointAdapter() { @Override public Collection<TopicPartitionInitialOffset> getTopicPartitions() { return topicPartitions; } }); initializeContainer(container); return container; } @Override public C createContainer(final String... topics) { C container = createContainerInstance(new KafkaListenerEndpointAdapter() { @Override public Collection<String> getTopics() { return Arrays.asList(topics); } }); initializeContainer(container); return container; } @Override public C createContainer(final Pattern topicPattern) { C container = createContainerInstance(new KafkaListenerEndpointAdapter() { @Override public Pattern getTopicPattern() { return topicPattern; } }); initializeContainer(container); return container; } }
30.675749
115
0.760437
f5f9cb2387d8d346b72f4f170f1d7fd2297bfb5a
10,414
/* * Copyright (C) 2007-2010 Júlio Vilmar Gesser. * Copyright (C) 2011, 2013-2015 The JavaParser Team. * * This file is part of JavaParser. * * JavaParser can be used either under the terms of * a) 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. * b) the terms of the Apache License * * You should have received a copy of both licenses in LICENCE.LGPL and * LICENCE.APACHE. Please refer to those files for details. * * JavaParser 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. */ package com.github.javaparser.ast; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import com.github.javaparser.ast.comments.Comment; import com.github.javaparser.ast.visitor.*; /** * Abstract class for all nodes of the AST. * * Each Node can have one associated comment which describe it and * a number of "orphan comments" which it contains but are not specifically * associated to any element. * * @author Julio Vilmar Gesser */ public abstract class Node implements Cloneable { private int beginLine; private int beginColumn; private int endLine; private int endColumn; private Node parentNode; private List<Node> childrenNodes = new LinkedList<Node>(); private List<Comment> orphanComments = new LinkedList<Comment>(); /** * This attribute can store additional information from semantic analysis. */ private Object data; private Comment comment; public Node() { } public Node(final int beginLine, final int beginColumn, final int endLine, final int endColumn) { this.beginLine = beginLine; this.beginColumn = beginColumn; this.endLine = endLine; this.endColumn = endColumn; } /** * Accept method for visitor support. * * @param <R> * the type the return value of the visitor * @param <A> * the type the argument passed to the visitor * @param v * the visitor implementation * @param arg * the argument passed to the visitor * @return the result of the visit */ public abstract <R, A> R accept(GenericVisitor<R, A> v, A arg); /** * Accept method for visitor support. * * @param <A> * the type the argument passed for the visitor * @param v * the visitor implementation * @param arg * any value relevant for the visitor */ public abstract <A> void accept(VoidVisitor<A> v, A arg); /** * Return the begin column of this node. * * @return the begin column of this node */ public final int getBeginColumn() { return beginColumn; } /** * Return the begin line of this node. * * @return the begin line of this node */ public final int getBeginLine() { return beginLine; } /** * This is a comment associated with this node. * * @return comment property */ public final Comment getComment() { return comment; } /** * Use this to retrieve additional information associated to this node. * * @return data property */ public final Object getData() { return data; } /** * Return the end column of this node. * * @return the end column of this node */ public final int getEndColumn() { return endColumn; } /** * Return the end line of this node. * * @return the end line of this node */ public final int getEndLine() { return endLine; } /** * Sets the begin column of this node. * * @param beginColumn * the begin column of this node */ public final void setBeginColumn(final int beginColumn) { this.beginColumn = beginColumn; } /** * Sets the begin line of this node. * * @param beginLine * the begin line of this node */ public final void setBeginLine(final int beginLine) { this.beginLine = beginLine; } /** * Use this to store additional information to this node. * * @param comment to be set */ public final void setComment(final Comment comment) { if (comment != null && (this instanceof Comment)) { throw new RuntimeException("A comment can not be commented"); } if (this.comment != null) { this.comment.setCommentedNode(null); } this.comment = comment; if (comment != null) { this.comment.setCommentedNode(this); } } /** * Use this to store additional information to this node. * * @param data to be set */ public final void setData(final Object data) { this.data = data; } /** * Sets the end column of this node. * * @param endColumn * the end column of this node */ public final void setEndColumn(final int endColumn) { this.endColumn = endColumn; } /** * Sets the end line of this node. * * @param endLine * the end line of this node */ public final void setEndLine(final int endLine) { this.endLine = endLine; } /** * Return the String representation of this node. * * @return the String representation of this node */ @Override public final String toString() { final DumpVisitor visitor = new DumpVisitor(); accept(visitor, null); return visitor.getSource(); } public final String toStringWithoutComments() { final DumpVisitor visitor = new DumpVisitor(false); accept(visitor, null); return visitor.getSource(); } @Override public final int hashCode() { return toString().hashCode(); } @Override public boolean equals(final Object obj) { if (obj == null || !(obj instanceof Node)) { return false; } return EqualsVisitor.equals(this, (Node) obj); } @Override public Node clone() { return this.accept(new CloneVisitor(), null); } public Node getParentNode() { return parentNode; } public List<Node> getChildrenNodes() { return childrenNodes; } public boolean contains(Node other) { if (getBeginLine() > other.getBeginLine()) return false; if (getBeginLine() == other.getBeginLine() && getBeginColumn() > other.getBeginColumn()) return false; if (getEndLine() < other.getEndLine()) return false; if (getEndLine() == other.getEndLine() && getEndColumn() < other.getEndColumn()) return false; return true; } public void addOrphanComment(Comment comment) { orphanComments.add(comment); comment.setParentNode(this); } /** * This is a list of Comment which are inside the node and are not associated * with any meaningful AST Node. * * For example, comments at the end of methods (immediately before the parenthesis) * or at the end of CompilationUnit are orphan comments. * * When more than one comments preceed a statement, the one immediately preceeding it * it is associated with the statements, while the others are "orphan". * @return all comments that cannot be attributed to a concept */ public List<Comment> getOrphanComments() { return orphanComments; } /** * This is the list of Comment which are contained in the Node either because * they are properly associated to one of its children or because they are floating * around inside the Node * @return all Comments within the node as a list */ public List<Comment> getAllContainedComments() { List<Comment> comments = new LinkedList<Comment>(); comments.addAll(getOrphanComments()); for (Node child : getChildrenNodes()) { if (child.getComment() != null) { comments.add(child.getComment()); } comments.addAll(child.getAllContainedComments()); } return comments; } /** * Assign a new parent to this node, removing it * from the list of children of the previous parent, if any. * * @param parentNode node to be set as parent */ public void setParentNode(Node parentNode) { // remove from old parent, if any if (this.parentNode != null) { this.parentNode.childrenNodes.remove(this); } this.parentNode = parentNode; // add to new parent, if any if (this.parentNode != null) { this.parentNode.childrenNodes.add(this); } } protected void setAsParentNodeOf(List<? extends Node> childNodes) { if (childNodes != null) { Iterator<? extends Node> it = childNodes.iterator(); while (it.hasNext()) { Node current = it.next(); current.setParentNode(this); } } } protected void setAsParentNodeOf(Node childNode) { if (childNode != null) { childNode.setParentNode(this); } } public static final int ABSOLUTE_BEGIN_LINE = -1; public static final int ABSOLUTE_END_LINE = -2; public boolean isPositionedAfter(int line, int column) { if (line == ABSOLUTE_BEGIN_LINE) return true; if (getBeginLine() > line) { return true; } else if (getBeginLine() == line) { return getBeginColumn() > column; } else { return false; } } public boolean isPositionedBefore(int line, int column) { if (line == ABSOLUTE_END_LINE) return true; if (getEndLine() < line) { return true; } else if (getEndLine() == line) { return getEndColumn() < column; } else { return false; } } public boolean hasComment() { return comment != null; } }
27.623342
110
0.600922
abd578549c5ba1cd2d3040209745177e18ca0a25
941
package com.github.webdriverextensions.internal.junitrunner; import com.github.webdriverextensions.Bot; import static com.github.webdriverextensions.internal.utils.StringUtils.quote; import static com.github.webdriverextensions.internal.utils.WebDriverUtils.getScreenshotFilePath; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.slf4j.Logger; public class TakeScreenshotOnFailureRunListener extends RunListener { private final Logger log; private final String fileName; public TakeScreenshotOnFailureRunListener(Logger log, String fileName) { this.log = log; this.fileName = fileName; } @Override public void testFailure(Failure failure) throws Exception { String filePath = getScreenshotFilePath(fileName); log.trace("Saving test failure screenshot to " + quote(filePath)); Bot.takeScreenshot(fileName); } }
34.851852
97
0.774708
145382db8a10b6e156849f3535c1b12926ccb26e
114
package org.fz.complexity.json.drops; /** * @author Zach (findzach.com) */ public class NPCDropDefinition { }
12.666667
37
0.701754
5edec53e7b06b3c01d2e64d53e41547feedfa438
317
package de.pnp.manager.ui.part.interfaces; import javafx.beans.value.ObservableDoubleValue; import javafx.scene.Node; public interface EdgeFactory<E> { Node create(ObservableDoubleValue startX, ObservableDoubleValue startY, ObservableDoubleValue endX, ObservableDoubleValue endY, E content); }
28.818182
83
0.782334
1b4860b5a6e320f0be987aab9a08308874525570
63
package Chapter6; public interface ITire { void tire(); }
10.5
24
0.68254
31e997214c39c681afa22eeafbbfe73b409570c3
2,953
/* * Copyright 2021 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.web; import com.navercorp.pinpoint.common.server.util.ServerBootLogger; import com.navercorp.pinpoint.web.cache.CacheConfiguration; import org.apache.catalina.connector.Connector; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.ImportResource; @SpringBootConfiguration @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, SecurityAutoConfiguration.class}) @ImportResource({"classpath:applicationContext-web.xml", "classpath:servlet-context-web.xml"}) @Import({WebAppPropertySources.class, WebServerConfig.class, WebMvcConfig.class, CacheConfiguration.class}) public class WebApp { private static final ServerBootLogger logger = ServerBootLogger.getLogger(WebApp.class); public static void main(String[] args) { try { WebStarter starter = new WebStarter(WebApp.class, PinpointBasicLoginConfig.class); starter.start(args); } catch (Exception exception) { logger.error("[WebApp] could not launch app.", exception); } } @Bean public ServletWebServerFactory serverFactory(@Value("${server.http.port}") int httpPort) { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); tomcat.addAdditionalTomcatConnectors(createHttpConnector(httpPort)); tomcat.setDisableMBeanRegistry(false); return tomcat; } private Connector createHttpConnector(int httpPort) { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setPort(httpPort); return connector; } }
45.430769
107
0.780224
7ba6cacc985114d965cf5f123312f9010d4edb3f
303
package android.support.v4.p006c.p007a; import android.graphics.drawable.Drawable; /* renamed from: android.support.v4.c.a.f */ class C0072f extends C0071e { C0072f() { } public int m522d(Drawable drawable) { int a = C0080n.m548a(drawable); return a >= 0 ? a : 0; } }
20.2
44
0.636964
cccab2f948c02120f550e3f5c96f023e798838b2
3,478
/***************************************************************************** * This file is part of the Prolog Development Tool (PDT) * * Author: Andreas Becker * WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start * Mail: pdt@lists.iai.uni-bonn.de * Copyright (C): 2012, CS Dept. III, University of Bonn * * All rights reserved. This program is made available under the terms * of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * ****************************************************************************/ package org.cs3.pdt.common.queries; import static org.cs3.prolog.connector.common.QueryUtils.bT; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Vector; import org.cs3.pdt.common.PDTCommonPredicates; import org.cs3.prolog.connector.common.Debug; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.search.ui.text.Match; public class MetaPredicatesSearchQuery extends MarkerCreatingSearchQuery { private static final String ATTRIBUTE = "pdt.meta.predicate"; private static final String SMELL_NAME = "PDT_Quickfix"; private static final String QUICKFIX_DESCRIPTION = "PDT_QuickfixDescription"; private static final String QUICKFIX_ACTION = "PDT_QuickfixAction"; public MetaPredicatesSearchQuery(boolean createMarkers) { super(createMarkers, ATTRIBUTE, ATTRIBUTE); } @Override public void setProjectScope(IProject project) { super.setProjectScope(project); if (project == null) { setSearchType("Undeclared meta predicates"); } else { setSearchType("Undeclared meta predicates in project " + project.getName()); } } @Override protected String buildSearchQuery() { return bT(PDTCommonPredicates.FIND_UNDECLARED_META_PREDICATE, getProjectPath() == null ? "_" : getProjectPath(), "Module", "Name", "Arity", "MetaSpec", "MetaSpecAtom", "File", "Line", "PropertyList", "Directive"); } @SuppressWarnings("unchecked") @Override protected Match constructPrologMatchForAResult(Map<String, Object> m) throws IOException { String definingModule = m.get("Module").toString(); String functor = m.get("Name").toString(); int arity=-1; try { arity = Integer.parseInt(m.get("Arity").toString()); } catch (NumberFormatException e) {} IFile file = findFile(m.get("File").toString()); if (getProject() != null && !getProject().equals(file.getProject())) { return null; } int line = Integer.parseInt(m.get("Line").toString()); Object prop = m.get("PropertyList"); List<String> properties = null; if (prop instanceof Vector<?>) { properties = (Vector<String>)prop; } Match match = createUniqueMatch(PROLOG_MATCH_KIND_DEFAULT, definingModule, functor, arity, file, line, properties, "", "definition"); if (createMarkers && match != null) { try { String metaSpec = m.get("MetaSpecAtom").toString(); IMarker marker = createMarker(file, "Meta predicate: " + metaSpec, line); marker.setAttribute(SMELL_NAME, "Meta Predicate"); marker.setAttribute(QUICKFIX_ACTION, m.get("Directive").toString()); marker.setAttribute(QUICKFIX_DESCRIPTION, "Declare meta predicate"); } catch (CoreException e) { Debug.report(e); } } return match; } }
32.203704
135
0.690052
7b2d6b85ae1c77bac30240fdb76100ebc4045d6d
628
package sanity.basictests; import edu.umd.cs.mtc.MultithreadedTestCase; import edu.umd.cs.mtc.Threaded; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author <a href="mailto:jvb@newtec.eu">Jan Van Besien</a> */ public class SanityWaitForTickBlocksThread extends MultithreadedTestCase { Thread t; @Threaded public void thread1() { t = Thread.currentThread(); waitForTick(2); } @Threaded public void thread2() { waitForTick(1); assertEquals(Thread.State.WAITING, t.getState()); } @Test public void test() { } }
18.470588
72
0.651274
7006a128c9f65ad3d5e94fa84d525bba5be2b7e9
723
package org.tiankafei.aviator.extend.exception; /** * @author tiankafei * @since 1.0 **/ public class AviatorException extends RuntimeException { public AviatorException() { super(); } public AviatorException(String message) { super(message); } public AviatorException(String message, Throwable cause) { super(message, cause); } public AviatorException(Throwable cause) { super(cause); } protected AviatorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
22.59375
69
0.625173
4d0d5c18f7e9b20f6e90abee03fc27684a074967
541
package gov.nasa.jpf.symbc.veritesting.ast.transformations.ssaToAst; import com.ibm.wala.ssa.ISSABasicBlock; import za.ac.sun.cs.green.expr.Expression; /** * This represents a phi condition, that associates a "condition" with the "then" and the "else side. */ public class PhiCondition { public enum Branch {Then, Else}; public final Branch branch; public final Expression condition; public PhiCondition(Branch branch, Expression condition) { this.branch = branch; this.condition = condition; } }
24.590909
101
0.719039
c61a2d65fb80e3aa509dc43d1dad40edc65c1a17
1,334
package com.prowidesoftware.swift.model.mx.dic; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for TransactionOperationType1Code. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="TransactionOperationType1Code"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="AMND"/&gt; * &lt;enumeration value="CANC"/&gt; * &lt;enumeration value="CORR"/&gt; * &lt;enumeration value="NEWT"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "TransactionOperationType1Code") @XmlEnum public enum TransactionOperationType1Code { /** * Transaction amends a previously sent transaction. * */ AMND, /** * Transaction requests the deletion/cancellation of a previously sent transaction. * */ CANC, /** * Transaction corrects errors in a previously sent transaction. * */ CORR, /** * Transaction is a new transaction. * */ NEWT; public String value() { return name(); } public static TransactionOperationType1Code fromValue(String v) { return valueOf(v); } }
21.174603
95
0.63943
16ffa670da821e9a54a77389aa69ea9c576ecec4
3,540
package no.unicornis.altinn.soap.models; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Created by taldev on 14/10/16. * * Originally created by tba @ brreg. * * Helper class to perform a file upload. */ public class UploadFile { private String externalServiceCode; private int externalServiceEditionCode; private ArrayList<String> receiverList; private ArrayList<String> fileList; private String zipFileName; private String sendersReference; @SuppressWarnings("CanBeFinal") private Map<String, String> properties; public UploadFile() { receiverList = new ArrayList<>(); fileList = new ArrayList<>(); properties = new HashMap<>(); } public String getExternalServiceCode() { return externalServiceCode; } public void setExternalServiceCode(String externalServiceCode) { this.externalServiceCode = externalServiceCode; } public int getExternalServiceEditionCode() { return externalServiceEditionCode; } public void setExternalServiceEditionCode(int externalServiceEditionCode) { this.externalServiceEditionCode = externalServiceEditionCode; } public String getZipFileName() { return zipFileName; } public void setZipFileName(String fileName) { this.zipFileName = fileName; } public String getSendersReference() { return sendersReference; } public void setSendersReference(String sendersReference) { this.sendersReference = sendersReference; } public ArrayList<String> getFileList() { return fileList; } @SuppressWarnings("unused") public void setFileList(ArrayList<String> fileList) { this.fileList = fileList; } public void addFile(String file) { this.fileList.add(file); } public ArrayList<String> getReceiverList() { return receiverList; } @SuppressWarnings("unused") public void setReceiverList(ArrayList<String> receiverList) { this.receiverList = receiverList; } public void addReceiver(String receiver) { this.receiverList.add(receiver); } public Map<String, String> getProperties() { return properties; } @SuppressWarnings("unused") public void addProperty(String key, String value) { this.properties.put(key, value); } @Override public String toString() { String receiverListString; String fileListString; if (!receiverList.isEmpty()) { receiverListString = receiverList.get(0); for (int i = 1; i < receiverList.size(); i++) { receiverListString += ", " + receiverList.get(i); } } else { receiverListString = ""; } if (!fileList.isEmpty()) { fileListString = fileList.get(0); for (int i = 1; i < fileList.size(); i++) { fileListString += ", " + fileList.get(i); } } else { fileListString = ""; } return "Initiate {" + '\'' + "externalServiceCode: " + externalServiceCode + '\'' + ", externalServiceEditionCode: " + externalServiceEditionCode + '\'' + ", filename(s): " + fileListString + '\'' + ", zipFileName: " + zipFileName + '\'' + ", sendersReference: " + sendersReference + '\'' + ", receiver(s): " + receiverListString; } }
27.874016
86
0.614689
91eee8a89ce3b3e32c50d0818b1c0a3b84d2600e
1,162
package com.android_mvc.framework.ui.view; import java.util.HashMap; import android.content.Context; import android.widget.EditText; /** * EditTextのラッパークラス。 * @author id:language_and_engineering * */ public class MEditText extends EditText implements IFWView { public MEditText(Context context) { super(context); } // パラメータ保持 HashMap<String, Object> view_params = new HashMap<String, Object>(); @Override public Object getViewParam(String key) { return view_params.get(key); } @Override public void setViewParam(String key, Object val) { view_params.put(key, val); } // 以下は属性操作 public MEditText widthPx(int px) { setWidth(px); // http://www.javadrive.jp/android/textview/index8.html return this; } public MEditText text(String s) { setText(s); return this; } public String text() { return this.getText().toString(); // http://stackoverflow.com/questions/2785907/what-does-an-edittext-gettext-in-android-return-if-it-is-empty } }
20.385965
121
0.612737
7ce3669a464f77c54115ffe78443f4fac3538886
1,191
// Copyright 2015 The Vanadium Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package io.v.v23.vdl; /** * VdlUint64 is a representation of a VDL uint64. */ public class VdlUint64 extends VdlValue { private static final long serialVersionUID = 1L; private final long value; public VdlUint64(VdlType type, long value) { super(type); assertKind(Kind.UINT64); this.value = value; } public VdlUint64(long value) { this(Types.UINT64, value); } public VdlUint64() { this(0); } protected VdlUint64(VdlType type) { this(type, 0); } public long getValue() { return this.value; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof VdlUint64)) return false; VdlUint64 other = (VdlUint64) obj; return value == other.value; } @Override public int hashCode() { return Long.valueOf(value).hashCode(); } @Override public String toString() { return Long.toString(value); } }
21.654545
60
0.61377
767213221b54d8f34a3ee9c01e41462068fbf4fa
5,650
package com.tomlai.app; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private DisplayMetrics mPhone; private String injuries_number; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);//設定螢幕不隨手機旋轉 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//設定螢幕直向顯示 //讀取手機解析度 mPhone = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(mPhone); Button button0 = (Button) findViewById(R.id.button0); Button button1 = (Button) findViewById(R.id.button1); Button button2 = (Button) findViewById(R.id.button2); Button button3 = (Button) findViewById(R.id.button3); Button button4 = (Button) findViewById(R.id.button4); Button button5 = (Button) findViewById(R.id.button5); Button button6 = (Button) findViewById(R.id.button6); Button button6Up = (Button) findViewById(R.id.button6Up); LocationManager status = (LocationManager) (this.getSystemService(Context.LOCATION_SERVICE)); if(!(status.isProviderEnabled(LocationManager.GPS_PROVIDER) || status.isProviderEnabled(LocationManager.NETWORK_PROVIDER))) { // 無提供者, 顯示提示訊息 AlertDialog.Builder ad=new AlertDialog.Builder(MainActivity.this); //創建訊息方塊 ad.setTitle("偵測到未開啟GPS"); ad.setMessage("請先開啟GPS?"); ad.setPositiveButton("前往開啟", new DialogInterface.OnClickListener() { //按"是",則退出應用程式 public void onClick(DialogInterface dialog, int i) { Intent intents = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intents); } }); ad.show();//顯示訊息視窗 } Intent intent = new Intent(MainActivity.this, GetLocation.class); //啟動Service定位 startService(intent); button0.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); injuries_number = "0"; intent.setClass(MainActivity.this, inform_unit.class); intent.putExtra("injuries_number", injuries_number); startActivity(intent); MainActivity.this.finish(); } }); button1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { injuries_number = "1"; activityJump(); } }); button2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { injuries_number = "2"; activityJump(); } }); button3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { injuries_number = "3"; activityJump(); } }); button4.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { injuries_number = "4"; activityJump(); } }); button5.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { injuries_number = "5"; activityJump(); } }); button6.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { injuries_number = "6"; activityJump(); } }); button6Up.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { EditText editText = (EditText) findViewById(R.id.editText); injuries_number = editText.getText().toString(); activityJump(); } }); } public void activityJump() { Intent intent = new Intent(); intent.putExtra("injuries_number", injuries_number); intent.setClass(MainActivity.this, emergy.class); startActivity(intent); MainActivity.this.finish(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { //確定按下退出鍵 ConfirmExit(); //呼叫ConfirmExit()函數 return true; } return super.onKeyDown(keyCode, event); } public void ConfirmExit(){ AlertDialog.Builder ad=new AlertDialog.Builder(MainActivity.this); //創建訊息方塊 ad.setTitle("離開"); ad.setMessage("確定要離開?"); ad.setPositiveButton("是", new DialogInterface.OnClickListener() { //按"是",則退出應用程式 public void onClick(DialogInterface dialog, int i) { MainActivity.this.finish();//關閉activity } }); ad.setNegativeButton("否", new DialogInterface.OnClickListener() { //按"否",則不執行任何操作 public void onClick(DialogInterface dialog, int i) { } }); ad.show();//顯示訊息視窗 } }
33.431953
131
0.606726
90cb931749db5793d3b7982fff451550164c8f9a
31,117
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.jaxws.support; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; import javax.jws.Oneway; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebParam.Mode; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.ParameterStyle; import javax.jws.soap.SOAPBinding.Style; import javax.xml.bind.annotation.XmlElement; import javax.xml.namespace.QName; import javax.xml.ws.Action; import javax.xml.ws.Holder; import javax.xml.ws.RequestWrapper; import javax.xml.ws.Response; import javax.xml.ws.ResponseWrapper; import javax.xml.ws.WebFault; import org.apache.cxf.common.classloader.ClassLoaderUtils; import org.apache.cxf.common.i18n.Message; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.common.util.PackageUtils; import org.apache.cxf.common.util.StringUtils; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.jaxws.JaxWsConfigurationException; import org.apache.cxf.service.factory.ServiceConstructionException; import org.apache.cxf.service.model.InterfaceInfo; import org.apache.cxf.service.model.MessageInfo; import org.apache.cxf.service.model.MessagePartInfo; import org.apache.cxf.service.model.OperationInfo; import org.apache.cxf.wsdl.service.factory.AbstractServiceConfiguration; import org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean; public class JaxWsServiceConfiguration extends AbstractServiceConfiguration { private static final Logger LOG = LogUtils.getL7dLogger(JaxWsServiceConfiguration.class); private JaxWsImplementorInfo implInfo; /** * We retrieve the wrapper methods more than once * while creating an endpoint. So caching the wrapper * classes saves CPU time. * * It would also be good to cache across creations, * but Method.equals isn't good enough. */ private Map<Object, Class<?>> responseMethodClassCache; private Map<Object, Class<?>> requestMethodClassCache; private List<Method> responseMethodClassNotFoundCache; private List<Method> requestMethodClassNotFoundCache; private Map<Method, Annotation[][]> methodAnnotationCache; public JaxWsServiceConfiguration() { responseMethodClassCache = new HashMap<>(); requestMethodClassCache = new HashMap<>(); responseMethodClassNotFoundCache = new ArrayList<>(); requestMethodClassNotFoundCache = new ArrayList<>(); methodAnnotationCache = new HashMap<>(); } @Override public void setServiceFactory(ReflectionServiceFactoryBean serviceFactory) { super.setServiceFactory(serviceFactory); implInfo = ((JaxWsServiceFactoryBean)serviceFactory).getJaxWsImplementorInfo(); } @Override public String getServiceName() { QName service = implInfo.getServiceName(); return service.getLocalPart(); } @Override public String getServiceNamespace() { String ret = super.getServiceNamespace(); if (ret != null) { return ret; } QName service = implInfo.getServiceName(); return service.getNamespaceURI(); } @Override public QName getEndpointName() { return implInfo.getEndpointName(); } @Override public QName getInterfaceName() { return implInfo.getInterfaceName(); } @Override public String getWsdlURL() { String wsdlLocation = implInfo.getWsdlLocation(); if (wsdlLocation != null && wsdlLocation.length() > 0) { return wsdlLocation; } return null; } @Override public QName getOperationName(InterfaceInfo intf, Method method) { method = getDeclaredMethod(method); WebMethod wm = method.getAnnotation(WebMethod.class); if (wm != null) { String name = wm.operationName(); if (name.length() == 0) { name = method.getName(); } return new QName(intf.getName().getNamespaceURI(), name); } return new QName(intf.getName().getNamespaceURI(), method.getName()); } public Boolean isWebMethod(final Method method) { if (method == null || method.getReturnType().equals(Future.class) || method.getReturnType().equals(Response.class) || method.isSynthetic()) { return Boolean.FALSE; } WebMethod wm = method.getAnnotation(WebMethod.class); Class<?> cls = method.getDeclaringClass(); if ((wm != null) && wm.exclude()) { return Boolean.FALSE; } if ((wm != null && !wm.exclude()) || (implInfo.getSEIClass() != null && cls.isInterface() && cls.isAssignableFrom(implInfo.getSEIClass()))) { return Boolean.TRUE; } if (method.getDeclaringClass().isInterface()) { return hasWebServiceAnnotation(method); } if (implInfo.getSEIClass() == null) { return hasWebServiceAnnotation(method) && !Modifier.isFinal(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()); } return implInfo.getSEIClass().isAssignableFrom(method.getDeclaringClass()); } @Override public Boolean isOperation(final Method method) { if (Object.class.equals(method.getDeclaringClass())) { return false; } if (method.getDeclaringClass() == implInfo.getSEIClass()) { WebMethod wm = method.getAnnotation(WebMethod.class); if (wm != null && wm.exclude()) { Message message = new Message("WEBMETHOD_EXCLUDE_NOT_ALLOWED", LOG, method.getName()); throw new JaxWsConfigurationException(message); } } Class<?> implClz = implInfo.getImplementorClass(); Method m = getDeclaredMethod(implClz, method); if (m != null) { WebMethod wm = m.getAnnotation(WebMethod.class); if (wm != null && wm.exclude()) { return Boolean.FALSE; } } if (isWebMethod(m)) { return true; } return isWebMethod(getDeclaredMethod(method)); } private boolean hasWebServiceAnnotation(Method method) { return method.getDeclaringClass().getAnnotation(WebService.class) != null; } Method getDeclaredMethod(Method method) { return getDeclaredMethod(implInfo.getEndpointClass(), method); } private Method getDeclaredMethod(Class<?> endpointClass, Method method) { if (!method.getDeclaringClass().equals(endpointClass)) { try { method = endpointClass.getMethod(method.getName(), method.getParameterTypes()); } catch (SecurityException e) { throw new ServiceConstructionException(e); } catch (NoSuchMethodException e) { return isWebMethod(method) ? method : null; } } return method; } @Override public QName getInPartName(OperationInfo op, Method method, int paramNumber) { if (paramNumber < 0) { return null; } return getPartName(op, method, paramNumber, op.getInput(), "arg", true); } @Override public QName getInParameterName(OperationInfo op, Method method, int paramNumber) { if (paramNumber < 0) { return null; } return getParameterName(op, method, paramNumber, op.getInput().size(), "arg", true); } private QName getPartName(OperationInfo op, Method method, int paramNumber, MessageInfo mi, String prefix, boolean isIn) { int partIndex = getPartIndex(method, paramNumber, isIn); method = getDeclaredMethod(method); WebParam param = getWebParam(method, paramNumber); String tns = mi.getName().getNamespaceURI(); String local = null; if (param != null) { if (Boolean.TRUE.equals(isRPC(method)) || isDocumentBare(method) || param.header()) { local = param.partName(); } if (local == null || local.length() == 0) { local = param.name(); } } if (local == null || local.length() == 0) { if (Boolean.TRUE.equals(isRPC(method)) || !Boolean.FALSE.equals(isWrapped(method))) { local = getDefaultLocalName(op, method, paramNumber, partIndex, prefix); } else { local = getOperationName(op.getInterface(), method).getLocalPart(); } } return new QName(tns, local); } private int getPartIndex(Method method, int paraNumber, boolean isIn) { int ret = 0; if (isIn && isInParam(method, paraNumber)) { for (int i = 0; i < paraNumber; i++) { if (isInParam(method, i)) { ret++; } } } if (!isIn && isOutParam(method, paraNumber)) { if (method.getReturnType() != Void.class && method.getReturnType() != Void.TYPE) { ret++; } for (int i = 0; i < paraNumber; i++) { if (isOutParam(method, i)) { ret++; } } } return ret; } private QName getParameterName(OperationInfo op, Method method, int paramNumber, int curSize, String prefix, boolean input) { int partIndex = getPartIndex(method, paramNumber, input); method = getDeclaredMethod(method); WebParam param = getWebParam(method, paramNumber); String tns = null; String local = null; if (param != null) { tns = param.targetNamespace(); local = param.name(); } if (tns == null || tns.length() == 0) { QName wrappername = null; if (input) { wrappername = getRequestWrapperName(op, method); } else { wrappername = getResponseWrapperName(op, method); } if (wrappername != null) { tns = wrappername.getNamespaceURI(); } } if (tns == null || tns.length() == 0) { tns = op.getName().getNamespaceURI(); } if (local == null || local.length() == 0) { if (Boolean.TRUE.equals(isRPC(method)) || !Boolean.FALSE.equals(isWrapped(method))) { local = getDefaultLocalName(op, method, paramNumber, partIndex, prefix); } else { local = getOperationName(op.getInterface(), method).getLocalPart(); if (!input) { local += "Response"; } } } return new QName(tns, local); } private String getDefaultLocalName(OperationInfo op, Method method, int paramNumber, int partIndex, String prefix) { String paramName = null; if (paramNumber != -1) { paramName = prefix + partIndex; } else { paramName = prefix; } return paramName; } private WebParam getWebParam(Method method, int parameter) { // we could really use a centralized location for this. Annotation[][] annotations = methodAnnotationCache.get(method); if (annotations == null) { annotations = method.getParameterAnnotations(); methodAnnotationCache.put(method, annotations); } if (parameter >= annotations.length) { return null; } for (int i = 0; i < annotations[parameter].length; i++) { Annotation annotation = annotations[parameter][i]; // With the ibm jdk, the condition: // if (annotation.annotationType().equals(WebParam.class)) { // SOMETIMES returns false even when the annotation type // is a WebParam. Doing an instanceof check or using the // == operator seems to give the desired result. if (annotation instanceof WebParam) { return (WebParam)annotation; } } return null; } @Override public String getRequestWrapperPartName(OperationInfo op, Method method) { method = getDeclaredMethod(method); RequestWrapper rw = method.getAnnotation(RequestWrapper.class); if (rw != null) { return getWithReflection(RequestWrapper.class, rw, "partName"); } return null; } @Override public String getResponseWrapperPartName(OperationInfo op, Method method) { method = getDeclaredMethod(method); WebResult webResult = getWebResult(method); ResponseWrapper rw = method.getAnnotation(ResponseWrapper.class); if (rw != null) { String pn = getWithReflection(ResponseWrapper.class, rw, "partName"); if (pn != null) { return pn; } } int countOut = 0; int countHeaders = 0; if (webResult != null && webResult.header()) { countHeaders++; } else if (method.getReturnType() != Void.TYPE) { countOut++; } for (int x = 0; x < method.getParameterTypes().length; x++) { WebParam parm = getWebParam(method, x); if (parm != null) { if (parm.header()) { countHeaders++; } if (parm.mode() != WebParam.Mode.IN) { countOut++; } } } if (countHeaders > 0 && countOut == 0) { //all outs are headers, thus it's an empty body part //thus return the default for an empty part of "result" return "result"; } return null; } public String getFaultMessageName(OperationInfo op, Class<?> exClass, Class<?> beanClass) { WebFault f = exClass.getAnnotation(WebFault.class); if (f != null) { return getWithReflection(WebFault.class, f, "messageName"); } return null; } private <T> String getWithReflection(Class<T> cls, T obj, String name) { try { String s = cls.getMethod(name).invoke(obj).toString(); if (!StringUtils.isEmpty(s)) { return s; } } catch (Exception e) { //ignore = possibly JAX-WS 2.1 } return null; } @Override public QName getOutParameterName(OperationInfo op, Method method, int paramNumber) { method = getDeclaredMethod(method); if (paramNumber >= 0) { return getParameterName(op, method, paramNumber, op.getOutput().size(), "return", false); } WebResult webResult = getWebResult(method); String tns = null; String local = null; if (webResult != null) { tns = webResult.targetNamespace(); local = webResult.name(); } if (tns == null || tns.length() == 0) { QName wrappername = getResponseWrapperName(op, method); if (wrappername != null) { tns = wrappername.getNamespaceURI(); } } if (tns == null || tns.length() == 0) { tns = op.getName().getNamespaceURI(); } if (local == null || local.length() == 0) { if (Boolean.TRUE.equals(isRPC(method)) || !Boolean.FALSE.equals(isWrapped(method))) { local = getDefaultLocalName(op, method, paramNumber, op.getOutput().size(), "return"); } else { local = getOperationName(op.getInterface(), method).getLocalPart() + "Response"; } } return new QName(tns, local); } @Override public QName getOutPartName(OperationInfo op, Method method, int paramNumber) { method = getDeclaredMethod(method); if (paramNumber >= 0) { return getPartName(op, method, paramNumber, op.getOutput(), "return", false); } WebResult webResult = getWebResult(method); String tns = op.getOutput().getName().getNamespaceURI(); String local = null; if (webResult != null) { if (Boolean.TRUE.equals(isRPC(method)) || isDocumentBare(method)) { local = webResult.partName(); } if (local == null || local.length() == 0) { local = webResult.name(); } } if (local == null || local.length() == 0) { if (Boolean.TRUE.equals(isRPC(method)) || !Boolean.FALSE.equals(isWrapped(method))) { local = "return"; } else { local = getOperationName(op.getInterface(), method).getLocalPart() + "Response"; } } return new QName(tns, local); } @Override public Boolean isInParam(Method method, int j) { if (j < 0) { return Boolean.FALSE; } method = getDeclaredMethod(method); WebParam webParam = getWebParam(method, j); return webParam == null || (webParam.mode().equals(Mode.IN) || webParam.mode().equals(Mode.INOUT)); } private WebResult getWebResult(Method method) { return method.getAnnotation(WebResult.class); } @Override public Boolean isOutParam(Method method, int j) { method = getDeclaredMethod(method); if (j == -1) { return !method.getReturnType().equals(void.class); } WebParam webParam = getWebParam(method, j); if (webParam != null && (webParam.mode().equals(Mode.OUT) || webParam.mode().equals(Mode.INOUT))) { return Boolean.TRUE; } return method.getParameterTypes()[j] == Holder.class; } @Override public Boolean isInOutParam(Method method, int j) { method = getDeclaredMethod(method); if (j == -1) { return !method.getReturnType().equals(void.class); } WebParam webParam = getWebParam(method, j); if (webParam != null && webParam.mode().equals(Mode.INOUT)) { return Boolean.TRUE; } return Boolean.FALSE; } @Override public QName getRequestWrapperName(OperationInfo op, Method method) { Method m = getDeclaredMethod(method); RequestWrapper rw = m.getAnnotation(RequestWrapper.class); String nm = null; String lp = null; if (rw != null) { nm = rw.targetNamespace(); lp = rw.localName(); } WebMethod meth = m.getAnnotation(WebMethod.class); if (meth != null && StringUtils.isEmpty(lp)) { lp = meth.operationName(); } if (StringUtils.isEmpty(nm)) { nm = op.getName().getNamespaceURI(); } if (!StringUtils.isEmpty(nm) && !StringUtils.isEmpty(lp)) { return new QName(nm, lp); } return null; } @Override public QName getResponseWrapperName(OperationInfo op, Method method) { Method m = getDeclaredMethod(method); ResponseWrapper rw = m.getAnnotation(ResponseWrapper.class); String nm = null; String lp = null; if (rw != null) { nm = rw.targetNamespace(); lp = rw.localName(); } WebMethod meth = m.getAnnotation(WebMethod.class); if (meth != null && StringUtils.isEmpty(lp)) { lp = meth.operationName(); if (!StringUtils.isEmpty(lp)) { lp += "Response"; } } if (StringUtils.isEmpty(nm)) { nm = op.getName().getNamespaceURI(); } if (!StringUtils.isEmpty(nm) && !StringUtils.isEmpty(lp)) { return new QName(nm, lp); } return null; } @Override public Class<?> getResponseWrapper(Method selected) { if (this.responseMethodClassNotFoundCache.contains(selected)) { return null; } Class<?> cachedClass = responseMethodClassCache.get(selected); if (cachedClass != null) { return cachedClass; } Method m = getDeclaredMethod(selected); ResponseWrapper rw = m.getAnnotation(ResponseWrapper.class); String clsName = ""; if (rw == null) { clsName = getPackageName(selected) + ".jaxws." + StringUtils.capitalize(selected.getName()) + "Response"; } else { clsName = rw.className(); } if (clsName.length() > 0) { cachedClass = responseMethodClassCache.get(clsName); if (cachedClass != null) { responseMethodClassCache.put(selected, cachedClass); return cachedClass; } try { Class<?> r = ClassLoaderUtils.loadClass(clsName, implInfo.getEndpointClass()); responseMethodClassCache.put(clsName, r); responseMethodClassCache.put(selected, r); if (r.equals(m.getReturnType())) { LOG.log(Level.WARNING, "INVALID_RESPONSE_WRAPPER", new Object[] {clsName, m.getReturnType().getName()}); } return r; } catch (ClassNotFoundException e) { //do nothing, we will mock a schema for wrapper bean later on } } responseMethodClassNotFoundCache.add(selected); return null; } @Override public String getResponseWrapperClassName(Method selected) { Method m = getDeclaredMethod(selected); ResponseWrapper rw = m.getAnnotation(ResponseWrapper.class); String clsName = ""; if (rw != null) { clsName = rw.className(); } if (clsName.length() > 0) { return clsName; } return null; } public String getRequestWrapperClassName(Method selected) { Method m = getDeclaredMethod(selected); RequestWrapper rw = m.getAnnotation(RequestWrapper.class); String clsName = ""; if (rw != null) { clsName = rw.className(); } if (clsName.length() > 0) { return clsName; } return null; } @Override public Class<?> getRequestWrapper(Method selected) { if (this.requestMethodClassNotFoundCache.contains(selected)) { return null; } Class<?> cachedClass = requestMethodClassCache.get(selected); if (cachedClass != null) { return cachedClass; } Method m = getDeclaredMethod(selected); RequestWrapper rw = m.getAnnotation(RequestWrapper.class); String clsName = ""; if (rw == null) { clsName = getPackageName(selected) + ".jaxws." + StringUtils.capitalize(selected.getName()); } else { clsName = rw.className(); } if (clsName.length() > 0) { cachedClass = requestMethodClassCache.get(clsName); if (cachedClass != null) { requestMethodClassCache.put(selected, cachedClass); return cachedClass; } try { Class<?> r = ClassLoaderUtils.loadClass(clsName, implInfo.getEndpointClass()); requestMethodClassCache.put(clsName, r); requestMethodClassCache.put(selected, r); if (m.getParameterTypes().length == 1 && r.equals(m.getParameterTypes()[0])) { LOG.log(Level.WARNING, "INVALID_REQUEST_WRAPPER", new Object[] {clsName, m.getParameterTypes()[0].getName()}); } return r; } catch (ClassNotFoundException e) { //do nothing, we will mock a schema for wrapper bean later on } } requestMethodClassNotFoundCache.add(selected); return null; } private static String getPackageName(Method method) { return PackageUtils.getPackageName(method.getDeclaringClass()); } @Override public QName getFaultName(InterfaceInfo service, OperationInfo o, Class<?> exClass, Class<?> beanClass) { WebFault fault = exClass.getAnnotation(WebFault.class); if (fault != null) { String name = fault.name(); if (name.length() == 0) { name = exClass.getSimpleName(); } String ns = fault.targetNamespace(); if (ns.length() == 0) { ns = service.getName().getNamespaceURI(); } return new QName(ns, name); } return null; } @Override public Boolean isWrapped(Method m) { // see if someone overrode the default value if (getServiceFactory().getWrapped() != null) { return getServiceFactory().getWrapped(); } m = getDeclaredMethod(m); SOAPBinding ann = m.getAnnotation(SOAPBinding.class); if (ann != null) { if (ann.style().equals(Style.RPC)) { Message message = new Message("SOAPBinding_MESSAGE_RPC", LOG, m.getName()); throw new Fault(new JaxWsConfigurationException(message)); } return !(ann.parameterStyle().equals(ParameterStyle.BARE)); } return isWrapped(); } @Override public Boolean isWrapped() { SOAPBinding ann = implInfo.getEndpointClass().getAnnotation(SOAPBinding.class); if (ann != null) { return !(ann.parameterStyle().equals(ParameterStyle.BARE) || ann.style().equals(Style.RPC)); } return null; } @Override public Boolean isHeader(Method method, int j) { method = getDeclaredMethod(method); if (j >= 0) { WebParam webParam = getWebParam(method, j); return webParam != null && webParam.header(); } WebResult webResult = getWebResult(method); return webResult != null && webResult.header(); } @Override public String getStyle() { SOAPBinding ann = implInfo.getEndpointClass().getAnnotation(SOAPBinding.class); if (ann != null) { return ann.style().toString().toLowerCase(); } return super.getStyle(); } private boolean isDocumentBare(Method method) { SOAPBinding ann = method.getAnnotation(SOAPBinding.class); if (ann != null) { return ann.style().equals(SOAPBinding.Style.DOCUMENT) && ann.parameterStyle().equals(SOAPBinding.ParameterStyle.BARE); } ann = implInfo.getEndpointClass().getAnnotation(SOAPBinding.class); if (ann != null) { return ann.style().equals(SOAPBinding.Style.DOCUMENT) && ann.parameterStyle().equals(SOAPBinding.ParameterStyle.BARE); } return false; } @Override public Boolean isRPC(Method method) { SOAPBinding ann = method.getAnnotation(SOAPBinding.class); if (ann != null) { return ann.style().equals(SOAPBinding.Style.RPC); } ann = implInfo.getEndpointClass().getAnnotation(SOAPBinding.class); if (ann != null) { return ann.style().equals(SOAPBinding.Style.RPC); } return super.isRPC(method); } @Override public Boolean hasOutMessage(Method method) { method = getDeclaredMethod(method); return !method.isAnnotationPresent(Oneway.class); } @Override public String getAction(OperationInfo op, Method method) { method = getDeclaredMethod(method); WebMethod wm = method.getAnnotation(WebMethod.class); String action = ""; if (wm != null) { action = wm.action(); } if (StringUtils.isEmpty(action)) { Action act = method.getAnnotation(Action.class); if (act != null) { action = act.input(); } } return action; } public Boolean isHolder(Class<?> cls, Type type) { return Holder.class.equals(cls); } public Type getHolderType(Class<?> cls, Type type) { if (cls.equals(Holder.class) && type instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType)type; return paramType.getActualTypeArguments()[0]; } return cls; } public Boolean isWrapperPartQualified(MessagePartInfo mpi) { Annotation[] annotations = (Annotation[])mpi.getProperty("parameter.annotations"); if (annotations != null) { for (Annotation an : annotations) { String tns = null; if (an instanceof WebParam) { tns = ((WebParam)an).targetNamespace(); } else if (an instanceof WebResult) { tns = ((WebResult)an).targetNamespace(); } if (tns != null && !StringUtils.isEmpty(tns)) { return Boolean.TRUE; } } } return null; } public Long getWrapperPartMinOccurs(MessagePartInfo mpi) { Annotation[] a = (Annotation[])mpi.getProperty(ReflectionServiceFactoryBean.PARAM_ANNOTATION); if (a != null) { for (Annotation a2 : a) { if (a2 instanceof XmlElement) { XmlElement e = (XmlElement)a2; if (e.required()) { return 1L; } } } } return null; } }
34.651448
109
0.57663
a3701d29708312d59bd245846120c72d3bd206da
1,621
package de.undercouch.citeproc.tool.shell; import de.undercouch.citeproc.tool.AbstractCSLToolCommand; import de.undercouch.underline.CommandDesc; import de.undercouch.underline.CommandDescList; /** * Contains the configuration for all additional shell commands * @author Michel Kraemer */ public final class AdditionalShellCommands { /** * Configures all additional shell commands * @param command the configured command */ @CommandDescList({ @CommandDesc(longName = "load", description = "load an input bibliography from a file", command = ShellLoadCommand.class), @CommandDesc(longName = "get", description = "get values of shell variables", command = ShellGetCommand.class), @CommandDesc(longName = "set", description = "assign values to shell variables", command = ShellSetCommand.class), @CommandDesc(longName = "help", description = "display help for a given command", command = ShellHelpCommand.class), @CommandDesc(longName = "exit", description = "exit the interactive shell", command = ShellExitCommand.class), @CommandDesc(longName = "quit", description = "exit the interactive shell", command = ShellQuitCommand.class), }) public void setCommand(@SuppressWarnings("unused") AbstractCSLToolCommand command) { // we don't have to do anything here } }
40.525
88
0.60765
7399a6c139ffd75c124e5c7573eb13d53dbb9f3f
10,528
/* ### * IP: GHIDRA * * 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 docking.widgets.filechooser; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.io.File; import java.io.FileFilter; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.filechooser.FileSystemView; import ghidra.util.filechooser.GhidraFileChooserModel; import resources.ResourceManager; import utility.function.Callback; /** * A default implementation of the file chooser model that browses the local file system. * */ public class LocalFileChooserModel implements GhidraFileChooserModel { private static final ImageIcon PROBLEM_FILE_ICON = ResourceManager.loadImage("images/unknown.gif"); private static final ImageIcon PENDING_ROOT_ICON = ResourceManager.loadImage("images/famfamfam_silk_icons_v013/drive.png"); private static final FileSystemRootInfo FS_ROOT_INFO = new FileSystemRootInfo(); private static final FileSystemView FS_VIEW = FileSystemView.getFileSystemView(); /** * This is a cache of file icons, as returned from the OS's file icon service. * <p> * This cache is cleared each time a directory is requested (via * {@link #getListing(File, FileFilter)} so that any changes to a file's icon are visible the * next time the user hits refresh or navigates into a directory. */ private Map<File, Icon> fileIconMap = new HashMap<>(); private Callback callback; @Override public char getSeparator() { return File.separatorChar; } @Override public void setModelUpdateCallback(Callback callback) { this.callback = callback; } @Override public File getHomeDirectory() { return new File(System.getProperty("user.home")); } @Override public File getDesktopDirectory() { String userHomeProp = System.getProperty("user.home"); if (userHomeProp == null) { return null; } File home = new File(userHomeProp); File desktop = new File(home, "Desktop"); return desktop.isDirectory() ? desktop : null; } @Override public List<File> getRoots(boolean forceUpdate) { if (FS_ROOT_INFO.isEmpty() || forceUpdate) { FS_ROOT_INFO.updateRootInfo(callback); } return FS_ROOT_INFO.getRoots(); } @Override public List<File> getListing(File directory, FileFilter filter) { // This clears the previously cached icons and avoids issues with modifying the map // while its being used by other methods by throwing away the instance and allocating // a new one. fileIconMap = new HashMap<>(); if (directory == null) { return List.of(); } File[] files = directory.listFiles(filter); return (files == null) ? List.of() : List.of(files); } @Override public Icon getIcon(File file) { if (FS_ROOT_INFO.isRoot(file)) { return FS_ROOT_INFO.getRootIcon(file); } Icon result = (file != null && file.exists()) ? fileIconMap.computeIfAbsent(file, this::getSystemIcon) : null; return (result != null) ? result : PROBLEM_FILE_ICON; } private Icon getSystemIcon(File file) { try { return FS_VIEW.getSystemIcon(file); } catch (Exception e) { // ignore, return null } return null; } @Override public String getDescription(File file) { if (FS_ROOT_INFO.isRoot(file)) { return FS_ROOT_INFO.getRootDescriptionString(file); } return FS_VIEW.getSystemTypeDescription(file); } @Override public boolean createDirectory(File directory, String name) { File newDir = new File(directory, name); return newDir.mkdir(); } @Override public boolean isDirectory(File file) { return file != null && (FS_ROOT_INFO.isRoot(file) || file.isDirectory()); } @Override public boolean isAbsolute(File file) { if (file != null) { return file.isAbsolute(); } return false; } @Override public boolean renameFile(File src, File dest) { if (FS_ROOT_INFO.isRoot(src)) { return false; } return src.renameTo(dest); } //--------------------------------------------------------------------------------------------- /** * Handles querying / caching information about file system root locations. * <p> * Only a single instance of this class is needed and can be shared statically. */ private static class FileSystemRootInfo { private Map<File, String> descriptionMap = new ConcurrentHashMap<>(); private Map<File, Icon> iconMap = new ConcurrentHashMap<>(); private List<File> roots = List.of(); private AtomicBoolean updatePending = new AtomicBoolean(); synchronized boolean isEmpty() { return roots.isEmpty(); } synchronized boolean isRoot(File f) { for (File root : roots) { if (root.equals(f)) { return true; } } return false; } /** * Returns the currently known root locations. * * @return list of currently known root locations */ synchronized List<File> getRoots() { return new ArrayList<>(roots); } Icon getRootIcon(File root) { return iconMap.get(root); } String getRootDescriptionString(File root) { return descriptionMap.get(root); } /** * If there is no pending update, updates information about the root filesystem locations * present on the local computer, in a partially blocking manner. The initial list * of locations is queried directly, and the descriptions and icons for the root * locations are fetched in a background thread. * <p> * When new information is found during the background querying, the listener callback * will be executed so that it can cause UI updates. * <p> * If there is a pending background update, no-op. * * @param callback callback */ void updateRootInfo(Callback callback) { if (updatePending.compareAndSet(false, true)) { File[] localRoots = listRoots(); // possibly sloooow synchronized (this) { roots = List.of(localRoots); } for (File root : localRoots) { descriptionMap.put(root, getInitialRootDescriptionString(root)); iconMap.put(root, PENDING_ROOT_ICON); } Thread updateThread = new Thread( () -> asyncUpdateRootInfo(localRoots, Callback.dummyIfNull(callback))); updateThread.setName("GhidraFileChooser File System Updater"); updateThread.start(); // updateThread will unset the updatePending flag when done } } private File[] listRoots() { File[] tmpRoots = File.listRoots(); // possibly sloooow // File.listRoots javadoc says null result possible (but actual jdk code doesn't do it) return tmpRoots != null ? tmpRoots : new File[0]; } private void asyncUpdateRootInfo(File[] localRoots, Callback callback) { try { // Populate root description strings with values that are hopefully faster to // get than the full description strings that will be fetched next. for (File root : localRoots) { String fastRootDescriptionString = getFastRootDescriptionString(root); if (fastRootDescriptionString != null) { descriptionMap.put(root, fastRootDescriptionString); callback.call(); } } // Populate root description strings with final values, and icons for (File root : localRoots) { String slowRootDescriptionString = getSlowRootDescriptionString(root); if (slowRootDescriptionString != null) { descriptionMap.put(root, slowRootDescriptionString); callback.call(); } Icon rootIcon = FS_VIEW.getSystemIcon(root); // possibly a slow call iconMap.put(root, rootIcon); callback.call(); } } finally { updatePending.set(false); } } private String getInitialRootDescriptionString(File root) { return String.format("Unknown (%s)", formatRootPathForDisplay(root)); } /** * Return a description string for a file system root. Avoid slow calls (such as * {@link FileSystemView#getSystemDisplayName(File)}. * <p> * @param root file location * @return formatted description string, example "Local Drive (C:)" */ private String getFastRootDescriptionString(File root) { try { String fsvSTD = FS_VIEW.getSystemTypeDescription(root); return String.format("%s (%s)", fsvSTD, formatRootPathForDisplay(root)); } catch (Exception e) { //Windows expects the A drive to exist; if it does not exist, an exception results. //Ignore it. } return null; } /** * Returns the string path of a file system root, formatted so it doesn't have a trailing * backslash in the case of Windows root drive strings such as "c:\\", which becomes "c:" * * @param root file location * @return string path, formatted to not contain unneeded trailing slashes, example "C:" * instead of "C:\\" */ private String formatRootPathForDisplay(File root) { String s = root.getPath(); return s.length() > 1 && s.endsWith("\\") ? s.substring(0, s.length() - 1) : s; } /** * Return a description string for a root location. * <p> * @param root location to get description string * @return string such as "Local Disk (C:)", "Network Drive (R:)" */ private String getSlowRootDescriptionString(File root) { // Special case the description of the root of a unix filesystem, otherwise it gets // marked as removable if ("/".equals(root.getPath())) { return "File system root (/)"; } // Special case the description of floppies and removable disks, otherwise delegate to // fsView's getSystemDisplayName. if (FS_VIEW.isFloppyDrive(root)) { return String.format("Floppy (%s)", formatRootPathForDisplay(root)); } String fsvSTD = null; try { fsvSTD = FS_VIEW.getSystemTypeDescription(root); } catch (Exception e) { //Windows expects the A drive to exist; if it does not exist, an exception results. //Ignore it } if (fsvSTD == null || fsvSTD.toLowerCase().indexOf("removable") != -1) { return String.format("Removable Disk (%s)", formatRootPathForDisplay(root)); } // call the (possibly slow) fsv's getSystemDisplayName return FS_VIEW.getSystemDisplayName(root); } } }
30.340058
96
0.696429
7c5c443b7eacf072580b4698fe450d93751705b5
1,196
package pl.edu.pw.mini.gapso.configuration; import com.google.gson.JsonElement; import pl.edu.pw.mini.gapso.bounds.BoundsManager; import pl.edu.pw.mini.gapso.bounds.GlobalModelBoundsManager; import pl.edu.pw.mini.gapso.bounds.RandomRegionBoundsManager; import pl.edu.pw.mini.gapso.bounds.ResetAllBoundsManager; public class BoundsManagerConfiguration { String name; JsonElement parameters; public BoundsManagerConfiguration(String name, JsonElement parameters) { this.name = name; this.parameters = parameters; } public String getName() { return name; } public JsonElement getParameters() { return parameters; } public BoundsManager getBoundsManager() { if (getName().equals(GlobalModelBoundsManager.NAME)) { return new GlobalModelBoundsManager(this); } if (getName().equals(ResetAllBoundsManager.NAME)) { return new ResetAllBoundsManager(this); } if (getName().equals(RandomRegionBoundsManager.NAME)) { return new RandomRegionBoundsManager(this); } throw new IllegalArgumentException("Unknown initializer " + getName()); } }
30.666667
79
0.694816
904dd9858b9d76fdd04f1769a71a19b3f7822a7b
1,714
/** * Copyright (C) 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.tekton.pipeline.v1alpha1; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; class TaskTest { @Test public void testTaskFromJSON() throws IOException { InputStream is = TaskTest.class.getResourceAsStream("/task.json"); ObjectMapper mapper = new ObjectMapper(); Task task = mapper.readValue(is, Task.class); assertEquals("Task", task.getKind()); assertEquals("tekton.dev/v1alpha1", task.getApiVersion()); List<Step> steps = task.getSpec().getSteps(); assertEquals(1, steps.size()); Step step = steps.get(0); assertEquals("echo", step.getName()); assertEquals("ubuntu", step.getImage()); List<String> command = step.getCommand(); assertEquals(1, command.size()); assertEquals("echo", command.get(0)); List<String> args = step.getArgs(); assertEquals(1, args.size()); assertEquals("hello world", args.get(0)); } }
32.961538
75
0.714702
35a23fb7e0091bfa48a369cb1c5bb7150bbd47fc
5,571
/* * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors. * * 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.integration.fuse.karaf.itest.workitem; import org.apache.commons.io.FileUtils; import org.drools.core.process.instance.WorkItem; import org.drools.core.process.instance.impl.DefaultWorkItemManager; import org.drools.core.process.instance.impl.WorkItemImpl; import org.jbpm.process.workitem.camel.CamelHandler; import org.jbpm.process.workitem.camel.CamelHandlerFactory; import org.jbpm.process.workitem.camel.request.RequestPayloadMapper; import org.jbpm.process.workitem.camel.uri.FileURIMapper; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.runtime.process.WorkItemManager; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.inject.Inject; import org.apache.karaf.features.FeaturesService; import org.jboss.integration.fuse.karaf.itest.KarafConfigUtil; import org.ops4j.pax.exam.Configuration; /** * Uploading a file via File endpoint using Camel in Karaf. */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class CamelFileTest { private static File tempDir; private static File testDir; private static File testFile; private KieServices kieServices; private KieSession kieSession; @Inject FeaturesService fs; @Configuration public static Option[] configure() { return KarafConfigUtil.karafConfiguration(); } @BeforeClass public static void initialize() { tempDir = new File(System.getProperty("java.io.tmpdir")); testDir = new File(tempDir, "test_dir"); String fileName = "test_file_" + CamelFileTest.class.getName() + "_" + UUID.randomUUID().toString(); testFile = new File(tempDir, fileName); } @AfterClass public static void clean() throws IOException { FileUtils.deleteDirectory(testDir); } @Before public void prepare() { this.kieServices = KieServices.Factory.get(); final KieContainer kieContainer = this.kieServices.newKieClasspathContainer(this.getClass().getClassLoader()); this.kieSession = kieContainer.newKieSession("camel-workitem-ksession"); assertNotNull(this.kieSession); } @After public void cleanup() { if (this.kieSession != null) { this.kieSession.dispose(); } } /** * Test with entire BPMN process. * @throws java.io.IOException */ @Test public void testSingleFileProcess() throws IOException { final String testData = "test-data"; CamelHandler handler = CamelHandlerFactory.fileHandler(); kieSession.getWorkItemManager().registerWorkItemHandler("CamelFile", handler); Map<String, Object> params = new HashMap<String, Object>(); params.put("payloadVar", testData); params.put("pathVar", tempDir.getAbsolutePath()); params.put("fileNameVar", testFile.getName()); ProcessInstance pi = kieSession.startProcess("camelFileProcess", params); ProcessInstance result = kieSession.getProcessInstance(pi.getId()); assertNull(result); assertTrue(testFile.exists()); String resultText = FileUtils.readFileToString(testFile); assertEquals(testData,resultText); } /** * File to upload has been specified by Camel header. * * @throws java.io.IOException */ @Test public void testSingleFileWithHeaders() throws IOException { Set<String> headers = new HashSet<String>(); headers.add("CamelFileName"); CamelHandler handler = new CamelHandler(new FileURIMapper(), new RequestPayloadMapper("payload", headers)); final String testData = "test-data"; final WorkItem workItem = new WorkItemImpl(); workItem.setParameter("path", tempDir.getAbsolutePath()); workItem.setParameter("payload", testData); workItem.setParameter("CamelFileName", testFile.getName()); WorkItemManager manager = new DefaultWorkItemManager(null); handler.executeWorkItem(workItem, manager); assertTrue(testFile.exists()); String resultText = FileUtils.readFileToString(testFile); assertEquals(testData,resultText); } }
34.388889
118
0.72285
e9af07b98514f22b9af15e9c73aab024e1d8e8d9
503
package com.sjwoh.airview.client; import java.io.IOException; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * The client-side stub for the RPC service. */ @RemoteServiceRelativePath("greet") public interface GreetingService extends RemoteService { String greetServer(String name) throws IllegalArgumentException, IOException; String greetServer(String name, String name2) throws IllegalArgumentException, IOException; }
31.4375
92
0.817097
fa967aa670d27587130168d2434f8d00aa80222d
8,164
package com.yourpackagename.yourwebproject.model.entity; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.GenericGenerator; import com.yourpackagename.framework.data.NoIDEntity; @Entity @Table(name = "group_event_invites") public class GroupEventInvite extends NoIDEntity implements Serializable{ /** * */ private static final long serialVersionUID = 2900028549296577243L; @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") @Column(unique = true, updatable = false) private String groupEventInviteId; @Column private String groupCode; @Column private String groupEventCode; @Column private String groupEventInviteCode; @Column private String memberCategoryCode; @Column private Date inviteStartDate; @Column private Date inviteExpiryDate; @Column private boolean inviteSent; @Column private boolean inviteDelivered; @Column private boolean inviteCancelled; @Column private boolean inviteHeld; @Column private boolean rsvpd; @Column private boolean markAttended; @Column private double paidAmount; @Column private String transactionReference; @Column private Date transactionDateTime; @Column private boolean transactionApproved; @Column private int inviteEmailCount; /* @Column private boolean resendInvite; */ /* May be need to establish connection betweengroupEmails Somehow*/ @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "serialNumber") private GroupMember groupMember; /* @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = GroupEmail.class) @JoinColumn(name = "groupEventInviteId", referencedColumnName = "groupEventInviteId") private List<GroupEmail> groupEmails;*/ /* @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = GroupEventInviteRSVP.class) @JoinColumn(name = "groupEventInviteId", referencedColumnName = "groupEventInviteId") private List<GroupEventInviteRSVP> groupEventInviteRSVPs;*/ /** * @return the groupEventInviteId */ public String getGroupEventInviteId() { return groupEventInviteId; } /** * @param groupEventInviteId the groupEventInviteId to set */ public void setGroupEventInviteId(String groupEventInviteId) { this.groupEventInviteId = groupEventInviteId; } /** * @return the groupCode */ public String getGroupCode() { return groupCode; } /** * @param groupCode the groupCode to set */ public void setGroupCode(String groupCode) { this.groupCode = groupCode; } /** * @return the groupEventCode */ public String getGroupEventCode() { return groupEventCode; } /** * @param groupEventCode the groupEventCode to set */ public void setGroupEventCode(String groupEventCode) { this.groupEventCode = groupEventCode; } /** * @return the groupEventInviteCode */ public String getGroupEventInviteCode() { return groupEventInviteCode; } /** * @param groupEventInviteCode the groupEventInviteCode to set */ public void setGroupEventInviteCode(String groupEventInviteCode) { this.groupEventInviteCode = groupEventInviteCode; } /** * @return the memberCategoryCode */ public String getMemberCategoryCode() { return memberCategoryCode; } /** * @param memberCategoryCode the memberCategoryCode to set */ public void setMemberCategoryCode(String memberCategoryCode) { this.memberCategoryCode = memberCategoryCode; } /** * @return the inviteStartDate */ public Date getInviteStartDate() { return inviteStartDate; } /** * @param inviteStartDate the inviteStartDate to set */ public void setInviteStartDate(Date inviteStartDate) { this.inviteStartDate = inviteStartDate; } /** * @return the inviteExpiryDate */ public Date getInviteExpiryDate() { return inviteExpiryDate; } /** * @param inviteExpiryDate the inviteExpiryDate to set */ public void setInviteExpiryDate(Date inviteExpiryDate) { this.inviteExpiryDate = inviteExpiryDate; } /** * @return the inviteSend */ public boolean isInviteSent() { return inviteSent; } /** * @param inviteSend the inviteSend to set */ public void setInviteSent(boolean inviteSent) { this.inviteSent = inviteSent; } /** * @return the inviteDelivered */ public boolean isInviteDelivered() { return inviteDelivered; } /** * @param inviteDelivered the inviteDelivered to set */ public void setInviteDelivered(boolean inviteDelivered) { this.inviteDelivered = inviteDelivered; } /** * @return the inviteCancelled */ public boolean isInviteCancelled() { return inviteCancelled; } /** * @param inviteCancelled the inviteCancelled to set */ public void setInviteCancelled(boolean inviteCancelled) { this.inviteCancelled = inviteCancelled; } /** * @return the inviteHeld */ public boolean isInviteHeld() { return inviteHeld; } /** * @param inviteHeld the inviteHeld to set */ public void setInviteHeld(boolean inviteHeld) { this.inviteHeld = inviteHeld; } /* *//** * @return the resendInvite *//* public boolean isResendInvite() { return resendInvite; } *//** * @param resendInvite the resendInvite to set *//* public void setResendInvite(boolean resendInvite) { this.resendInvite = resendInvite; }*/ /** * @return the groupMember */ public GroupMember getGroupMember() { return groupMember; } /** * @param groupMember the groupMember to set */ public void setGroupMember(GroupMember groupMember) { this.groupMember = groupMember; } /* *//** * @return the groupEmails *//* public List<GroupEmail> getGroupEmails() { return groupEmails; } *//** * @param groupEmails the groupEmails to set *//* public void setGroupEmails(List<GroupEmail> groupEmails) { this.groupEmails = groupEmails; } */ /** * @return the rsvpd */ public boolean isRsvpd() { return rsvpd; } /** * @param rsvpd the rsvpd to set */ public void setRsvpd(boolean rsvpd) { this.rsvpd = rsvpd; } /** * @return the markAttended */ public boolean isMarkAttended() { return markAttended; } /** * @param markAttended the markAttended to set */ public void setMarkAttended(boolean markAttended) { this.markAttended = markAttended; } /** * @return the paidAmount */ public double getPaidAmount() { return paidAmount; } /** * @param paidAmount the paidAmount to set */ public void setPaidAmount(double paidAmount) { this.paidAmount = paidAmount; } /** * @return the inviteEmailCount */ public int getInviteEmailCount() { return inviteEmailCount; } /** * @param inviteEmailCount the inviteEmailCount to set */ public void setInviteEmailCount(int inviteEmailCount) { this.inviteEmailCount = inviteEmailCount; } /** * @return the transactionReference */ public String getTransactionReference() { return transactionReference; } /** * @param transactionReference the transactionReference to set */ public void setTransactionReference(String transactionReference) { this.transactionReference = transactionReference; } /** * @return the transactionDateTime */ public Date getTransactionDateTime() { return transactionDateTime; } /** * @param transactionDateTime the transactionDateTime to set */ public void setTransactionDateTime(Date transactionDateTime) { this.transactionDateTime = transactionDateTime; } /** * @return the transactionApproved */ public boolean isTransactionApproved() { return transactionApproved; } /** * @param transactionApproved the transactionApproved to set */ public void setTransactionApproved(boolean transactionApproved) { this.transactionApproved = transactionApproved; } }
20.207921
108
0.734444
93cd84ad11d05516510554cf17fde52e5350df0f
1,589
package tm; import java.util.Set; import java.util.HashSet; // Verrou bloquant avec deux modes : // partagé pour des lectures en parallèle et exclusif pour une écriture seule. public class SharedLock { private boolean exclusive; private Set<String> holders; public SharedLock() { this.exclusive = false; this.holders = new HashSet<String>(); } // Demande (en exclusion mutuelle) le verrou en mode partagé. public synchronized void shared(String asker) { try { while (exclusive) {this.wait();} this.holders.add(asker); } catch (InterruptedException e) { System.out.println("Interruption de l'attente sur un verrou bloquant."); } } // Demande (en exclusion mutuelle) le verrou en mode exclusif. public synchronized void exclusive(String asker) { try { while (this.exclusive || (!this.holders.isEmpty() && !(this.holders.size() == 1 && this.holders.contains(asker)))) { this.wait(); } this.holders.add(asker); this.exclusive = true; } catch (InterruptedException e) { System.out.println("Interruption de l'attente sur un verrou bloquant."); } } // Relache (en exclusion mutuelle) le verrou. public synchronized void release(String holder) { if (this.holders.contains(holder)) { this.holders.remove(holder); this.exclusive = false; this.notify(); } } }
29.425926
84
0.583386
828641a95a493af64f94210ec84f4e5774943f53
5,168
/* * Minio Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.minio; import java.util.Date; import org.joda.time.DateTime; import io.minio.http.Header; /** * HTTP response header class. */ public class ResponseHeader { @Header("Content-Length") private long contentLength; @Header("Content-Type") private String contentType; @Header("Date") private DateTime date; @Header("ETag") private String etag; @Header("Last-Modified") private DateTime lastModified; @Header("Server") private String server; @Header("Status Code") private String statusCode; @Header("Transfer-Encoding") private String transferEncoding; @Header("x-amz-bucket-region") private String xamzBucketRegion; @Header("x-amz-id-2") private String xamzId2; @Header("x-amz-request-id") private String xamzRequestId; @Header("x-amz-meta-x-amz-key") private String xamzMetaKey; @Header("x-amz-meta-x-amz-iv") private String xamzMetaIv; @Header("x-amz-meta-x-amz-matdesc") private String xamzMetaMatdesc; /** * Sets content length. */ public void setContentLength(String contentLength) { this.contentLength = Long.parseLong(contentLength); } /** * Returns content length. */ public long contentLength() { return this.contentLength; } /** * Sets content type. */ public void setContentType(String contentType) { this.contentType = contentType; } /** * Returns content type. */ public String contentType() { return this.contentType; } /** * Sets date. */ public void setDate(String date) { this.date = DateFormat.HTTP_HEADER_DATE_FORMAT.parseDateTime(date); } /** * Returns date. */ public Date date() { return this.date.toDate(); } /** * Sets ETag. */ public void setEtag(String etag) { this.etag = etag.replaceAll("\"", ""); } /** * Returns ETag. */ public String etag() { return this.etag; } /** * Sets last modified time. */ public void setLastModified(String lastModified) { this.lastModified = DateFormat.HTTP_HEADER_DATE_FORMAT.parseDateTime(lastModified); } /** * Returns last modified time. */ public Date lastModified() { return this.lastModified.toDate(); } /** * Sets server name. */ public void setServer(String server) { this.server = server; } /** * Returns server name. */ public String server() { return this.server; } /** * Sets status code. */ public void setStatusCode(String statusCode) { this.statusCode = statusCode; } /** * Returns status code. */ public String statusCode() { return this.statusCode; } /** * Sets transfer encoding. */ public void setTransferEncoding(String transferEncoding) { this.transferEncoding = transferEncoding; } /** * Returns transfer encoding. */ public String transferEncoding() { return this.transferEncoding; } /** * Sets Amazon bucket region. */ public void setXamzBucketRegion(String xamzBucketRegion) { this.xamzBucketRegion = xamzBucketRegion; } /** * Returns Amazon bucket region. */ public String xamzBucketRegion() { return this.xamzBucketRegion; } /** * Sets Amazon ID2. */ public void setXamzId2(String xamzId2) { this.xamzId2 = xamzId2; } /** * Returns Amazon ID2. */ public String xamzId2() { return this.xamzId2; } /** * Sets Amazon request ID. */ public void setXamzRequestId(String xamzRequestId) { this.xamzRequestId = xamzRequestId; } /** * Returns Amazon request ID. */ public String xamzRequestId() { return this.xamzRequestId; } /** * Sets encryption key. */ public void setXamzMetaKey(String xamzMetaKey) { this.xamzMetaKey = xamzMetaKey; } /** * Returns encryption key. */ public String xamzMetaKey() { return this.xamzMetaKey; } /** * Sets encryption initialization vector (IV). */ public void setXamzMetaIv(String xamzMetaIv) { this.xamzMetaIv = xamzMetaIv; } /** * Returns encryption initialization vector (IV). */ public String xamzMetaIv() { return this.xamzMetaIv; } /** * Sets encryption material description in JSON (UTF8) format. */ public void setXamzMetaMatdesc(String xamzMetaMatdesc) { this.xamzMetaMatdesc = xamzMetaMatdesc; } /** * Returns encryption material description in JSON (UTF8) format. */ public String xamzMetaMatdesc() { return this.xamzMetaMatdesc; } }
18.65704
87
0.658475
2fdc388e6cabe3783de51276c524b8e938917d3f
1,808
package com.amazon.aws.prototyping.apigateway; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.util.StringInputStream; public class S3Function extends AbstractFunction { private static final AmazonS3 S3 = AmazonS3ClientBuilder.defaultClient(); private static final String BUCKET_NAME = System.getenv("BUCKET_NAME"); public APIGatewayProxyResponseEvent putObject(APIGatewayProxyRequestEvent event, Context context) { String content = "hello"; // String S3.putObject(BUCKET_NAME, "sample-string.txt", content); // InputStream try (InputStream is = new StringInputStream(content)) { S3.putObject(BUCKET_NAME, "sample-inputstream.txt", is, new ObjectMetadata()); } catch (IOException e) { throw new RuntimeException(e); } return ok(); } public APIGatewayProxyResponseEvent getObject(APIGatewayProxyRequestEvent event, Context context) { S3Object s3Object = S3.getObject(BUCKET_NAME, "sample-string.txt"); try (InputStream is = s3Object.getObjectContent()) { String content = IOUtils.toString(is, "UTF-8"); System.out.println("content: " + content); } catch (IOException e) { throw new RuntimeException(e); } return ok(); } }
35.45098
103
0.720133
b3a641fc73a1e15f0ce7c242e9d451d44c3016ec
322
/** * Classe de exceção para camada de acesso a dados */ package br.edu.fanor.progweb.arquitetura.exceptions; /** * @author patrick.cunha * */ public class DAOException extends Exception { private static final long serialVersionUID = 6986867524676026821L; public DAOException(String msg) { super(msg); } }
16.947368
67
0.726708