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
a5bffc1da29f867ef2235c5eecbb04400122e13f
3,562
/* * Project: Timer * Class: com.leontg77.timer.Main * * The MIT License (MIT) * * Copyright (c) 2016-2018 Leon Vaktskjold <[email protected]>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.leontg77.timer; import com.leontg77.timer.commands.TimerCommand; import com.leontg77.timer.handling.handlers.BossBarHandler; import com.leontg77.timer.runnable.TimerRunnable; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import java.time.Instant; import java.util.Objects; /** * Main class of the plugin. * * @author LeonTG */ public class Main extends JavaPlugin { public static final String PREFIX = "§cTimer §8» §7"; @Override public void onEnable() { reloadConfig(); Objects.requireNonNull(getCommand("timer")).setExecutor(new TimerCommand(this)); } private TimerRunnable runnable = null; /** * Get the current runnable for the timer. * * @return The current runnable. */ public TimerRunnable getRunnable() { return runnable; } @Override public void reloadConfig() { super.reloadConfig(); if (getConfig().getConfigurationSection("bossbar") == null) { getConfig().set("bossbar.color", "pink"); getConfig().set("bossbar.style", "solid"); saveConfig(); } if (runnable != null && runnable.getHandler() instanceof Listener) { HandlerList.unregisterAll((Listener) runnable.getHandler()); } FileConfiguration config = getConfig(); runnable = new TimerRunnable(this, new BossBarHandler(this, config.getString("bossbar.color", "pink"), config.getString("bossbar.style", "solid"))); if(config.getConfigurationSection("timer") != null) { long endTimestamp = config.getLong("timer.last-end-time"); String message = config.getString("timer.last-message"); if(endTimestamp > 0 && message != null) { Instant endTime = Instant.ofEpochSecond(endTimestamp); if(endTime.isAfter(Instant.now())) { getLogger().info("Resuming saved timer \"" + message + "\""); getRunnable().startSendingMessage(message, endTime); } } } } }
35.62
107
0.6516
c286b8a86988813d962afbd268d38a3c9af2bdb2
5,799
/* * Copyright 2015 JAXIO http://www.jaxio.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 com.jaxio.celerio.configuration.database; import com.jaxio.celerio.util.StringUtil; import lombok.Setter; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static com.jaxio.celerio.configuration.Util.nonNull; import static org.springframework.util.StringUtils.hasLength; public class JdbcConnectivity { @Setter private String driver; @Setter private String driverGroupId; @Setter private String driverArtifactId; @Setter private String driverArtifactIdVersion; @Setter private String hibernateDialect; @Setter private String sqlDelimiter; @Setter private String password; @Setter private String url; @Setter private String user; @Setter private String schemaName; @Setter private List<String> tableNamePatterns = newArrayList(); @Setter private boolean oracleRetrieveRemarks; @Setter private boolean oracleRetrieveSynonyms; @Setter private Boolean reverseIndexes = true; @Setter private Boolean reverseOnlyUniqueIndexes = true; @Setter private String catalog; private List<TableType> tableTypes = newArrayList(); public JdbcConnectivity() { } public JdbcConnectivity(TableType tableType) { add(tableType); } /* * Jdbc driver name<br> * Example: org.h2.Driver */ public String getDriver() { return driver; } /* * Jdbc driver group id<br> * Example: */ public String getDriverGroupId() { return driverGroupId; } /* * Jdbc driver artifact id<br> * Example: */ public String getDriverArtifactId() { return driverArtifactId; } /* * Jdbc driver artifact id version<br> * Example: */ public String getDriverArtifactIdVersion() { return driverArtifactIdVersion; } /* * Jdbc hibernate dialect<br> * Example: */ public String getHibernateDialect() { return hibernateDialect; } /* * SQL delimiter<br> * Example: ; or / */ public String getSqlDelimiter() { return sqlDelimiter; } /* * Jdbc url connection<br> * Example: Jdbc:h2:~/mydatabase */ public String getUrl() { return url; } /* * Jdbc user<br> * Example: myuser */ public String getUser() { return user; } /* * Jdbc password<br> * Example: mypassword */ public String getPassword() { return password; } public String getSchemaName() { return schemaName; } /* * you can restrict table extraction using a pattern<br> * Example: PROJECT_% */ public List<String> getTableNamePatterns() { return tableNamePatterns; } /* * Table types to retrieve */ public List<TableType> getTableTypes() { return tableTypes; } /* * Should Celerio retrieve remarks on oracle, beware this is a very time consuming operation */ public boolean isOracleRetrieveRemarks() { return oracleRetrieveRemarks; } /* * Should Celerio retrieve synonyms on oracle */ public boolean isOracleRetrieveSynonyms() { return oracleRetrieveSynonyms; } /* * When false, no indexes is reversed at all. * @return */ public Boolean getReverseIndexes() { return reverseIndexes; } public boolean shouldReverseIndexes() { // we assume null is by default TRUE. return reverseIndexes == null || reverseIndexes; } /* * when true, reverse only indexes for unique values; when false, reverse indexes regardless of whether unique or not. */ public Boolean getReverseOnlyUniqueIndexes() { return reverseOnlyUniqueIndexes; } public boolean shouldReverseOnlyUniqueIndexes() { // we assume null is by default TRUE. return shouldReverseIndexes() && (reverseOnlyUniqueIndexes == null || reverseOnlyUniqueIndexes); } /* * Catalog name; must match the catalog name as it is stored in the database.<br> * "" retrieves those without a catalog<br> * empty means that the catalog name should not be used to narrow the search */ public String getCatalog() { return catalog; } public void setTableTypes(List<TableType> tableTypes) { this.tableTypes = nonNull(tableTypes); } public void add(TableType tableType) { tableTypes.add(tableType); } public boolean invalid() { // password can be empty return isBlank(driver, url, user); } public boolean isValid() { return !invalid(); } private boolean isBlank(String... args) { for (String arg : args) { if (!hasLength(arg)) { return true; } } return false; } public WellKnownDatabase getWellKownDatabase() { return WellKnownDatabase.fromJdbcUrl(getUrl()); } public boolean isWellKownDatabase() { return getWellKownDatabase() != null; } }
23.573171
122
0.634247
1ba248062870ae9ce31ab522789cdd4cbcb341f0
11,774
package com.bbva.kyof.vega.protocol.subscriber; import com.bbva.kyof.vega.autodiscovery.model.AutoDiscTopicSocketInfo; import com.bbva.kyof.vega.protocol.common.VegaContext; import com.bbva.kyof.vega.protocol.control.ISecurityRequesterNotifier; import com.bbva.kyof.vega.util.collection.HashMapOfHashSet; import lombok.extern.slf4j.Slf4j; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * Receive manager to hanle IPC and Multicast subscriptions. It will handle all the sockets and relations between topic subscribers. * * This class is not thread safe! */ @Slf4j class SubscribersManagerIpcMcast extends AbstractSubscribersManager { /** Stores all the subscribers handled by this manager by the parameters used to create them */ private final Map<AeronSubscriberParams, AeronSubscriber> subscriberByParams = new HashMap<>(); /** Store all the pub topic sockets info of publishers that match a topic name */ private final HashMapOfHashSet<String, UUID> pubTopicSocketInfosByTopicName = new HashMapOfHashSet<>(); /** Store all the pub topic sockets info related to an AeronSubscriber */ private final HashMapOfHashSet<AeronSubscriber, UUID> pubTopicSocketIdByAeronSub = new HashMapOfHashSet<>(); /** Store the relation between pub topic socket infos and aeron subscribers */ private final Map<UUID, AeronSubscriber> aeronSubByPubTopicSocketId = new HashMap<>(); /** * Constructor * * @param vegaContext the context of the manager instance * @param pollersManager manager that handle the pollers * @param topicSubAndTopicPubIdRelations relationships between topic subscribers and topic publishers * @param subSecurityNotifier notifier for security changes */ SubscribersManagerIpcMcast(final VegaContext vegaContext, final SubscribersPollersManager pollersManager, final TopicSubAndTopicPubIdRelations topicSubAndTopicPubIdRelations, final ISecurityRequesterNotifier subSecurityNotifier) { super(vegaContext, pollersManager, topicSubAndTopicPubIdRelations, subSecurityNotifier); } @Override protected void processTopicSubscriberBeforeDestroy(final TopicSubscriber topicSubscriber) { // Remove and consume all the topic socket Id's related to that topic subscriber this.pubTopicSocketInfosByTopicName.removeAndConsumeIfKeyEquals(topicSubscriber.getTopicName(), topicSocketId -> removeTopicSocketInfo(topicSubscriber, topicSocketId)); } @Override public void cleanAfterClose() { this.subscriberByParams.clear(); this.aeronSubByPubTopicSocketId.clear(); this.pubTopicSocketIdByAeronSub.clear(); this.pubTopicSocketInfosByTopicName.clear(); } @Override public void onNewAutoDiscTopicSocketInfo(final AutoDiscTopicSocketInfo publisherTopicSocketInfo) { log.debug("New topic socket info event received from auto-discovery {}", publisherTopicSocketInfo); synchronized (this.lock) { if (this.isClosed()) { return; } // Get the topic subscriber for the publisher topic name, if none we are not subscribed, ignore the event final TopicSubscriber topicSubscriber = this.getTopicSubscriberForTopicName(publisherTopicSocketInfo.getTopicName()); if (topicSubscriber == null) { return; } // Check if we already have that topic socket info registered, if registered is a duplicated event if (this.aeronSubByPubTopicSocketId.containsKey(publisherTopicSocketInfo.getUniqueId())) { return; } // Check the security to decide if the topic socket should be filtered. Both topics should have or not have security, if secured the security id of // the publisher should be in the list of valid id's for the subscriber if (!performSecurityFilter(topicSubscriber, publisherTopicSocketInfo)) { return; } // Create the aeron subscriber parameters for the topic subscriber and topic socket info of the publisher that generates the event final AeronSubscriberParams aeronSubscriberParams = this.createAeronSubscriberParams(topicSubscriber, publisherTopicSocketInfo); // Check if we already have the socket created with that parameters, if not create a new one AeronSubscriber aeronSubscriber = this.subscriberByParams.get(aeronSubscriberParams); if (aeronSubscriber == null) { // Create the new subscriber and store aeronSubscriber = new AeronSubscriber(this.getVegaContext(), aeronSubscriberParams); this.subscriberByParams.put(aeronSubscriberParams, aeronSubscriber); // Add to the poller this.getPollersManager().getPoller(topicSubscriber.getTopicConfig().getRcvPoller()).addSubscription(aeronSubscriber); } // Add all the relations between the topic socket id and the topic subscriber and aeron subscriber this.aeronSubByPubTopicSocketId.put(publisherTopicSocketInfo.getUniqueId(), aeronSubscriber); this.pubTopicSocketIdByAeronSub.put(aeronSubscriber, publisherTopicSocketInfo.getUniqueId()); this.pubTopicSocketInfosByTopicName.put(topicSubscriber.getTopicName(), publisherTopicSocketInfo.getUniqueId()); } } @Override public void onTimedOutAutoDiscTopicSocketInfo(final AutoDiscTopicSocketInfo publisherTopicSocketInfo) { log.debug("Topic socket info event timed out in auto-discovery {}", publisherTopicSocketInfo); synchronized (this.lock) { if (this.isClosed()) { return; } // Get the topic subscriber for the publisher topic name, if not there we are not subscribed, it may be a duplicated final TopicSubscriber topicSubscriber = this.getTopicSubscriberForTopicName(publisherTopicSocketInfo.getTopicName()); if (topicSubscriber == null) { return; } // Remove the relationship between the topic and the topic socket this.pubTopicSocketInfosByTopicName.remove(topicSubscriber.getTopicName(), publisherTopicSocketInfo.getUniqueId()); // Remove the the topic socket, it will delete the required relations and close the aeron subscriber if necessary this.removeTopicSocketInfo(topicSubscriber, publisherTopicSocketInfo.getUniqueId()); } } /** * Triggered to remove a topic socket info that was stored. * * It will remove all stored relations for that topic socket id and if the AeronSubscriber that contains it * don't have any more topic sockets related it will close and delete it as well * * @param topicSubscriber the topic subscriber for the topic name that match the topic socket information * @param pubTopicSocketId the unique id of the topic socket to remove */ private void removeTopicSocketInfo(final TopicSubscriber topicSubscriber, final UUID pubTopicSocketId) { // For each topic socket id that is going to be deleted, find the Aeron Subscribers that have them and remove it from there as well final AeronSubscriber aeronSubscriber = this.aeronSubByPubTopicSocketId.remove(pubTopicSocketId); // It may not be there if it is triggered by a duplicated event if (aeronSubscriber == null) { return; } // Remove it also from the topic socket id's related to the aeron subscriber this.pubTopicSocketIdByAeronSub.remove(aeronSubscriber, pubTopicSocketId); // If there are no more topic socket ids for the Aeron Subscriber, we should close it if (!this.pubTopicSocketIdByAeronSub.containsKey(aeronSubscriber)) { // If there are no topic sockets attached to the AeronSubscriber we should remove it as well this.getPollersManager().getPoller(topicSubscriber.getTopicConfig().getRcvPoller()).removeSubscription(aeronSubscriber); aeronSubscriber.close(); this.subscriberByParams.remove(aeronSubscriber.getParams()); } } /** * Given the topic subscriber and topic socket info it creates the aeron subscriber parameters that correspond to the topic socket * * @param topicSubscriber topic subscriber to create the parameters from * @param topicSocketInfo topic socket information from autodiscovery * * @return the created parameters */ private AeronSubscriberParams createAeronSubscriberParams(final TopicSubscriber topicSubscriber, final AutoDiscTopicSocketInfo topicSocketInfo) { return new AeronSubscriberParams( topicSubscriber.getTopicConfig().getTransportType(), topicSocketInfo.getIpAddress(), topicSocketInfo.getPort(), topicSocketInfo.getStreamId(), topicSubscriber.getTopicConfig().getSubnetAddress()); } /** * Check the security to decide if the topic should be filtered. Both topics should have or not have security, if secured the security id of * the publisher should be in the list of valid id's for the subscriber. * * @param topicSubscriber the existing topic subscriber * @param pubTopicSocketInfo the new topic publisher information * @return true if it pass the security filger */ private boolean performSecurityFilter(final TopicSubscriber topicSubscriber, final AutoDiscTopicSocketInfo pubTopicSocketInfo) { // If the topic subscriber has security configured if (topicSubscriber.hasSecurity()) { final SecureTopicSubscriber secureTopicSubscriber = (SecureTopicSubscriber)topicSubscriber; // The topic subscriber has security configured, the sub topic socket should have as well if (!pubTopicSocketInfo.hasSecurity()) { log.warn("Non-secured new PubTopicSocketInfo event received but the subscriber has security configured. {}", pubTopicSocketInfo); return false; } // Both have security, make sure the security id is in the list of valid id's if (!secureTopicSubscriber.isTopicPubSecureIdAllowed(pubTopicSocketInfo.getSecurityId())) { log.warn("Secured new PubTopicSocketInfo event received but the secure id is not configured for the subscriber. {}", pubTopicSocketInfo); return false; } // Finally we should have the public key of the publisher if (!this.getVegaContext().getSecurityContext().getRsaCrypto().isSecurityIdRegistered(pubTopicSocketInfo.getSecurityId())) { // If is in the list, the public key should have been loaded as well log.warn("New secure publisher AutoDiscTopicSocketInfo received but the public key cannot be found in any of the pub keys files. {}", pubTopicSocketInfo); return false; } } else if(pubTopicSocketInfo.hasSecurity()) { // No security configured in topic subscriber, but topic socket has security, is an error log.warn("Secured new PubTopicSocketInfo event received but the subscriber has no security configured. {}", pubTopicSocketInfo); return false; } return true; } }
48.057143
170
0.691439
814d4e86ed8af3cf4f147c5c877dbdcb6b963ea9
6,479
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.xa.bean; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.ejb.CreateException; import javax.ejb.EJBException; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.jboss.test.xa.interfaces.CantSeeDataException; public class XATestBean implements SessionBean { org.apache.log4j.Category log = org.apache.log4j.Category.getInstance(getClass()); public final static String DROP_TABLE = "DROP TABLE XA_TEST"; public final static String CREATE_TABLE = "CREATE TABLE XA_TEST(ID INTEGER NOT NULL PRIMARY KEY, DATA INTEGER NOT NULL)"; public final static String DB_1_NAME = "java:comp/env/jdbc/DBConnection1"; public final static String DB_2_NAME = "java:comp/env/jdbc/DBConnection2"; public XATestBean() { } public void ejbCreate() throws CreateException { } public void ejbActivate() throws EJBException { } public void ejbPassivate() throws EJBException { } public void ejbRemove() throws EJBException { } public void setSessionContext(SessionContext parm1) throws EJBException { } protected void execute(DataSource ds, String sql) throws SQLException { Connection con = ds.getConnection(); try { Statement s = con.createStatement(); s.execute(sql); s.close(); } finally { con.close(); } } protected void execute(Connection con, String sql) throws SQLException { Statement s = con.createStatement(); s.execute(sql); s.close(); } public void createTables() throws NamingException, SQLException { Context ctx = new InitialContext(); try { DataSource ds1 = (DataSource)ctx.lookup(DB_1_NAME); try { execute(ds1, DROP_TABLE); } catch (Exception ignore) {} execute(ds1, CREATE_TABLE); DataSource ds2 = (DataSource)ctx.lookup(DB_2_NAME); try { execute(ds2, DROP_TABLE); } catch (Exception ignore) {} execute(ds2, CREATE_TABLE); } finally { ctx.close(); } } public void clearData() { try { Context ctx = new InitialContext(); DataSource db1ds = (DataSource)ctx.lookup(DB_1_NAME); Connection db1con = db1ds.getConnection(); Statement db1st = db1con.createStatement(); db1st.executeUpdate("DELETE FROM XA_TEST"); db1st.close(); DataSource db2ds = (DataSource)ctx.lookup(DB_2_NAME); Connection db2con = db2ds.getConnection(); Statement db2st = db2con.createStatement(); db2st.executeUpdate("DELETE FROM XA_TEST"); db2st.close(); db2con.close(); db1con.close(); } catch(SQLException e) { throw new EJBException("Unable to clear data (have tables been created?): "+e); } catch(NamingException e) { throw new EJBException("Unable to find DB pool: "+e); } } public void doWork() throws CantSeeDataException { Connection db1cona = null, db1conb = null, db2con = null; try { // Create 3 connections Context ctx = new InitialContext(); DataSource db1ds = (DataSource)ctx.lookup(DB_1_NAME); db1cona = db1ds.getConnection(); db1conb = db1ds.getConnection(); DataSource db2ds = (DataSource)ctx.lookup(DB_2_NAME); db2con = db2ds.getConnection(); // Insert some data on one connection Statement s = db1cona.createStatement(); int data = (int)(System.currentTimeMillis() & 0x0000FFFFL); s.executeUpdate("INSERT INTO XA_TEST (ID, DATA) VALUES (1, "+data+")"); s.close(); // Verify that another connection on the same DS can read it s = db1conb.createStatement(); int result = -1; ResultSet rs = s.executeQuery("SELECT DATA FROM XA_TEST WHERE ID=1"); while(rs.next()) { result = rs.getInt(1); } rs.close(); s.close(); // Do some work on the other data source s = db2con.createStatement(); s.executeUpdate("INSERT INTO XA_TEST (ID, DATA) VALUES (1, "+data+")"); s.close(); if(result != data) throw new CantSeeDataException("Insert performed on one connection wasn't visible\n"+ "to another connection in the same transaction!"); } catch(SQLException e) { throw new EJBException("Unable to clear data (have tables been created?): "+e); } catch(NamingException e) { throw new EJBException("Unable to find DB pool: "+e); } finally { // Close all connections if(db2con != null) try {db2con.close();}catch(SQLException e) {} if(db1cona != null) try {db1cona.close();}catch(SQLException e) {} if(db1conb != null) try {db1conb.close();}catch(SQLException e) {} } } }
35.598901
101
0.618923
75c710e927381f37e97f8ab3f15e32d81a920f36
1,445
/* * 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 tech.tablesaw.io.html; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import tech.tablesaw.aggregate.AggregateFunctions; import tech.tablesaw.api.StringColumn; import tech.tablesaw.api.Table; import tech.tablesaw.io.csv.CsvReadOptions; import tech.tablesaw.table.StandardTableSliceGroup; import tech.tablesaw.table.TableSliceGroup; public class HtmlTableWriterTest { private Table table; @BeforeEach public void setUp() throws Exception { table = Table.read().csv(CsvReadOptions.builder("../data/bush.csv")); } @Test public void testWrite() { StringColumn byColumn = table.stringColumn("who"); TableSliceGroup group = StandardTableSliceGroup.create(table, byColumn); Table result = group.aggregate("approval", AggregateFunctions.mean); HtmlTableWriter.write(result); } }
32.840909
80
0.740484
b47a0bc712e85a7b55b0bb203e25e75ffa544c15
343
package exercicio_1_2; public class Calzoneria implements Fabrica { public static final int CALABRESA = 1; public static final int PRESUNTO = 2; @Override public Produto getProduto(int tipo) { switch(tipo) { case CALABRESA: return new CalzoneCalabresa(); case PRESUNTO: return new CalzonePresunto(); } return null; } }
18.052632
44
0.725948
c34a256e63d5051485bf9c2db25a193a455e40e9
711
package net.sourceforge.ondex.parser.taxonomy; /** * Interface states meta data usage of Parser. * * @author taubertj * @version 28.05.2008 */ public interface MetaData { /** * The evidence type */ public static final String ET = "IMPD"; /** * The concept class */ public static final String CC = "Taxon"; /** * The controlled vocabulary */ public static final String CV = "TX"; /** * The taxonomy id itself */ public static final String TAXID = "TAXID"; /** * The taxonomy rank attribute */ public static final String RANK = "RANK"; /** * The relation between entries */ public static final String RTSET = "is_a"; }
17.341463
47
0.606188
7fa84746b264fae796bb56f2e8392b3bc748d5ae
4,515
/** * 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.flink.runtime.protocols; import java.io.IOException; import java.util.List; import org.apache.flink.core.io.StringRecord; import org.apache.flink.runtime.event.job.AbstractEvent; import org.apache.flink.runtime.event.job.RecentJobEvent; import org.apache.flink.runtime.jobgraph.JobID; import org.apache.flink.runtime.managementgraph.ManagementGraph; import org.apache.flink.runtime.managementgraph.ManagementVertexID; import org.apache.flink.runtime.topology.NetworkTopology; /** * This protocol provides extended management capabilities beyond the * simple {@link JobManagementProtocol}. It can be used to retrieve * internal scheduling information, the network topology, or profiling * information about thread or instance utilization. * */ public interface ExtendedManagementProtocol extends JobManagementProtocol { /** * Retrieves the management graph for the job * with the given ID. * * @param jobID * the ID identifying the job * @return the management graph for the job * @throws IOException * thrown if an error occurs while retrieving the management graph */ ManagementGraph getManagementGraph(JobID jobID) throws IOException; /** * Retrieves the current network topology for the job with * the given ID. * * @param jobID * the ID identifying the job * @return the network topology for the job * @throws IOException * thrown if an error occurs while retrieving the network topology */ NetworkTopology getNetworkTopology(JobID jobID) throws IOException; /** * Retrieves a list of jobs which have either running or have been started recently. * * @return a (possibly) empty list of recent jobs * @throws IOException * thrown if an error occurs while retrieving the job list */ List<RecentJobEvent> getRecentJobs() throws IOException; /** * Retrieves the collected events for the job with the given job ID. * * @param jobID * the ID of the job to retrieve the events for * @return a (possibly empty) list of events which occurred for that event and which * are not older than the query interval * @throws IOException * thrown if an error occurs while retrieving the list of events */ List<AbstractEvent> getEvents(JobID jobID) throws IOException; /** * Kills the task with the given vertex ID. * * @param jobID * the ID of the job the vertex to be killed belongs to * @param id * the vertex ID which identified the task be killed * @throws IOException * thrown if an error occurs while transmitting the kill request */ void killTask(JobID jobID, ManagementVertexID id) throws IOException; /** * Kills the instance with the given name (i.e. shuts down its task manager). * * @param instanceName * the name of the instance to be killed * @throws IOException * thrown if an error occurs while transmitting the kill request */ void killInstance(StringRecord instanceName) throws IOException; /** * Triggers all task managers involved in processing the job with the given job ID to write the utilization of * their read and write buffers to their log files. This method is primarily for debugging purposes. * * @param jobID * the ID of the job to print the buffer distribution for * @throws IOException * throws if an error occurs while transmitting the request */ void logBufferUtilization(JobID jobID) throws IOException; /** * Returns the number of available slots among the registered task managers * @return number of available slots * @throws IOException */ int getAvailableSlots() throws IOException; }
35.551181
111
0.732669
b14483c7abca7a160282de621c42859298d85743
218
package maxim.rpc.socket; import maxim.rpc.socket.transport.IoSession; import java.nio.ByteBuffer; //消息传输协议接口 public interface Protocol<T> { public T decode(final ByteBuffer readBuffer, IoSession<T> session); }
19.818182
71
0.775229
49cec2f8c8bbbda5b3258a0f34dfe733cc68c8bc
707
package com.skytala.eCommerce.domain.workeffort.relations.deliverable.event.workEffortProd; import java.util.List; import com.skytala.eCommerce.framework.pubsub.Event; import com.skytala.eCommerce.domain.workeffort.relations.deliverable.model.workEffortProd.WorkEffortDeliverableProd; public class WorkEffortDeliverableProdFound implements Event{ private List<WorkEffortDeliverableProd> workEffortDeliverableProds; public WorkEffortDeliverableProdFound(List<WorkEffortDeliverableProd> workEffortDeliverableProds) { this.workEffortDeliverableProds = workEffortDeliverableProds; } public List<WorkEffortDeliverableProd> getWorkEffortDeliverableProds() { return workEffortDeliverableProds; } }
33.666667
116
0.862801
e9ba0fe97b17c725b73914bbab03b359ffc16680
37,454
package org.aion.zero.impl.pendingState; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import java.io.File; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.aion.avm.stub.IAvmResourceFactory; import org.aion.avm.stub.IContractFactory.AvmContract; import org.aion.base.AionTransaction; import org.aion.base.TransactionTypes; import org.aion.base.TxUtil; import org.aion.crypto.ECKey; import org.aion.db.utils.FileUtils; import org.aion.txpool.Constant; import org.aion.zero.impl.blockchain.AionHub; import org.aion.zero.impl.blockchain.AionImpl; import org.aion.zero.impl.blockchain.AionImpl.NetworkBestBlockCallback; import org.aion.zero.impl.blockchain.AionImpl.PendingTxCallback; import org.aion.zero.impl.blockchain.AionImpl.TransactionBroadcastCallback; import org.aion.zero.impl.blockchain.StandaloneBlockchain; import org.aion.zero.impl.blockchain.StandaloneBlockchain.Bundle; import org.aion.zero.impl.types.TxResponse; import org.aion.zero.impl.core.ImportResult; import org.aion.base.TransactionTypeRule; import org.aion.types.AionAddress; import org.aion.util.bytes.ByteUtil; import org.aion.util.time.TimeInstant; import org.aion.zero.impl.config.CfgAion; import org.aion.zero.impl.types.AionBlock; import org.aion.zero.impl.types.AionBlockSummary; import org.aion.zero.impl.vm.AvmPathManager; import org.aion.zero.impl.vm.AvmTestConfig; import org.aion.zero.impl.vm.TestResourceProvider; import org.aion.base.AionTxReceipt; import org.apache.commons.lang3.tuple.Pair; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.spongycastle.pqc.math.linearalgebra.ByteUtils; public class PendingStateTest { private Bundle bundle; private StandaloneBlockchain blockchain; private ECKey deployerKey; private AionPendingStateImpl pendingState; private long energyPrice = 10_000_000_000L; @BeforeClass public static void setup() { TransactionTypeRule.allowAVMContractTransaction(); AvmTestConfig.supportOnlyAvmVersion1(); } @AfterClass public static void tearDown() { AvmTestConfig.clearConfigurations(); } @Before public void reinitialize() throws SecurityException, IllegalArgumentException { bundle = new StandaloneBlockchain.Builder() .withDefaultAccounts() .withValidatorConfiguration("simple") .withAvmEnabled() .build(); blockchain = bundle.bc; deployerKey = bundle.privateKeys.get(0); CfgAion.inst().setGenesis(blockchain.getGenesis()); pendingState = AionHub.createForTesting(CfgAion.inst(), blockchain, new PendingTxCallback(new ArrayList<>()), new NetworkBestBlockCallback(AionImpl.inst()), new TransactionBroadcastCallback(AionImpl.inst())).getPendingState(); } private List<AionTransaction> getMockTransaction(int startNonce, int num, int keyIndex) { List<AionTransaction> txn = new ArrayList<>(); for (int i = startNonce; i < startNonce + num; i++) { AionTransaction tx = AionTransaction.create( bundle.privateKeys.get(keyIndex), BigInteger.valueOf(i).toByteArray(), new AionAddress(bundle.privateKeys.get(keyIndex + 1).getAddress()), ByteUtil.hexStringToBytes("1"), ByteUtil.hexStringToBytes("1"), Constant.MIN_ENERGY_CONSUME * 10, energyPrice, TransactionTypes.DEFAULT, null); txn.add(tx); } return txn; } @Test public void testAddPendingTransactionSuccess() { // Successful transaction AionTransaction tx = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 1_000_000L, energyPrice, TransactionTypes.DEFAULT, null); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.SUCCESS); } @Test public void testAddPendingTransactionInvalidNrgPrice() { // Invalid Nrg Price transaction AionTransaction tx = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 1_000_000L, energyPrice - 1, TransactionTypes.DEFAULT, null); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.INVALID_TX_NRG_PRICE); } @Test public void testAddPendingTransaction_AVMContractDeploy_Success() throws Exception { TestResourceProvider resourceProvider = TestResourceProvider.initializeAndCreateNewProvider(AvmPathManager.getPathOfProjectRootDirectory()); IAvmResourceFactory resourceFactory = resourceProvider.factoryForVersion1; // Successful transaction byte[] jar = resourceFactory.newContractFactory().getDeploymentBytes(AvmContract.HELLO_WORLD); AionTransaction transaction = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), null, BigInteger.ZERO.toByteArray(), jar, 5_000_000, energyPrice, TransactionTypes.AVM_CREATE_CODE, null); assertEquals(pendingState.addTransactionFromApiServer(transaction), TxResponse.SUCCESS); } @Test public void testAddPendingTransaction_AVMContractCall_Success() throws Exception { TestResourceProvider resourceProvider = TestResourceProvider.initializeAndCreateNewProvider(AvmPathManager.getPathOfProjectRootDirectory()); IAvmResourceFactory resourceFactory = resourceProvider.factoryForVersion1; // Successful transaction byte[] jar = resourceFactory.newContractFactory().getDeploymentBytes(AvmContract.HELLO_WORLD); AionTransaction createTransaction = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), null, BigInteger.ZERO.toByteArray(), jar, 5_000_000, energyPrice, TransactionTypes.AVM_CREATE_CODE, null); assertEquals(pendingState.addTransactionFromApiServer(createTransaction), TxResponse.SUCCESS); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), pendingState.getPendingTransactions(), false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); AionTxReceipt receipt = connectResult.getRight().getReceipts().get(0); // Check the block was imported, the contract has the Avm prefix, and deployment succeeded. assertThat(connectResult.getLeft()).isEqualTo(ImportResult.IMPORTED_BEST); // verify that the output is indeed the contract address AionAddress contractAddress = TxUtil.calculateContractAddress(createTransaction); assertThat(contractAddress.toByteArray()).isEqualTo(receipt.getTransactionOutput()); AionAddress contract = new AionAddress(receipt.getTransactionOutput()); byte[] call = resourceFactory.newStreamingEncoder().encodeOneString("sayHello").getEncoding(); AionTransaction callTransaction = AionTransaction.create( deployerKey, BigInteger.ONE.toByteArray(), contract, BigInteger.ZERO.toByteArray(), call, 2_000_000, energyPrice, TransactionTypes.DEFAULT, null); assertEquals(pendingState.addTransactionFromApiServer(callTransaction), TxResponse.SUCCESS); } private AionTransaction genTransactionWithTimestamp(byte[] nonce, ECKey key, byte[] timeStamp) { return AionTransaction.createGivenTimestamp( key, nonce, new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, energyPrice, TransactionTypes.DEFAULT, timeStamp, null); } private AionTransaction genTransaction(byte[] nonce) { return AionTransaction.create( deployerKey, nonce, new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, energyPrice, TransactionTypes.DEFAULT, null); } @Test public void snapshotWithSameTransactionTimestamp() { ECKey deployerKey2 = bundle.privateKeys.get(1); byte[] timeStamp = ByteUtil.longToBytes(TimeInstant.now().toEpochMicro()); final int cnt = 16; for (int i = 0; i < cnt; i++) { byte[] nonce = new byte[Long.BYTES]; nonce[Long.BYTES - 1] = (byte) i; AionTransaction tx = genTransactionWithTimestamp(nonce, deployerKey, timeStamp); pendingState.addTransactionFromApiServer(tx); } timeStamp = ByteUtil.longToBytes(TimeInstant.now().toEpochMicro()); for (int i = 0; i < cnt; i++) { byte[] nonce = new byte[Long.BYTES]; nonce[Long.BYTES - 1] = (byte) i; AionTransaction tx = genTransactionWithTimestamp(nonce, deployerKey2, timeStamp); pendingState.addTransactionFromApiServer(tx); } timeStamp = ByteUtil.longToBytes(TimeInstant.now().toEpochMicro()); for (int i = cnt; i < 2 * cnt; i++) { byte[] nonce = new byte[Long.BYTES]; nonce[Long.BYTES - 1] = (byte) i; AionTransaction tx = genTransactionWithTimestamp(nonce, deployerKey, timeStamp); pendingState.addTransactionFromApiServer(tx); } timeStamp = ByteUtil.longToBytes(TimeInstant.now().toEpochMicro()); for (int i = cnt; i < 2 * cnt; i++) { byte[] nonce = new byte[Long.BYTES]; nonce[Long.BYTES - 1] = (byte) i; AionTransaction tx = genTransactionWithTimestamp(nonce, deployerKey2, timeStamp); pendingState.addTransactionFromApiServer(tx); } assertEquals(pendingState.getPendingTxSize(), cnt * 4); } @Test public void addRepeatedTxn() { AionTransaction tx = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, energyPrice, TransactionTypes.DEFAULT, null); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.SUCCESS); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.REPAYTX_LOWPRICE); assertEquals(1, pendingState.getPendingTxSize()); } @Test public void addRepeatedTxn2() { final int cnt = 10; for (int i = 0; i < cnt; i++) { byte[] nonce = new byte[Long.BYTES]; nonce[Long.BYTES - 1] = (byte) i; assertEquals(pendingState.addTransactionFromApiServer(genTransaction(nonce)), TxResponse.SUCCESS); } assertEquals(pendingState.getPendingTxSize(), cnt); AionTransaction tx = genTransaction(BigInteger.TWO.toByteArray()); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.REPAYTX_LOWPRICE); assertEquals(pendingState.getPendingTxSize(), cnt); assertNotEquals(pendingState.getPendingTransactions().get(2), tx); } @Test public void addTxWithSameNonce() { AionTransaction tx = genTransaction(BigInteger.ZERO.toByteArray()); AionTransaction tx2 = genTransaction(BigInteger.ZERO.toByteArray()); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.SUCCESS); assertEquals(pendingState.addTransactionFromApiServer(tx2), TxResponse.REPAYTX_LOWPRICE); assertEquals(1, pendingState.getPendingTxSize()); List<AionTransaction> pendingTransactions = pendingState.getPendingTransactions(); assertEquals(1, pendingTransactions.size()); assertEquals(pendingTransactions.get(0), tx); } @Test public void addLargeNonce() { AionTransaction tx = AionTransaction.create( deployerKey, BigInteger.TEN.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, energyPrice, TransactionTypes.DEFAULT, null); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.CACHED_NONCE); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.ALREADY_CACHED); } @Test public void invalidEnergyLimit() { AionTransaction tx = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 10L, energyPrice, TransactionTypes.DEFAULT, null); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.INVALID_TX_NRG_LIMIT); } @Test public void alreadySealed() { AionTransaction tx = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, energyPrice, TransactionTypes.DEFAULT, null); AionTransaction tx2 = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("2"), ByteUtils.fromHexString("2"), 1000_000L, energyPrice * 2, TransactionTypes.DEFAULT, null); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.SUCCESS); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), pendingState.getPendingTransactions(), false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); assertEquals(connectResult.getLeft(), ImportResult.IMPORTED_BEST); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.ALREADY_SEALED); assertEquals(pendingState.addTransactionFromApiServer(tx2), TxResponse.ALREADY_SEALED); } @Test public void replayTransactionWithLessThanDoubleEnergyPrice() { AionTransaction tx1 = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, 10_000_000_000L, TransactionTypes.DEFAULT, null); AionTransaction tx2 = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, energyPrice * 2 - 1, TransactionTypes.DEFAULT, null); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx1)); assertEquals(TxResponse.REPAYTX_LOWPRICE, pendingState.addTransactionFromApiServer(tx2)); assertEquals(1, pendingState.getPendingTxSize()); } @Test public void replayTransactionWithDoubleEnergyPrice() { AionTransaction tx1 = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, energyPrice, TransactionTypes.DEFAULT, null); AionTransaction tx2 = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, energyPrice * 2, TransactionTypes.DEFAULT, null); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx1)); assertEquals(TxResponse.REPAID, pendingState.addTransactionFromApiServer(tx2)); assertEquals(1, pendingState.getPendingTxSize()); // tx2 will get cached and will replace tx1 if tx1 is not included in the next block. assertEquals(pendingState.getPendingTransactions().get(0), tx1); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), Collections.emptyList(), false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); assertEquals(connectResult.getLeft(), ImportResult.IMPORTED_BEST); (pendingState).applyBlockUpdate(block, connectResult.getRight().getReceipts()); assertEquals(pendingState.getPendingTransactions().get(0), tx2); } @Test public void replayTransactionWithDoubleEnergyPriceAfterSealing() { AionTransaction tx1 = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, energyPrice, TransactionTypes.DEFAULT, null); AionTransaction tx2 = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), ByteUtils.fromHexString("1"), ByteUtils.fromHexString("1"), 1000_000L, energyPrice * 2, TransactionTypes.DEFAULT, null); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx1)); assertEquals(TxResponse.REPAID, pendingState.addTransactionFromApiServer(tx2)); assertEquals(1, pendingState.getPendingTxSize()); // tx2 will get cached and will replace tx1 if tx1 is not included in the next block. assertEquals(pendingState.getPendingTransactions().get(0), tx1); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), pendingState.getPendingTransactions(), false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); assertEquals(connectResult.getLeft(), ImportResult.IMPORTED_BEST); pendingState.applyBlockUpdate(block, connectResult.getRight().getReceipts()); assertEquals(0, pendingState.getPendingTxSize()); } @Test public void replayTransactionThatUsesEntireBalance() { BigInteger balance = blockchain.getRepository().getBalance(new AionAddress(deployerKey.getAddress())); BigInteger value = balance.subtract(BigInteger.valueOf(21000*3).multiply(BigInteger.valueOf(energyPrice))); AionTransaction tx1 = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), value.toByteArray(), new byte[0], 21000, energyPrice, TransactionTypes.DEFAULT, null); AionTransaction tx2 = AionTransaction.create( deployerKey, BigInteger.ONE.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 21000, energyPrice, TransactionTypes.DEFAULT, null); /* tx1 and tx3 should use the entire balance. If tx2 is removed properly, tx3 should be * able to replace it in the pending state */ AionTransaction tx3 = AionTransaction.create( deployerKey, BigInteger.ONE.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 21000, energyPrice * 2, TransactionTypes.DEFAULT, null); // This would execute fine on top of tx2, but should have insufficient balance on top of tx3 AionTransaction tx4 = AionTransaction.create( deployerKey, BigInteger.TWO.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 21000, energyPrice, TransactionTypes.DEFAULT, null); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx1)); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx2)); assertEquals(TxResponse.REPAID, pendingState.addTransactionFromApiServer(tx3)); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx4)); assertEquals(3, pendingState.getPendingTxSize()); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), Collections.emptyList(), false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); assertEquals(connectResult.getLeft(), ImportResult.IMPORTED_BEST); pendingState.applyBlockUpdate(block, connectResult.getRight().getReceipts()); // tx3 should replace tx2, and tx4 will now have insufficient funds so it will get dropped assertEquals(2, pendingState.getPendingTxSize()); assertEquals(pendingState.getPendingTransactions().get(1), tx3); } @Test public void replayTransactionThatThatInvalidatesMiddleTx() { BigInteger balance = blockchain.getRepository().getBalance(new AionAddress(deployerKey.getAddress())); BigInteger value = balance.subtract(BigInteger.valueOf(21000*7).multiply(BigInteger.valueOf(energyPrice))); AionTransaction tx1 = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), value.toByteArray(), new byte[0], 21000, energyPrice, TransactionTypes.DEFAULT, null); AionTransaction tx2 = AionTransaction.create( deployerKey, BigInteger.ONE.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 21000, energyPrice, TransactionTypes.DEFAULT, null); /* tx1 and tx3 should use the entire balance. If tx2 is removed properly, tx3 should be * able to replace it in the pending state */ AionTransaction tx3 = AionTransaction.create( deployerKey, BigInteger.ONE.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 21000, energyPrice * 4, TransactionTypes.DEFAULT, null); // This would execute fine on top of tx2, but should have insufficient balance on top of tx3 AionTransaction tx4 = AionTransaction.create( deployerKey, BigInteger.TWO.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 21000, energyPrice * 4, TransactionTypes.DEFAULT, null); AionTransaction tx5 = AionTransaction.create( deployerKey, BigInteger.valueOf(3).toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 21000, energyPrice, TransactionTypes.DEFAULT, null); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx1)); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx2)); assertEquals(TxResponse.REPAID, pendingState.addTransactionFromApiServer(tx3)); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx4)); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx5)); assertEquals(4, pendingState.getPendingTxSize()); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), Collections.emptyList(), false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); assertEquals(connectResult.getLeft(), ImportResult.IMPORTED_BEST); pendingState.applyBlockUpdate(block, connectResult.getRight().getReceipts()); // tx3 should replace tx2, and tx4 will now have insufficient funds so it will get dropped assertEquals(2, pendingState.getPendingTxSize()); assertEquals(pendingState.getPendingTransactions().get(1), tx3); } @Test public void replayInvalidTransactionInMiddle() { BigInteger balance = blockchain.getRepository().getBalance(new AionAddress(deployerKey.getAddress())); BigInteger value = balance.subtract(BigInteger.valueOf(21000*3).multiply(BigInteger.valueOf(energyPrice))); AionTransaction tx1 = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), value.toByteArray(), new byte[0], 21000, energyPrice, TransactionTypes.DEFAULT, null); AionTransaction tx2 = AionTransaction.create( deployerKey, BigInteger.ONE.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 21000, energyPrice, TransactionTypes.DEFAULT, null); AionTransaction tx3 = AionTransaction.create( deployerKey, BigInteger.ONE.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 21000, energyPrice * 4, TransactionTypes.DEFAULT, null); // This tx will get dropped after tx3 is rejected AionTransaction tx4 = AionTransaction.create( deployerKey, BigInteger.TWO.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), new byte[0], 21000, energyPrice, TransactionTypes.DEFAULT, null); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx1)); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx2)); assertEquals(TxResponse.REPAID, pendingState.addTransactionFromApiServer(tx3)); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx4)); assertEquals(3, pendingState.getPendingTxSize()); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), Collections.emptyList(), false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); assertEquals(connectResult.getLeft(), ImportResult.IMPORTED_BEST); pendingState.applyBlockUpdate(block, connectResult.getRight().getReceipts()); assertEquals(1, pendingState.getPendingTxSize()); } @Test public void energyLimitMinimum() { AionTransaction tx = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), ByteUtils.fromHexString("1"), 21_000L, energyPrice, TransactionTypes.DEFAULT, null); assertEquals(pendingState.addTransactionFromApiServer(tx), TxResponse.DROPPED); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), pendingState.getPendingTransactions(), false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); assertEquals(connectResult.getLeft(), ImportResult.IMPORTED_BEST); } @Test public void testAionPendingStateInit() { CfgAion.inst().getTx().setSeedMode(true); // NullPointerException should not happens AionHub.createForTesting(CfgAion.inst(), blockchain, new PendingTxCallback(new ArrayList<>()), new NetworkBestBlockCallback(AionImpl.inst()), new TransactionBroadcastCallback(AionImpl.inst())); CfgAion.inst().getTx().setSeedMode(false); } @Test public void addTransactionFromNetworkTest() { List<AionTransaction> mockTransactions = getMockTransaction(0, 10, 0); pendingState.addTransactionsFromNetwork(mockTransactions); assertEquals(10 , pendingState.getPendingTxSize()); List<AionTransaction> pooledTransactions = pendingState.getPendingTransactions(); for (int i=0 ; i< 10 ; i++) { assertEquals(mockTransactions.get(i), pooledTransactions.get(i)); } } @Test public void addTransactionsFromCacheTest() { List<AionTransaction> transactionsInPool = getMockTransaction(0, 5, 0); List<AionTransaction> transactionsInCache = getMockTransaction(6, 5, 0); List<AionTransaction> missingTransaction = getMockTransaction(5, 1, 0); pendingState.addTransactionsFromNetwork(transactionsInPool); assertEquals(5 , pendingState.getPendingTxSize()); pendingState.addTransactionsFromNetwork(transactionsInCache); assertEquals(5 , pendingState.getPendingTxSize()); assertEquals(5 , pendingState.getCachePoolSize()); pendingState.addTransactionsFromNetwork(missingTransaction); assertEquals(11 , pendingState.getPendingTxSize()); assertEquals(0 , pendingState.getCachePoolSize()); List<AionTransaction> pooledTransactions = pendingState.getPendingTransactions(); assertEquals(11, pooledTransactions.size()); } @Test public void repayTransactionTest() { AionTransaction tx = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), ByteUtils.fromHexString("1"), 21_000L * 10, energyPrice, TransactionTypes.DEFAULT, null); AionTransaction repayTx = AionTransaction.create( deployerKey, BigInteger.ZERO.toByteArray(), new AionAddress(new byte[32]), BigInteger.ZERO.toByteArray(), ByteUtils.fromHexString("1"), 21_000L * 10, energyPrice * 2, TransactionTypes.DEFAULT, null); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(tx)); assertEquals(1 , pendingState.getPendingTxSize()); assertEquals(TxResponse.REPAID, pendingState.addTransactionFromApiServer(repayTx)); assertEquals(1 , pendingState.getPendingTxSize()); assertEquals(tx, pendingState.getPendingTransactions().get(0)); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), Collections.emptyList(), false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); assertEquals(connectResult.getLeft(), ImportResult.IMPORTED_BEST); assertEquals(1 , pendingState.getPendingTxSize()); assertEquals(repayTx, pendingState.getPendingTransactions().get(0)); } @Test public void addTransactionInFullPoolTest() { List<AionTransaction> transactionsInPool = getMockTransaction(0, 2048, 0); pendingState.addTransactionsFromNetwork(transactionsInPool); assertEquals(2048, pendingState.getPendingTxSize()); List<AionTransaction> transactionInCache = getMockTransaction(2048, 1, 0); pendingState.addTransactionsFromNetwork(transactionInCache); assertEquals(2048, pendingState.getPendingTxSize()); assertEquals(1, pendingState.getCachePoolSize()); } @Test public void updateCacheTransactionsTest() { List<AionTransaction> transactions = getMockTransaction(0, 2, 0); List<AionTransaction> cachedTx = getMockTransaction(2, 1, 0); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(transactions.get(0))); assertEquals(1 , pendingState.getPendingTxSize()); assertEquals(TxResponse.CACHED_NONCE, pendingState.addTransactionFromApiServer(cachedTx.get(0))); assertEquals(1 , pendingState.getPendingTxSize()); assertEquals(1 , pendingState.getCachePoolSize()); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), transactions, false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); assertEquals(connectResult.getLeft(), ImportResult.IMPORTED_BEST); assertEquals(1 , pendingState.getPendingTxSize()); assertEquals(0 , pendingState.getCachePoolSize()); assertEquals(cachedTx.get(0), pendingState.getPendingTransactions().get(0)); } @Test public void updateCacheTransactionsTest2() { List<AionTransaction> transactions = getMockTransaction(0, 2, 0); List<AionTransaction> cachedTx = getMockTransaction(2, 2, 0); assertEquals(TxResponse.SUCCESS, pendingState.addTransactionFromApiServer(transactions.get(0))); assertEquals(1 , pendingState.getPendingTxSize()); pendingState.addTransactionsFromNetwork(cachedTx); assertEquals(1 , pendingState.getPendingTxSize()); assertEquals(2 , pendingState.getCachePoolSize()); transactions.add(cachedTx.get(0)); AionBlock block = blockchain.createNewMiningBlock( blockchain.getBestBlock(), transactions, false); Pair<ImportResult, AionBlockSummary> connectResult = blockchain.tryToConnectAndFetchSummary(block); assertEquals(connectResult.getLeft(), ImportResult.IMPORTED_BEST); assertEquals(1 , pendingState.getPendingTxSize()); assertEquals(0 , pendingState.getCachePoolSize()); assertEquals(cachedTx.get(1), pendingState.getPendingTransactions().get(0)); } }
41.477298
170
0.624446
c7da3162b7325a6bc866c564d186f1d8dea48a2c
1,538
package com.annas; import org.newdawn.slick.*; import org.newdawn.slick.geom.Vector2f; public class Main extends BasicGame { Player player; Enemy enemy; static Ball ball; static Vector2f mousePos; public static void main(String[] arguments) { try { AppGameContainer app = new AppGameContainer(new Main()); app.setDisplayMode(1024, 600, false); app.setShowFPS(false); app.start(); } catch (SlickException slickException) { slickException.printStackTrace(); } } public Main() { super("Pong"); } @Override public void init(GameContainer gameContainer) throws SlickException { player = new Player(50, 300, 50, 200, Color.blue); enemy = new Enemy(926, 300, 50, 200, Color.red); ball = new Ball(512, 300, 50, 50, Color.white); } @Override public void update(GameContainer gameContainer, int delta) throws SlickException { mousePos = new Vector2f(gameContainer.getInput().getMouseX(), gameContainer.getInput().getMouseY()); player.update(); enemy.update(); ball.collide(player); ball.collide(enemy); ball.update(); } @Override public void render(GameContainer container, Graphics graphics) throws SlickException { player.draw(graphics); enemy.draw(graphics); ball.draw(graphics); } }
25.213115
109
0.583875
6d99c6656267f39232fdbd104892757d9e6d39ec
4,539
package seedu.ezwatchlist.storage; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static seedu.ezwatchlist.testutil.Assert.assertThrows; import static seedu.ezwatchlist.testutil.TypicalShows.AVENGERSENDGAME; import static seedu.ezwatchlist.testutil.TypicalShows.FIGHTCLUB; import static seedu.ezwatchlist.testutil.TypicalShows.GODFATHER2; import static seedu.ezwatchlist.testutil.TypicalShows.getTypicalWatchList; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import seedu.ezwatchlist.commons.exceptions.DataConversionException; import seedu.ezwatchlist.model.WatchList; import seedu.ezwatchlist.model.ReadOnlyWatchList; public class JsonWatchListStorageTest { private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data", "JsonWatchListStorageTest"); @TempDir public Path testFolder; @Test public void readWatchList_nullFilePath_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> readWatchList(null)); } private java.util.Optional<ReadOnlyWatchList> readWatchList(String filePath) throws Exception { return new JsonWatchListStorage(Paths.get(filePath)).readWatchList(addToTestDataPathIfNotNull(filePath)); } private Path addToTestDataPathIfNotNull(String prefsFileInTestDataFolder) { return prefsFileInTestDataFolder != null ? TEST_DATA_FOLDER.resolve(prefsFileInTestDataFolder) : null; } @Test public void read_missingFile_emptyResult() throws Exception { assertFalse(readWatchList("NonExistentFile.json").isPresent()); } @Test public void read_notJsonFormat_exceptionThrown() { assertThrows(DataConversionException.class, () -> readWatchList("notJsonFormatWatchList.json")); } @Test public void readWatchList_invalidShowWatchList_throwDataConversionException() { assertThrows(DataConversionException.class, () -> readWatchList("invalidShowWatchList.json")); } @Test public void readWatchList_invalidAndValidShowWatchList_throwDataConversionException() { assertThrows(DataConversionException.class, () -> readWatchList("invalidAndValidShowWatchList.json")); } /* @Test public void readAndSaveWatchList_allInOrder_success() throws Exception { Path filePath = testFolder.resolve("TempWatchList.json"); WatchList original = getTypicalWatchList(); JsonWatchListStorage jsonWatchListStorage = new JsonWatchListStorage(filePath); // Save in new file and read back jsonWatchListStorage.saveWatchList(original, filePath); ReadOnlyWatchList readBack = jsonWatchListStorage.readWatchList(filePath).get(); assertEquals(original, new WatchList(readBack)); // Modify data, overwrite exiting file, and read back original.addShow(AVENGERSENDGAME); original.removeShow(FIGHTCLUB); jsonWatchListStorage.saveWatchList(original, filePath); readBack = jsonWatchListStorage.readWatchList(filePath).get(); assertEquals(original, new WatchList(readBack)); // Save and read without specifying file path original.addShow(GODFATHER2); jsonWatchListStorage.saveWatchList(original); // file path not specified readBack = jsonWatchListStorage.readWatchList().get(); // file path not specified assertEquals(original, new WatchList(readBack)); } */ @Test public void saveWatchList_nullWatchList_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> saveWatchList(null, "SomeFile.json")); } /** * Saves {@code watchList} at the specified {@code filePath}. */ private void saveWatchList(ReadOnlyWatchList watchList, String filePath) { try { new JsonWatchListStorage(Paths.get(filePath)) .saveWatchList(watchList, addToTestDataPathIfNotNull(filePath)); } catch (IOException ioe) { throw new AssertionError("There should not be an error writing to the file.", ioe); } } @Test public void saveWatchList_nullFilePath_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> saveWatchList(new WatchList(), null)); } }
40.168142
113
0.722186
5cb5c0c6eb2fc7011a0c024283bba93b352d829c
1,260
package team07.vikingwars.Model; /** * Woodcutter is a production building, it produces wood. * This class is a subclass of Building. */ public class Woodcutter extends Building { private int baseProduction; private int resourcePerTurn; /** * Constructor for woodcutter. * @param level */ public Woodcutter(int level) { super("Woodcutter", new int[]{20,20,10}, level, 1.0, 20, "Creates wood per tick. Amount varies based on level"); this.baseProduction = 3; this.resourcePerTurn = (int)(baseProduction * Math.pow(level,1.5)); } /** * @return baseProduction */ public int getBaseProduction() { return baseProduction; } /** * @return resourcePerTurn */ public int getResourcePerTurn() { return resourcePerTurn; } /** * Updates resource per turn. * @param level */ @Override public void setLevel(int level) { this.level = level; resourcePerTurn = (int)(baseProduction * Math.pow(level,1.5)); } /** * @return super.toString() and toString(). */ @Override public String getInfo() { return super.toString() + " Resources per turn: " + resourcePerTurn; } }
23.333333
120
0.603968
ccff97e978cb89d197da4f949a81774c87043a36
1,520
package com.faoncloud.app.messenger.MensageiroBranco.message; import java.util.Date; //{ // "fromid": "1", // "message": "Olá Mamae. Aqui é o papai.", // "sentdate": 1582680700506, // "toid": "2", // "read":"no" // } public class Message { private Integer id; private Integer fromid; private Integer toid; private String message; private Date sentdate; private String read; public Message(Integer id, Integer fromid, Integer toid, String message, Date sentdate, String read) { super(); this.id = id; this.fromid = fromid; this.toid = toid; this.message = message; this.sentdate = sentdate; this.read = read; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getFromid() { return fromid; } public void setFromid(Integer fromid) { this.fromid = fromid; } public Integer getToid() { return toid; } public void setToid(Integer toid) { this.toid = toid; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Date getSentdate() { return sentdate; } public void setSentdate(Date sentdate) { this.sentdate = sentdate; } public String getRead() { return read; } public void setRead(String read) { this.read = read; } @Override public String toString() { return "Message [id=" + id + ", fromid=" + fromid + ", toid=" + toid + ", message=" + message + ", sentdate=" + sentdate + ", read=" + read + "]"; } }
19.74026
111
0.652632
fe07f3ccc6d01954178d2f8245c3362dbc0021a0
169
package util.remoter.service; import remoter.annotations.Remoter; /** * To test @Remoter can be passed */ @Remoter public interface IGen<T> { T echo(T input); }
14.083333
35
0.698225
43b7e247a785c4fcce97a8aa37e489492e628bec
4,464
/* * The MIT License (MIT) * * Copyright (c) 2010 Technische Universitaet Berlin * * 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.mumie.mathletfactory.transformer.noc; import java.awt.Color; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import net.mumie.mathletfactory.action.message.TodoException; import net.mumie.mathletfactory.display.noc.MMPanel; import net.mumie.mathletfactory.display.noc.matrix.MatrixBorder; import net.mumie.mathletfactory.display.noc.matrix.StringMatrixPanel; import net.mumie.mathletfactory.math.number.MNumber; import net.mumie.mathletfactory.mmobject.MMObjectIF; import net.mumie.mathletfactory.mmobject.algebra.linalg.MMNumberMatrix; import net.mumie.mathletfactory.transformer.ContainerObjectTransformer; /** * Transformer for {@link net.mumie.mathletfactory.mmobject.algebra.linalg.MMNumberMatrix}. * * @author gronau * @mm.docstatus finished */ public class MatrixImageTransformer extends ContainerObjectTransformer implements ChangeListener { private StringMatrixPanel m_matrixPanel; public void initialize(MMObjectIF masterObject) { super.initialize(masterObject); int rowCount = getRealMaster().getRowCount(); int colCount = getRealMaster().getColumnCount(); String[] bitmap = new String[rowCount * colCount]; for(int r = 0; r < rowCount; r++) { for(int c = 0; c < colCount; c++) { bitmap[r*colCount+c] = "\u2588"; } } m_matrixPanel = new StringMatrixPanel(bitmap, getRealMaster().getRowCount(), getRealMaster().getColumnCount()); m_matrixPanel.setCellHeight(25); m_matrixPanel.setCellWidth(25); m_matrixPanel.setBorderType(MatrixBorder.BRACKETS); m_matrixPanel.setHorizontalCellAlignment(SwingConstants.CENTER); m_matrixPanel.setHorizontalCellAlignment(SwingConstants.CENTER); m_matrixPanel.setFont(m_matrixPanel.getFont().deriveFont((float)20)); getRealMaster().addDimensionChangeListener(this); // trick because StringMatrixPanel is not a MMPanel m_mmPanel = new MMPanel(getMaster(), this, m_matrixPanel) {}; render(); } public void render() { super.render(); int rowCount = getRealMaster().getRowCount(); int colCount = getRealMaster().getColumnCount(); for(int r = 1; r <= rowCount; r++) { for(int c = 1; c <= colCount; c++) { MNumber entry = (MNumber)getRealMaster().getEntryRef(r, c); int value = (int) entry.getDouble(); Color color = null; if( ! entry.isEdited()) { color = new Color(255, 175, 175); // rosa for non edited numbers } else if(value > 510) { // green for numbers > 510 color = new Color(0, 255, 0); } else if(value > 255) { // 255: white -> green: 510 int i = Math.abs(value - 510); color = new Color(i, 255, i); } else if(value >= 0) { // 0: black -> white: 255 color = new Color(value, value, value); } else if(value < -255) { // red for numbers < -255 color = new Color(255, 0, 0); } else { // -255: red -> 0: black int i = Math.abs(value); color = new Color(i, 0, 0); } m_matrixPanel.setCellForeground(r, c, color); } } } private MMNumberMatrix getRealMaster() { return (MMNumberMatrix) getMaster(); } public void stateChanged(ChangeEvent event) { throw new TodoException(); } }
39.857143
115
0.706541
cc19d7b2d603f9864956b54be61178171ecc6fba
1,072
public class Solution { /* Binary Tree Node class * * class BinaryTreeNode<T> { T data; BinaryTreeNode<T> left; BinaryTreeNode<T> right; public BinaryTreeNode(T data) { this.data = data; } } */ public static void printNodeFromK1ToK2(BinaryTreeNode<Integer> root,int k1,int k2){ if(root==null){ return ; } if(root.data >= k1 && root.data <= k2) { //15 20 30 //15 10 30 //15 20 30 printNodeFromK1ToK2(root.left,k1,k2); System.out.print(root.data+" "); printNodeFromK1ToK2(root.right,k1,k2); } if(root.data <k1){ printNodeFromK1ToK2(root.right,k1,k2); } if(root.data >k2){ printNodeFromK1ToK2(root.left,k1,k2); } } }
26.146341
91
0.407649
d2ebe7da12fbf1872ab71db1c3f1227ca2e51453
55
package segua; public abstract class PlayerPair { }
9.166667
34
0.745455
aa5ab4a9380dc7f7568d0519e656baf38846b59a
1,637
/* * Copyright 2015 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 io.bosh.client.releases; import io.bosh.client.internal.AbstractSpringOperations; import java.net.URI; import java.util.Arrays; import java.util.List; import org.springframework.web.client.RestTemplate; import rx.Observable; /** * @author David Ehringer */ public class SpringReleases extends AbstractSpringOperations implements Releases { public SpringReleases(RestTemplate restTemplate, URI root) { super(restTemplate, root); } @Override public Observable<List<ReleaseSummary>> list() { return get(ReleaseSummary[].class, builder -> builder.pathSegment("releases")) .map(results -> Arrays.asList(results)); } @Override public Observable<Release> get(String releaseName) { return get(Release.class, builder -> builder.pathSegment("releases", releaseName)) .map(response -> { response.setName(releaseName); return response; }); } }
30.314815
82
0.682346
f49e99a77538cb00a668419735f0dc19b797f2d3
246
package com.akshat14714.stockcalculator.common.dtos.request; import com.akshat14714.stockcalculator.common.dtos.LatLong; import lombok.Data; @Data public class DirectionRequest { private LatLong origin; private LatLong destination; }
18.923077
60
0.800813
ae83bebf18b3e8ba23b268d0217fee737acf02a9
11,886
/* * 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 cn.zhengcaiyun.idata.connector.resourcemanager.yarn.bean; /** * @description: yarn 集群应用 * 作为查询列表时,暂未加 resourceRequests 属性 * @author: yangjianhua * @create: 2021-12-09 16:26 **/ public class ClusterApp { /** * The application id */ private String id; /** * The user who started the application */ private String user; /** * The application name */ private String name; /** * The queue the application was submitted to */ private String queue; /** * The application state according to the ResourceManager - valid values are members of the YarnApplicationState enum: NEW, NEW_SAVING, SUBMITTED, ACCEPTED, RUNNING, FINISHED, FAILED, KILLED */ private String state; /** * The final status of the application if finished - reported by the application itself - valid values are the members of the FinalApplicationStatus enum: UNDEFINED, SUCCEEDED, FAILED, KILLED */ private String finalStatus; /** * The progress of the application as a percent */ private Float progress; /** * Where the tracking url is currently pointing - History (for history server) or ApplicationMaster */ private String trackingUI; /** * The web URL that can be used to track the application */ private String trackingUrl; /** * Detailed diagnostics information */ private String diagnostics; /** * The cluster id */ private Long clusterId; /** * The application type */ private String applicationType; /** * Comma separated tags of an application */ private String applicationTags; /** * Priority of the submitted application */ private String priority; /** * The time in which application started (in ms since epoch) */ private Long startedTime; /** * The time in which the application finished (in ms since epoch) */ private Long finishedTime; /** * The elapsed time since the application started (in ms) */ private Long elapsedTime; /** * The URL of the application master container logs */ private String amContainerLogs; /** * The nodes http address of the application master */ private String amHostHttpAddress; /** * The RPC address of the application master */ private String amRPCAddress; /** * The sum of memory in MB allocated to the application’s running containers */ private Integer allocatedMB; /** * The sum of virtual cores allocated to the application’s running containers */ private Integer allocatedVCores; /** * The number of containers currently running for the application */ private Integer runningContainers; /** * The amount of memory the application has allocated (megabyte-seconds) */ private Long memorySeconds; /** * The amount of CPU resources the application has allocated (virtual core-seconds) */ private Long vcoreSeconds; /** * The percentage of resources of the queue that the app is using */ private Float queueUsagePercentage; /** * The percentage of resources of the cluster that the app is using */ private Float clusterUsagePercentage; /** * Memory used by preempted container */ private Long preemptedResourceMB; /** * Number of virtual cores used by preempted container */ private Long preemptedResourceVCores; /** * Number of standard containers preempted */ private Integer numNonAMContainerPreempted; /** * Number of application master containers preempted */ private Integer numAMContainerPreempted; /** * Status of log aggregation - valid values are the members of the LogAggregationStatus enum: DISABLED, NOT_START, RUNNING, RUNNING_WITH_FAILURE, SUCCEEDED, FAILED, TIME_OUT */ private String logAggregationStatus; /** * Is the application unmanaged */ private Boolean unmanagedApplication; /** * Node Label expression which is used to identify the nodes on which application’s containers are expected to run by default */ private String appNodeLabelExpression; /** * Node Label expression which is used to identify the node on which application’s AM container is expected to run */ private String amNodeLabelExpression; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getQueue() { return queue; } public void setQueue(String queue) { this.queue = queue; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getFinalStatus() { return finalStatus; } public void setFinalStatus(String finalStatus) { this.finalStatus = finalStatus; } public Float getProgress() { return progress; } public void setProgress(Float progress) { this.progress = progress; } public String getTrackingUI() { return trackingUI; } public void setTrackingUI(String trackingUI) { this.trackingUI = trackingUI; } public String getTrackingUrl() { return trackingUrl; } public void setTrackingUrl(String trackingUrl) { this.trackingUrl = trackingUrl; } public String getDiagnostics() { return diagnostics; } public void setDiagnostics(String diagnostics) { this.diagnostics = diagnostics; } public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getApplicationType() { return applicationType; } public void setApplicationType(String applicationType) { this.applicationType = applicationType; } public String getApplicationTags() { return applicationTags; } public void setApplicationTags(String applicationTags) { this.applicationTags = applicationTags; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public Long getStartedTime() { return startedTime; } public void setStartedTime(Long startedTime) { this.startedTime = startedTime; } public Long getFinishedTime() { return finishedTime; } public void setFinishedTime(Long finishedTime) { this.finishedTime = finishedTime; } public Long getElapsedTime() { return elapsedTime; } public void setElapsedTime(Long elapsedTime) { this.elapsedTime = elapsedTime; } public String getAmContainerLogs() { return amContainerLogs; } public void setAmContainerLogs(String amContainerLogs) { this.amContainerLogs = amContainerLogs; } public String getAmHostHttpAddress() { return amHostHttpAddress; } public void setAmHostHttpAddress(String amHostHttpAddress) { this.amHostHttpAddress = amHostHttpAddress; } public String getAmRPCAddress() { return amRPCAddress; } public void setAmRPCAddress(String amRPCAddress) { this.amRPCAddress = amRPCAddress; } public Integer getAllocatedMB() { return allocatedMB; } public void setAllocatedMB(Integer allocatedMB) { this.allocatedMB = allocatedMB; } public Integer getAllocatedVCores() { return allocatedVCores; } public void setAllocatedVCores(Integer allocatedVCores) { this.allocatedVCores = allocatedVCores; } public Integer getRunningContainers() { return runningContainers; } public void setRunningContainers(Integer runningContainers) { this.runningContainers = runningContainers; } public Long getMemorySeconds() { return memorySeconds; } public void setMemorySeconds(Long memorySeconds) { this.memorySeconds = memorySeconds; } public Long getVcoreSeconds() { return vcoreSeconds; } public void setVcoreSeconds(Long vcoreSeconds) { this.vcoreSeconds = vcoreSeconds; } public Float getQueueUsagePercentage() { return queueUsagePercentage; } public void setQueueUsagePercentage(Float queueUsagePercentage) { this.queueUsagePercentage = queueUsagePercentage; } public Float getClusterUsagePercentage() { return clusterUsagePercentage; } public void setClusterUsagePercentage(Float clusterUsagePercentage) { this.clusterUsagePercentage = clusterUsagePercentage; } public Long getPreemptedResourceMB() { return preemptedResourceMB; } public void setPreemptedResourceMB(Long preemptedResourceMB) { this.preemptedResourceMB = preemptedResourceMB; } public Long getPreemptedResourceVCores() { return preemptedResourceVCores; } public void setPreemptedResourceVCores(Long preemptedResourceVCores) { this.preemptedResourceVCores = preemptedResourceVCores; } public Integer getNumNonAMContainerPreempted() { return numNonAMContainerPreempted; } public void setNumNonAMContainerPreempted(Integer numNonAMContainerPreempted) { this.numNonAMContainerPreempted = numNonAMContainerPreempted; } public Integer getNumAMContainerPreempted() { return numAMContainerPreempted; } public void setNumAMContainerPreempted(Integer numAMContainerPreempted) { this.numAMContainerPreempted = numAMContainerPreempted; } public String getLogAggregationStatus() { return logAggregationStatus; } public void setLogAggregationStatus(String logAggregationStatus) { this.logAggregationStatus = logAggregationStatus; } public Boolean getUnmanagedApplication() { return unmanagedApplication; } public void setUnmanagedApplication(Boolean unmanagedApplication) { this.unmanagedApplication = unmanagedApplication; } public String getAppNodeLabelExpression() { return appNodeLabelExpression; } public void setAppNodeLabelExpression(String appNodeLabelExpression) { this.appNodeLabelExpression = appNodeLabelExpression; } public String getAmNodeLabelExpression() { return amNodeLabelExpression; } public void setAmNodeLabelExpression(String amNodeLabelExpression) { this.amNodeLabelExpression = amNodeLabelExpression; } }
24.608696
195
0.669527
865c6c87fbe20a8a9d953ef3a70da35542b7fbf8
7,553
package edu.cmu.lti.nlp.chinese.parser; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.List; import edu.cmu.lti.algorithm.structure.MyQueue; import edu.cmu.lti.algorithm.structure.MyStack; import edu.cmu.lti.nlp.chinese.util.Tree; import edu.cmu.lti.nlp.chinese.util.TreeHelper; /** * This class read in tree files and output new trees with head information marked * in a pretty printing format * During this process, FRAG rooted trees are eliminated from corpus */ public class GenerateTrainingData{ //private static Logger log = Logger.getLogger( GenerateTrainingData.class ); public static final String C_FILE_EXTENSION = ".fid"; public static final String E_FILE_EXTENSION = ".MRG"; public static final String HM_PP_TRANS_FILE_EXTENSION = ".training"; //default Language Chinese private static int LANG = Tree.CHINESE; private static BufferedWriter all = null; public static void main(String[] args){ if(args.length != 2){ System.err.println("Usage: java GenerateTrainingData LANG(E|C) dir_name"); System.exit(-1); } try{ if(args[0].equals("E")) LANG = Tree.ENGLISH; else if(args[0].equals("C")) LANG = Tree.CHINESE; else{ System.err.println("Usage: language options: E|C"); System.exit(-1); } File dir = new File(args[1]); try{ String fileName = dir.getPath()+"/all.trainingForZhangMaxentReducedBranching"; if(LANG == Tree.CHINESE){ fileName += ".C"; all = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF8")); }else{ fileName += ".E"; all = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))); } }catch(Exception ex){ ex.printStackTrace(); } visitAllFiles(dir); }catch(Exception ex){ ex.printStackTrace(); } } public static void visitAllFiles(File f) { if (f.isDirectory()) { String[] children = f.list(); for (int i=0; i<children.length; i++) { visitAllFiles(new File(f, children[i])); } } else { if(checkFileExtension(f.getName()) == true) processFile(f); } } private static boolean checkFileExtension(String fileName){ if(LANG == Tree.CHINESE){ if(fileName.endsWith(C_FILE_EXTENSION)) return true; else return false; }else{ if(fileName.endsWith(E_FILE_EXTENSION)) return true; else return false; } } public static void pseudoParse(Tree tree){ Tree root = tree; MyQueue<Tree> queue = TreeHelper.getPreterminals(tree); MyStack<Tree> stack = new MyStack<Tree>(); while(queue.peek() != null || stack.size() > 1){ List<String> featureList = FeatureExtractor.extractFeatureList(stack,queue); String action = null; if(stack.isEmpty()){ action = "S"; Tree queueItem = queue.poll(); if(queueItem.getHeadWord().matches("[‘“〔〈《「『([{〖【]")){ FeatureExtractor.bracketCount++; }else if(queueItem.getHeadWord().matches("[’”〕〉》」』)]}〗】]")){ FeatureExtractor.bracketCount--; } stack.push(queueItem); }else{ Tree top = stack.peek(); int indexAsChild = top.getIndexAsChild(); if(indexAsChild == 1){//Binary reduction Tree parent = TreeHelper.locateParent(top, root); action = "R:"+parent.getNormalizedLabel(); stack.pop(); stack.pop(); stack.push(parent); }else if(top.getParentNumOfChildren() == 1){//Unary reduction Tree parent = TreeHelper.locateParent(top, root); action = "U:"+parent.getNormalizedLabel(); stack.pop(); stack.push(parent); }else{//Shift action = "S"; Tree queueItem = queue.poll(); if(queueItem.getHeadWord().matches("[‘“〔〈《「『([{〖【]")){ FeatureExtractor.bracketCount++; }else if(queueItem.getHeadWord().matches("[’”〕〉》」』)]}〗】]")){ FeatureExtractor.bracketCount--; } stack.push(queueItem); } } FeatureExtractor.lastAction = action; try{ StringBuffer sb = new StringBuffer(); sb.append(action+" "); for(int i=0;i<featureList.size();i++){ //sb.append((i+1)+"-"); sb.append((i+1)+"-"); sb.append(featureList.get(i)); sb.append(" "); } sb.append("\n"); all.write(sb.toString()); }catch(Exception ex){ ex.printStackTrace(); } } } private static void processFile(File f){ try{ BufferedReader br = null; String line = null; if(LANG == Tree.CHINESE){ br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "GB18030")); while( (line = br.readLine()) != null){ if(line.startsWith("<S ID=")){ String id = line.substring(line.indexOf('=')+1, line.lastIndexOf('>')); StringBuffer strBuffer = new StringBuffer(); while(true){ line = br.readLine(); if(line == null){ System.err.println("Error in processFile method: Ill-formated input tree file, <S> tag not closed by </S>"); System.exit(-1); } if(line.equals("</S>")){ break; } strBuffer.append(line.trim()); } String treeStr = strBuffer.toString(); if(treeStr.trim().length() > 0){ Tree tree = Tree.newNode(id, strBuffer.toString(), LANG); if(tree == null){ System.err.println("For file "+f.getName()+" Error in processFile method: Ill-bracketed tree string:"+strBuffer.toString()); System.exit(-1); } TreeHelper.removeEmptyNode(tree); TreeHelper.markHeadNode(tree); TreeHelper.transform(tree); pseudoParse(tree); } } } } else{ br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); line = br.readLine(); while( line != null){ if(line.startsWith("(")){ StringBuffer strBuffer = new StringBuffer(); strBuffer.append(line.trim()); while(true){ line = br.readLine(); if(line == null || line.startsWith("(")){ break; } strBuffer.append(line.trim()); } String treeStr = strBuffer.toString(); if(treeStr.trim().length() > 0){ Tree tree = Tree.newNode(strBuffer.toString(), LANG); if(tree == null){ System.err.println("For file "+f.getName()+" Error in processFile method: Ill-bracketed tree string:"+strBuffer.toString()); System.exit(-1); } TreeHelper.removeEmptyNode(tree); TreeHelper.markHeadNode(tree); TreeHelper.transform(tree); pseudoParse(tree); } }else line = br.readLine(); } } all.flush(); }catch(Exception ex){ ex.printStackTrace(); } } }
32.277778
140
0.562426
04d564492a6ca7ff0012f48cbbd974f8a5b84cf1
7,627
package com.oxygenxml.gim.ui.ec; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.actions.ActionFactory; /** * Filter text field * */ public abstract class ECFilterText extends SourceViewer { /** * Ignore modifications. */ private boolean ignoreModificationEvent = false; /** * The gray color. */ private Color grayColor = Display.getDefault().getSystemColor(SWT.COLOR_GRAY); /** * The regular color. */ private Color normalColor = null; /** * A custom filter hint */ private final String filterHint; /** * Constructor. * * @param parent The parent composite. * @param customFilterHint The filter hint */ public ECFilterText(Composite parent, String customFilterHint) { super(parent, null, null, false, SWT.SINGLE); this.filterHint = customFilterHint; // Set a document in order to have Undo/Redo operations available. setDocument(new Document()); // Configure the source viewer. configure(new SourceViewerConfiguration()); // Set the find hint text. reset(); // Watches the changes in the text field. getTextWidget().addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { update(); } }); // Set the original search hint or reset it on focus gained/lost. getTextWidget().addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { if (getTextWidget().getText().length() == 0) { // If nothing was written, put back the HINT... reset(); } } @Override public void focusGained(FocusEvent e) { if (isShowingHint()) { ignoreModificationEvent = true; try { // It is showing the HINT. Clean it up. getTextWidget().setText(""); } finally { ignoreModificationEvent = false; } } } }); getTextWidget().addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { if (normalColor != null) { normalColor.dispose(); normalColor = null; } } }); } /** * Update the field. */ private void update() { if (!ignoreModificationEvent) { getTextWidget().setForeground(normalColor); filterWasChanged(getTextWidget().getText()); } Iterator<UpdateableAction> iter = actions.values().iterator(); while (iter.hasNext()) { iter.next().updateActionState(); } } /** * Updateable action. */ private class UpdateableAction extends Action { /** * The action's ID. */ private int actionID; /** * Updateable action's constructor. * * @param text The action's name. * @param actionID The action's id. */ public UpdateableAction(String text, int actionID) { super(text); this.actionID = actionID; } /** * Update the action's state. */ public void updateActionState() { setEnabled(canDoOperation(actionID)); } } /** * @param text The filter text. */ protected abstract void filterWasChanged(String text); public void reset() { try { if (normalColor == null) { normalColor = getTextWidget().getForeground(); } ignoreModificationEvent = true; // Set the italic font. // Set the gray color. getTextWidget().setForeground(grayColor); getTextWidget().setText(filterHint); setSelectedRange(0, getTextWidget().getText().length()); // Reset the undo manager in order not to present the filter hint... getUndoManager().reset(); } finally { ignoreModificationEvent = false; } } /** * @return True if is showing hint. */ public boolean isShowingHint() { if (filterHint != null && getTextWidget() != null) { return filterHint.equals(getTextWidget().getText()); } return false; } /** * Set field background color. * * @param color The background color. */ public void setFieldBgColor(Color color) { getTextWidget().setBackground(color); } /** * The actions map. */ private Map<String, UpdateableAction> actions = new HashMap<String, UpdateableAction>(); /** * Get the action for the specified id if possible. * * @param id The action's ID. * @return The action if available. */ public IAction getAction(String id) { UpdateableAction action = actions.get(id); if (action == null) { if (id.equals(ActionFactory.CUT.getId())) { action = new UpdateableAction("Cut", CUT) { /** * @see org.eclipse.jface.action.Action#run() */ @Override public void run() { if (canDoOperation(CUT)) { doOperation(CUT); } } }; } else if (id.equals(ActionFactory.COPY.getId())) { action = new UpdateableAction("Copy", COPY) { /** * @see org.eclipse.jface.action.Action#run() */ @Override public void run() { if (canDoOperation(COPY)) { doOperation(COPY); } } }; } else if (id.equals(ActionFactory.PASTE.getId())) { action = new UpdateableAction("Paste", PASTE) { /** * @see org.eclipse.jface.action.Action#run() */ @Override public void run() { if (canDoOperation(PASTE)) { doOperation(PASTE); update(); } } }; } else if (id.equals(ActionFactory.DELETE.getId())) { action = new UpdateableAction("Delete", DELETE) { /** * @see org.eclipse.jface.action.Action#run() */ @Override public void run() { if (canDoOperation(DELETE)) { doOperation(DELETE); update(); } } }; } else if (id.equals(ActionFactory.UNDO.getId())) { action = new UpdateableAction("Undo", UNDO) { /** * @see org.eclipse.jface.action.Action#run() */ @Override public void run() { if (canDoOperation(UNDO)) { doOperation(UNDO); update(); } } }; } else if (id.equals(ActionFactory.REDO.getId())) { action = new UpdateableAction("Redo", REDO) { /** * @see org.eclipse.jface.action.Action#run() */ @Override public void run() { if (canDoOperation(REDO)) { doOperation(REDO); update(); } } }; } actions.put(id, action); } return action; } }
26.482639
90
0.576505
5f371b98fe95a8c19c15a75c6b87ed1c5aaa912d
812
package com.amituofo.xcexplorer.entry.plugin.hitachi.hcp.model; import javax.swing.DefaultComboBoxModel; import com.amituofo.common.ex.ServiceException; import com.amituofo.xfs.plugin.fs.objectstorage.hcp.item.HCPFileItem; import com.amituofo.xfs.plugin.fs.objectstorage.hcp.item.HCPMetadataItem; public class HCPObjectMetadataListModel extends DefaultComboBoxModel<HCPMetadataItem> { // AbstractTableModel private HCPFileItem object; public HCPObjectMetadataListModel() { } public HCPFileItem getWorkingObject() { return object; } public int listMetadata(HCPFileItem object) throws ServiceException { this.removeAllElements(); HCPMetadataItem[] metas; metas = object.listMetadatas(); for (int i = 0; i < metas.length; i++) { this.addElement(metas[i]); } return metas.length; } }
26.193548
109
0.780788
803346cde537148a91bb71342c2bd71947ad8e9b
581
package com.sefford.common; import com.sefford.common.interfaces.Postable; /** * NullPostable is a dummy implementation of a Postable using Null-Object. It does nothing at all * when a element is received. * * @author Saul Diaz <[email protected]> */ public class NullPostable implements Postable { /** * Single instance of NullPostable, it is not necessary to use more memory than required. */ public static final NullPostable INSTANCE = new NullPostable(); private NullPostable() { } @Override public void post(Object event) { } }
23.24
97
0.702238
440b09991bdc82ec43600d873d3d0344a3d16f19
206
package com.wesring.example; /** * * @author Wes Ring * */ public class Drink { String type; public Drink(String _drink) { type = _drink; } public String getDrinkType() { return type; } }
11.444444
31
0.631068
bc1198d979a1020c317b965341674a097875b681
129
public class PacketThreadUtil$1 { // Failed to decompile, took too long to decompile: net/minecraft/network/PacketThreadUtil$1 }
43
93
0.79845
2480e928bbe8141a63346371d58fb47dad3d5cb7
17,501
/* * ### * Xcodebuild Command-Line Wrapper * * Copyright (C) 1999 - 2012 Photon Infotech 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. * ### */ /******************************************************************************* * Copyright (c) 2012 Photon infotech. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Photon Public License v1.0 * which accompanies this distribution, and is available at * http://www.photon.in/legal/ppl-v10.html * * 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: * Photon infotech - initial API and implementation ******************************************************************************/ package com.photon.phresco.plugins.xcode; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.photon.phresco.plugin.commons.PluginUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.codehaus.jettison.json.JSONObject; import org.codehaus.plexus.archiver.zip.ZipArchiver; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.photon.phresco.commons.BuildInfo; import com.photon.phresco.commons.XCodeConstants; import com.photon.phresco.exception.PhrescoException; import com.photon.phresco.plugins.xcode.utils.SdkVerifier; import com.photon.phresco.plugins.xcode.utils.XcodeUtil; /** * Run the xcodebuild command line program * * @goal xcodebuild * @phase compile */ public class XcodeBuild extends AbstractMojo { private static final String DO_NOT_CHECKIN_BUILD = "/do_not_checkin/build"; /** * Location of the xcodebuild executable. * * @parameter expression="${xcodebuild}" default-value="/usr/bin/xcodebuild" */ private File xcodeCommandLine; /** * Project Name * * @parameter */ private String xcodeProject; /** * Target to be built * * @parameter expression="${targetName}" */ private String xcodeTarget; /** * @parameter expression="${encrypt}" */ private boolean encrypt; /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ protected MavenProject project; /** * @parameter expression="${basedir}" */ private String basedir; /** * @parameter expression="${unittest}" */ private boolean unittest; /** * Build directory. * * @parameter expression="${project.build.directory}" * @required */ private File buildDirectory; /** * @parameter expression="${configuration}" default-value="Debug" */ private String configuration; /** * @parameter expression="${sdk}" default-value="iphonesimulator5.0" */ private String sdk; /** * @parameter */ protected String gccpreprocessor; /** * The java sources directory. * * @parameter default-value="${project.basedir}" * * @readonly */ protected File baseDir; /** * @parameter expression="${environmentName}" required="true" */ protected String environmentName; /** * XML property list file. In this file the webserverName * * @parameter expression="${plistfile}" * default-value="phresco-env-config.xml" */ protected String plistFile; /** * @parameter expression="${buildNumber}" required="true" */ protected String buildNumber; protected int buildNo; private File srcDir; private File buildDirFile; private File buildInfoFile; private List<BuildInfo> buildInfoList; private int nextBuildNo; private Date currentDate; private String appFileName; private String dSYMFileName; private String deliverable; private Map<String, Object> sdkOptions; /** * Execute the xcode command line utility. */ public void execute() throws MojoExecutionException { if (!xcodeCommandLine.exists()) { throw new MojoExecutionException("Invalid path, invalid xcodebuild file: " + xcodeCommandLine.getAbsolutePath()); } /* * // Compute archive name String archiveName = * project.getBuild().getFinalName() + ".cust"; File finalDir = new * File(buildDirectory, archiveName); * * // Configure archiver MavenArchiver archiver = new MavenArchiver(); * archiver.setArchiver(jarArchiver); archiver.setOutputFile(finalDir); */ try { if(!SdkVerifier.isAvailable(sdk)) { throw new MojoExecutionException("Selected version " +sdk +" is not available!"); } } catch (IOException e2) { throw new MojoExecutionException("SDK verification failed!"); } catch (InterruptedException e2) { throw new MojoExecutionException("SDK verification interrupted!"); } try { init(); configure(); ProcessBuilder pb = new ProcessBuilder(xcodeCommandLine.getAbsolutePath()); // Include errors in output pb.redirectErrorStream(true); List<String> commands = pb.command(); if (xcodeProject != null) { commands.add("-project"); commands.add(xcodeProject); } if (StringUtils.isNotBlank(configuration)) { commands.add("-configuration"); commands.add(configuration); } if (StringUtils.isNotBlank(sdk)) { commands.add("-sdk"); commands.add(sdk); } commands.add("OBJROOT=" + buildDirectory); commands.add("SYMROOT=" + buildDirectory); commands.add("DSTROOT=" + buildDirectory); if (StringUtils.isNotBlank(xcodeTarget)) { commands.add("-target"); commands.add(xcodeTarget); } if(StringUtils.isNotBlank(gccpreprocessor)) { commands.add("GCC_PREPROCESSOR_DEFINITIONS="+gccpreprocessor); } if (unittest) { commands.add("clean"); commands.add("build"); } getLog().info("List of commands" + pb.command()); // pb.command().add("install"); pb.directory(new File(basedir)); Process child = pb.start(); // Consume subprocess output and write to stdout for debugging InputStream is = new BufferedInputStream(child.getInputStream()); int singleByte = 0; while ((singleByte = is.read()) != -1) { // output.write(buffer, 0, bytesRead); System.out.write(singleByte); } child.waitFor(); int exitValue = child.exitValue(); getLog().info("Exit Value: " + exitValue); if (exitValue != 0) { throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!"); } if(!unittest) { //In case of unit testcases run, the APP files will not be generated. createdSYM(); createApp(); } /* * child.waitFor(); * * InputStream in = child.getInputStream(); InputStream err = * child.getErrorStream(); getLog().error(sb.toString()); */ } catch (IOException e) { getLog().error("An IOException occured."); throw new MojoExecutionException("An IOException occured", e); } catch (InterruptedException e) { getLog().error("The clean process was been interrupted."); throw new MojoExecutionException("The clean process was been interrupted", e); } catch (MojoFailureException e) { // TODO Auto-generated catch block e.printStackTrace(); } File directory = new File(this.basedir + "/pom.xml"); this.project.getArtifact().setFile(directory); } private void init() throws MojoExecutionException, MojoFailureException { try { // To Delete the buildDirectory if already exists if (buildDirectory.exists()) { FileUtils.deleteDirectory(buildDirectory); buildDirectory.mkdirs(); } buildInfoList = new ArrayList<BuildInfo>(); // initialization // srcDir = new File(baseDir.getPath() + File.separator + // sourceDirectory); buildDirFile = new File(baseDir, DO_NOT_CHECKIN_BUILD); if (!buildDirFile.exists()) { buildDirFile.mkdirs(); getLog().info("Build directory created..." + buildDirFile.getPath()); } buildInfoFile = new File(buildDirFile.getPath() + "/build.info"); System.out.println("file created " + buildInfoFile); nextBuildNo = generateNextBuildNo(); currentDate = Calendar.getInstance().getTime(); } catch (IOException e) { throw new MojoFailureException("APP could not initialize " + e.getLocalizedMessage()); } } private int generateNextBuildNo() throws IOException { int nextBuildNo = 1; if (!buildInfoFile.exists()) { return nextBuildNo; } BufferedReader read = new BufferedReader(new FileReader(buildInfoFile)); String content = read.readLine(); Gson gson = new Gson(); java.lang.reflect.Type listType = new TypeToken<List<BuildInfo>>() { }.getType(); buildInfoList = (List<BuildInfo>) gson.fromJson(content, listType); if (buildInfoList == null || buildInfoList.size() == 0) { return nextBuildNo; } int buildArray[] = new int[buildInfoList.size()]; int count = 0; for (BuildInfo buildInfo : buildInfoList) { buildArray[count] = buildInfo.getBuildNo(); count++; } Arrays.sort(buildArray); // sort to the array to find the max build no nextBuildNo = buildArray[buildArray.length - 1] + 1; // increment 1 to // the max in // the build // list return nextBuildNo; } private void createApp() throws MojoExecutionException { File outputFile = getAppName(); if (outputFile == null) { getLog().error("xcodebuild failed. resultant APP not generated!"); throw new MojoExecutionException("xcodebuild has been failed"); } if (outputFile.exists()) { try { System.out.println("Completed " + outputFile.getAbsolutePath()); getLog().info("APP created.. Copying to Build directory....."); String buildName = project.getBuild().getFinalName() + '_' + getTimeStampForBuildName(currentDate); File baseFolder = new File(baseDir + DO_NOT_CHECKIN_BUILD, buildName); if (!baseFolder.exists()) { baseFolder.mkdirs(); getLog().info("build output direcory created at " + baseFolder.getAbsolutePath()); } File destFile = new File(baseFolder, outputFile.getName()); getLog().info("Destination file " + destFile.getAbsolutePath()); XcodeUtil.copyFolder(outputFile, destFile); getLog().info("copied to..." + destFile.getName()); appFileName = destFile.getAbsolutePath(); getLog().info("Creating deliverables....."); ZipArchiver zipArchiver = new ZipArchiver(); zipArchiver.addDirectory(baseFolder); File deliverableZip = new File(baseDir + DO_NOT_CHECKIN_BUILD, buildName + ".zip"); zipArchiver.setDestFile(deliverableZip); zipArchiver.createArchive(); deliverable = deliverableZip.getAbsolutePath(); getLog().info("Deliverables available at " + deliverableZip.getName()); writeBuildInfo(true); } catch (IOException e) { throw new MojoExecutionException("Error in writing output..." + e.getLocalizedMessage()); } } else { getLog().info("output directory not found"); } } private void createdSYM() throws MojoExecutionException { File outputFile = getdSYMName(); if (outputFile == null) { getLog().error("xcodebuild failed. resultant dSYM not generated!"); throw new MojoExecutionException("xcodebuild has been failed"); } if (outputFile.exists()) { try { System.out.println("Completed " + outputFile.getAbsolutePath()); getLog().info("dSYM created.. Copying to Build directory....."); String buildName = project.getBuild().getFinalName() + '_' + getTimeStampForBuildName(currentDate); File baseFolder = new File(baseDir + DO_NOT_CHECKIN_BUILD, buildName); if (!baseFolder.exists()) { baseFolder.mkdirs(); getLog().info("build output direcory created at " + baseFolder.getAbsolutePath()); } File destFile = new File(baseFolder, outputFile.getName()); getLog().info("Destination file " + destFile.getAbsolutePath()); XcodeUtil.copyFolder(outputFile, destFile); getLog().info("copied to..." + destFile.getName()); dSYMFileName = destFile.getAbsolutePath(); getLog().info("Creating deliverables....."); ZipArchiver zipArchiver = new ZipArchiver(); zipArchiver.addDirectory(baseFolder); File deliverableZip = new File(baseDir + DO_NOT_CHECKIN_BUILD, buildName + ".zip"); zipArchiver.setDestFile(deliverableZip); zipArchiver.createArchive(); deliverable = deliverableZip.getAbsolutePath(); getLog().info("Deliverables available at " + deliverableZip.getName()); } catch (IOException e) { throw new MojoExecutionException("Error in writing output..." + e.getLocalizedMessage()); } } else { getLog().info("output directory not found"); } } private File getAppName() { String path = configuration + "-"; if (sdk.startsWith("iphoneos")) { path = path + "iphoneos"; } else { path = path + "iphonesimulator"; } File baseFolder = new File(buildDirectory, path); File[] files = baseFolder.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.getName().endsWith("app")) { return file; } } return null; } private File getdSYMName() { String path = configuration + "-"; if (sdk.startsWith("iphoneos")) { path = path + "iphoneos"; } else { path = path + "iphonesimulator"; } File baseFolder = new File(buildDirectory, path); File[] files = baseFolder.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.getName().endsWith("dSYM")) { return file; } } return null; } private void writeBuildInfo(boolean isBuildSuccess) throws MojoExecutionException { try { if (buildNumber != null) { buildNo = Integer.parseInt(buildNumber); } PluginUtils pu = new PluginUtils(); BuildInfo buildInfo = new BuildInfo(); List<String> envList = pu.csvToList(environmentName); if (buildNo > 0) { buildInfo.setBuildNo(buildNo); } else { buildInfo.setBuildNo(nextBuildNo); } buildInfo.setTimeStamp(getTimeStampForDisplay(currentDate)); if (isBuildSuccess) { buildInfo.setBuildStatus("SUCCESS"); } else { buildInfo.setBuildStatus("FAILURE"); } buildInfo.setBuildName(appFileName); buildInfo.setDeliverables(deliverable); buildInfo.setEnvironments(envList); Map<String, Boolean> sdkOptions = new HashMap<String, Boolean>(2); boolean isDeviceBuild = Boolean.FALSE; if (sdk.startsWith("iphoneos")) { isDeviceBuild = Boolean.TRUE; } sdkOptions.put(XCodeConstants.CAN_CREATE_IPA, isDeviceBuild); sdkOptions.put(XCodeConstants.DEVICE_DEPLOY, isDeviceBuild); buildInfo.setOptions(sdkOptions); // Gson gson2 = new Gson(); // String json = gson2.toJson(sdkOptions); // System.out.println("json = " + json); buildInfoList.add(buildInfo); Gson gson2 = new Gson(); FileWriter writer = new FileWriter(buildInfoFile); //gson.toJson(buildInfoList, writer); String json = gson2.toJson(buildInfoList); System.out.println("json = " + json); writer.write(json); writer.close(); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } private String getTimeStampForDisplay(Date currentDate) { SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss"); String timeStamp = formatter.format(currentDate.getTime()); return timeStamp; } private String getTimeStampForBuildName(Date currentDate) { SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy-HH-mm-ss"); String timeStamp = formatter.format(currentDate.getTime()); return timeStamp; } private void configure() throws MojoExecutionException { if (StringUtils.isEmpty(environmentName)) { return; } try { getLog().info("Configuring the project...."); getLog().info("environment name :" + environmentName); getLog().info("base dir name :" + baseDir.getName()); File srcConfigFile = new File(baseDir, project.getBuild().getSourceDirectory() + File.separator + plistFile); String basedir = baseDir.getName(); PluginUtils pu = new PluginUtils(); pu.executeUtil(environmentName, basedir, srcConfigFile); pu.setDefaultEnvironment(environmentName, srcConfigFile); // if(encrypt) { // pu.encode(srcConfigFile); // } } catch (PhrescoException e) { throw new MojoExecutionException(e.getMessage(), e); } } }
31.030142
112
0.689618
0c6bb9c1d1418b7cf5f5f1a21cf9cc7d0739463b
186
package br.com.economize.dao; /** * @author Mateus Henrique Tofanello * */ import br.com.economize.domain.Empresa; public class EmpresaDAO extends GenericDAO<Empresa> { }
15.5
54
0.704301
ff1f581f7ac87cb6402987cc0ff0302d52a19939
1,843
package com.ashessin.cs474.hw1.generator.creational; import com.ashessin.cs474.hw1.generator.*; public class SingletonGen extends DesignPatternGen { private String packageName; private String singletonName; private String singletonInstanceFieldName; private String singletonAccessorMethodName; public SingletonGen(String packageName, String singletonName, String singletonInstanceFieldName, String singletonAccessorMethodName) { this.packageName = packageName; this.singletonName = singletonName; this.singletonInstanceFieldName = singletonInstanceFieldName; this.singletonAccessorMethodName = singletonAccessorMethodName; } public DpArrayList<DpSource> main() { DpClassSource singleton = DpClassSource.newBuilder(packageName, singletonName) .setJavadoc("Singleton class implements singleton pattern. Only one object can be " + "instantiated.") .addField(DpSourceField.newBuilder(singletonInstanceFieldName, singletonName) .setAccessModifier(DpSourceField.AccessModifier.PRIVATE) .addModifier(DpSourceField.Modifier.STATIC) .build()) .addMethod(DpSourceMethod.newBuilder() .setIsConstructor(Boolean.TRUE) .setAccessModifier(DpSourceMethod.AccessModifier.PRIVATE) .build()) .addMethod(DpSourceMethod.newBuilder() .setName(singletonAccessorMethodName) .addModifier(DpSourceMethod.Modifier.STATIC) .addModifier(DpSourceMethod.Modifier.SYNCHRONIZED) .setReturnType(singletonName) .setBody(String.format( "if (%s == null) {\n" + " %s = new %s();\n" + "}\n" + "return %s;", singletonInstanceFieldName, singletonInstanceFieldName, singletonName, singletonInstanceFieldName)) .build()) .build(); dpSources.add(singleton, this.getClass()); return dpSources; } }
34.773585
100
0.742811
27edfeca7add336f97f163e3e29113607d111557
814
package cn.jianke.imagedeal.imageloader; import android.content.Context; import com.bumptech.glide.load.model.GenericLoaderFactory; import com.bumptech.glide.load.model.ModelLoader; import com.bumptech.glide.load.model.ModelLoaderFactory; import java.io.InputStream; /** * @className:CustomImageSizeModelFactory * @classDescription: 自定义图片大小工厂 * @author: leibing * @createTime: */ public class CustomImageSizeModelFactory implements ModelLoaderFactory<CustomImageSizeModel, InputStream> { @Override public ModelLoader<CustomImageSizeModel, InputStream> build(Context context, GenericLoaderFactory factories) { return new CustomImageSizeUrlLoader( context ); } @Override public void teardown() { } }
26.258065
97
0.710074
f1a04d7467e458149ff1d1fa3d7738c26e298fae
398
package com.spingular.cms.repository; import com.spingular.cms.domain.Feedback; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data SQL repository for the Feedback entity. */ @SuppressWarnings("unused") @Repository public interface FeedbackRepository extends JpaRepository<Feedback, Long>, JpaSpecificationExecutor<Feedback> {}
30.615385
112
0.81407
ea2c9278d6e50ddb4510a1ca425ed9e3a866502d
350
package ru.myx.sql.wrapper; import java.sql.Connection; interface ConnectionInfo { /** @return int */ int connectionMaxLoops(); /** @return long */ long connectionTimeToLive(); /** @return connection */ Connection createConnection(); /** @param poolConnectionHolder */ void reuse(final ConnectionHolder poolConnectionHolder); }
16.666667
57
0.711429
8e39ed6bc626cdfe48912ed23ef92c5c90e706f2
2,756
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands; import edu.wpi.first.wpilibj2.command.CommandBase; import edu.wpi.first.wpilibj.Timer; import frc.robot.subsystems.Drivetrain; import frc.robot.extraClasses.PIDControl; import static frc.robot.Constants.DrivetrainConstants.*; public class AutoTurn extends CommandBase { // Declare class variables double targetAngle; double startTime; double stopTime; double angleError; double angleCorrection; double motorOutput; PIDControl pidControl; private Timer timer = new Timer(); private final Drivetrain drivetrain; /** * Class constructor */ public AutoTurn(Drivetrain drive) { drivetrain = drive; //Use addRequirements() to require any subsystems for the command addRequirements(drivetrain); //Set up PID control pidControl = new PIDControl(kP_Turn, kI_Turn, kD_Turn); } /** * Called when the command is initially scheduled */ @Override public void initialize() { timer.start(); startTime = timer.get(); angleError = 0; angleCorrection = 0; } /** * Called every time the scheduler runs while the command is scheduled */ @Override public void execute() { angleCorrection = pidControl.run(drivetrain.getGyroAngle(), targetAngle); motorOutput = angleCorrection * kAutoTurnSpeed; drivetrain.autoDrive(motorOutput, -motorOutput); } /** * Called once the command ends or is interrupted */ @Override public void end(boolean interrupted) { drivetrain.stopDrive(); } /** * Returns true when the command should end */ @Override public boolean isFinished() { //Declare return flag boolean thereYet = false; //Check elapsed time if(stopTime<=timer.get()-startTime) { //Too much time has elapsed. Stop this command thereYet = true; } else { angleError = drivetrain.getGyroAngle() - targetAngle; if (Math.abs(angleError) <= kTurnAngleTolerance) { thereYet = true; } } //Return the flag return thereYet; } /** * Set the parameters */ public void setParams(double angle, double time){ //Set local variables targetAngle = angle; stopTime = time; } }
19.971014
80
0.605951
72cf4a67a5158e7cc3cf4c57d444e83e8316c708
12,039
/** * Copyright 2011 The PlayN 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 playn.android; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import com.android.vending.expansion.zipfile.APKExpansionSupport; import com.android.vending.expansion.zipfile.ZipResourceFile; import playn.core.AbstractAssets; import playn.core.AsyncImage; import playn.core.Image; import playn.core.Sound; import playn.core.gl.Scale; public class AndroidAssets extends AbstractAssets<Bitmap> { /** Extends {@link BitmapFactory.Options} with PlayN asset scale configuration. */ public class BitmapOptions extends BitmapFactory.Options { /** The asset scale for the resulting image. This will be populated with the appropriate scale * prior to the call to {@link BitmapOptionsAdjuster#adjustOptions} and can be adjusted by the * adjuster if it, for example, adjusts {@link BitmapFactory.Options#inSampleSize} to * downsample the image. */ public Scale scale; } /** See {@link #setBitmapOptionsAdjuster}. */ public interface BitmapOptionsAdjuster { /** Adjusts the {@link BitmapOptions} based on the app's special requirements. * @param path the path passed to {@link #getImage} or URL passed to {@link #getRemoteImage}.*/ void adjustOptions(String path, BitmapOptions options); } private final AndroidPlatform platform; private final AssetManager assetMgr; private String pathPrefix = ""; // 'assets/' is always prepended by AssetManager private Scale assetScale = null; private ZipResourceFile expansionFile = null; private BitmapOptionsAdjuster optionsAdjuster = new BitmapOptionsAdjuster() { public void adjustOptions(String path, BitmapOptions options) {} // noop! }; public AndroidAssets(AndroidPlatform platform) { super(platform); this.platform = platform; this.assetMgr = platform.activity.getResources().getAssets(); } /** * Configures a prefix which is prepended to all asset paths prior to loading. Android assets are * normally loaded via the Android AssetManager, which expects all assets to be in the {@code * assets} directory. This prefix is thus inserted between {@code assets} and the path supplied * to any of the various {@code get} methods. */ public void setPathPrefix(String prefix) { if (prefix.startsWith("/") || prefix.endsWith("/")) { throw new IllegalArgumentException("Prefix must not start or end with '/'."); } pathPrefix = (prefix.length() == 0) ? prefix : (prefix + "/"); } /** * Configures assets to be loaded from existing expansion files. Android supports two expansion * files, a main and patch file. The versions for each are passed to this method. If you are not * using either of the files, supply {@code 0} for the version. Both files will be searched for * resources. * * <p>Expansion resources do not make an assumption that the resources are in a directory named * 'assets' in contrast to the Android resource manager. Use {@link setPathPrefix(String)} to * configure the path within the expansion files.</p> * * <p>Expansion files are expected to be existing and zipped, following the * <a href="http://developer.android.com/google/play/expansion-files.html">Android expansion * file guidelines</a>.</p> * * <p>Due to Android limitations, fonts and typefaces can not be loaded from expansion files. * Fonts should be kept within the default Android assets directory so they may be loaded via the * AssetManager.</p> * * @throws IOException if any expansion files are missing. */ public void setExpansionFile(int mainVersion, int patchVersion) throws IOException { expansionFile = APKExpansionSupport.getAPKExpansionZipFile( platform.activity, mainVersion, patchVersion); if (expansionFile == null) throw new FileNotFoundException("Missing APK expansion zip files"); } /** * Configures the default scale to use for assets. This allows one to use higher resolution * imagery than the device might normally. For example, one can supply scale 2 here, and * configure the graphics scale to 1.25 in order to use iOS Retina graphics (640x960) on a WXGA * (480x800) device. */ public void setAssetScale(float scaleFactor) { this.assetScale = new Scale(scaleFactor); } /** * Configures a class that will adjust the {@link BitmapOptions} used to decode loaded bitmaps. * An app may wish to use different bitmap configs for different images (say {@code RGB_565} for * its non-transparent images) or adjust the dithering settings. */ public void setBitmapOptionsAdjuster(BitmapOptionsAdjuster optionsAdjuster) { this.optionsAdjuster = optionsAdjuster; } @Override public Image getRemoteImage(final String url, float width, float height) { final AndroidAsyncImage image = new AndroidAsyncImage(platform.graphics().ctx, width, height); platform.invokeAsync(new Runnable() { public void run () { try { BitmapOptions options = createOptions(url, false, Scale.ONE); setImageLater(image, downloadBitmap(url, options), options.scale); } catch (Exception error) { setErrorLater(image, error); } } }); return image; } @Override public Sound getSound(String path) { return platform.audio().createSound(path + ".mp3"); } @Override public Sound getMusic(String path) { return platform.audio().createMusic(path + ".mp3"); } @Override public String getTextSync(String path) throws Exception { InputStream is = openAsset(path); try { StringBuilder fileData = new StringBuilder(1000); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); } reader.close(); return fileData.toString(); } finally { is.close(); } } @Override public byte[] getBytesSync(String path) throws Exception { InputStream is = openAsset(path); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; while (true) { int r = is.read(buf); if (r == -1) { break; } out.write(buf, 0, r); } return out.toByteArray(); } finally { is.close(); } } @Override protected Image createStaticImage(Bitmap bitmap, Scale scale) { return new AndroidImage(platform.graphics().ctx, bitmap, scale); } @Override protected AsyncImage<Bitmap> createAsyncImage(float width, float height) { return new AndroidAsyncImage(platform.graphics().ctx, width, height); } @Override protected Image loadImage(String path, ImageReceiver<Bitmap> recv) { Exception error = null; for (Scale.ScaledResource rsrc : assetScale().getScaledResources(path)) { try { InputStream is = openAsset(rsrc.path); try { BitmapOptions options = createOptions(path, true, rsrc.scale); return recv.imageLoaded(BitmapFactory.decodeStream(is, null, options), options.scale); } finally { is.close(); } } catch (FileNotFoundException fnfe) { error = fnfe; // keep going, checking for lower resolution images } catch (Exception e) { error = e; break; // the image was broken not missing, stop here } } platform.log().warn("Could not load image: " + pathPrefix + path, error); return recv.loadFailed(error != null ? error : new FileNotFoundException(path)); } Typeface getTypeface(String path) { return Typeface.createFromAsset(assetMgr, normalizePath(pathPrefix + path)); } protected AssetFileDescriptor openAssetFd(String path) throws IOException { String fullPath = normalizePath(pathPrefix + path); return (expansionFile == null) ? assetMgr.openFd(fullPath) : expansionFile.getAssetFileDescriptor(fullPath); } protected Scale assetScale () { return (assetScale != null) ? assetScale : platform.graphics().ctx.scale; } /** * Attempts to open the asset with the given name, throwing an {@link IOException} in case of * failure. */ protected InputStream openAsset(String path) throws IOException { String fullPath = normalizePath(pathPrefix + path); InputStream is = (expansionFile == null) ? assetMgr.open(fullPath, AssetManager.ACCESS_STREAMING) : expansionFile.getInputStream(fullPath); if (is == null) throw new FileNotFoundException("Missing resource: " + fullPath); return is; } protected BitmapOptions createOptions(String path, boolean purgeable, Scale scale) { BitmapOptions options = new BitmapOptions(); options.inScaled = false; // don't scale bitmaps based on device parameters options.inDither = true; options.inPreferredConfig = platform.graphics().preferredBitmapConfig; options.inPurgeable = purgeable; options.inInputShareable = true; options.scale = scale; // give the game an opportunity to customize the bitmap options based on the image path optionsAdjuster.adjustOptions(path, options); return options; } // Taken from // http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html protected Bitmap downloadBitmap(String url, BitmapOptions options) throws Exception { AndroidHttpClient client = AndroidHttpClient.newInstance("Android"); HttpGet getRequest = new HttpGet(url); try { HttpResponse response = client.execute(getRequest); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { // we could check the status, but we'll just assume that if there's a Location header, // we should follow it Header[] headers = response.getHeaders("Location"); if (headers != null && headers.length > 0) { return downloadBitmap(headers[headers.length-1].getValue(), options); } throw new Exception("Error " + statusCode + " while retrieving bitmap from " + url); } HttpEntity entity = response.getEntity(); if (entity == null) throw new Exception("Error: getEntity returned null for " + url); InputStream inputStream = null; try { inputStream = entity.getContent(); return BitmapFactory.decodeStream(inputStream, null, options); } finally { if (inputStream != null) inputStream.close(); entity.consumeContent(); } } catch (Exception e) { // Could provide a more explicit error message for IOException or IllegalStateException getRequest.abort(); platform.reportError("Error while retrieving bitmap from " + url, e); throw e; } finally { client.close(); } } }
37.504673
99
0.698646
cef1eaee9a4cab89daf933998391b1f3a77943c9
5,404
import java.util.*; /** * Driver Class * * @author Seyda Nur DEMIR */ public class Driver { void driverForBranch () { KWLinkedList <Branch> branches = new KWLinkedList <Branch>(); System.out.println("\n---------------------------------------------------- Branch Class Driver"); branches.addLast((new Branch("Darica","Istasyon Cad, No:14"))); branches.addLast((new Branch("Gebze","Yeni Bagdat Cad, No:75"))); branches.addLast((new Branch("Emek","Fatih Sultan Mehmet Cad, No:9"))); branches.addLast((new Branch("Korfez","Istasyon Cad, No:32"))); branches.addLast((new Branch("Derince","Sahil Cad, No:80"))); branches.addLast((new Branch("Basiskele","Mahmut Cavus Cad, No:13"))); branches.addLast((new Branch("Golcuk","Koca Ahmet Cad, No:21"))); System.out.println("\n---------------------------------- Added Seven Branches to Branches List"); branches.print(); System.out.println("\n-------------------------------------------------- Printed Branches List"); branches.remove(3); System.out.println("\n---------------------------- Removed The Third Branch from Branches List"); branches.removeFirst(); System.out.println("\n---------------------------- Removed The First Branch from Branches List"); branches.removeLast(); System.out.println("\n----------------------------- Removed The Last Branch from Branches List"); branches.print(); System.out.println("\n-------------------------------------------------- Printed Branches List"); } void driverForProduct () { KWArrayList <Product> products = new KWArrayList <Product>(); System.out.println("\n---------------------------------------------------- Product Class Driver"); products.add((new Product("Office Chair","Tulpar","Red"))); products.add((new Product("Office Chair","Tulpar","Black"))); products.add((new Product("Office Chair","Tulpar","White"))); products.add((new Product("Office Desk","Triangle","Brown"))); products.add((new Product("Meeting Table","O Table","Dark Brown"))); products.add((new Product("Book Case","Four Roofs","No Color"))); products.add((new Product("Office Cabinet","Five Doors","No Color"))); System.out.println("\n---------------------------------- Added Seven Products to Products List"); products.print(); System.out.println("\n-------------------------------------------------- Printed Products List"); products.remove(3); System.out.println("\n--------------------------- Removed The Third Product from Products List"); products.remove(0); System.out.println("\n--------------------------- Removed The First Product from Products List"); products.remove(products.size()-1); System.out.println("\n---------------------------- Removed The Last Product from Products List"); products.print(); System.out.println("\n-------------------------------------------------- Printed Products List"); } void driverForOrder () { KWArrayList <Order> orders = new KWArrayList <Order>(); System.out.println("\n----------------------------------------------------- Order Class Driver"); orders.add((new Order((new Administrator((new Branch("Darica","Istasyon Cad, No:14")),"Seyda Nur","DEMIR","[email protected]","12345678","Kocaeli","555 555 55 55")),(new Product("Office Chair","Tulpar","Red"))))); orders.add((new Order((new BranchEmployee((new Branch("Gebze","Yeni Bagdat Cad, No:75")),"Ayse","KOCAK","[email protected]","12345678","Kocaeli","111 111 11 11")),(new Product("Office Chair","Tulpar","Black"))))); orders.add((new Order((new BranchEmployee((new Branch("Emek","Fatih Sultan Mehmet Cad, No:9")),"Fatma","ALTIN","[email protected]","12345678","Kocaeli","222 222 22 22")),(new Product("Office Chair","Tulpar","White"))))); orders.add((new Order((new BranchEmployee((new Branch("Korfez","Istasyon Cad, No:32")),"Ali","KAYA","[email protected]","12345678","Kocaeli","333 333 33 33")),(new Product("Office Desk","Triangle","Brown"))))); orders.add((new Order((new Customer((new Branch("Derince","Sahil Cad, No:80")),"Veli","AKAY","[email protected]","12345678","Kocaeli","333 333 33 33")),(new Product("Meeting Table","O Table","Dark Brown"))))); orders.add((new Order((new Customer((new Branch("Basiskele","Mahmut Cavus Cad, No:13")),"Akif","BAS","[email protected]","12345678","Ankara","222 222 22 22")),(new Product("Book Case","Four Roofs","No Color"))))); orders.add((new Order((new Customer((new Branch("Golcuk","Koca Ahmet Cad, No:21")),"Zeynep","SONMEZ","[email protected]","12345678","Ankara","111 111 11 11")),(new Product("Office Cabinet","Five Doors","No Color"))))); System.out.println("\n-------------------------------------- Added Seven Orders to Orders List"); orders.print(); System.out.println("\n---------------------------------------------------- Printed Orders List"); orders.remove(3); System.out.println("\n------------------------------- Removed The Third Order from Orders List"); orders.remove(0); System.out.println("\n------------------------------- Removed The First Order from Orders List"); orders.remove(orders.size()-1); System.out.println("\n-------------------------------- Removed The Last Order from Orders List"); orders.print(); System.out.println("\n---------------------------------------------------- Printed Orders List"); } void driverForCustomer () { } void driverForBranchEmployee () { } void driverForAdministrator () { } }
63.576471
223
0.584567
a3145233dcb6af4de3ea7a9d10032e13917d0698
242
package com.hy.tuna.xml.elements; public class ResultMapNode extends AbstractNode{ private String type; public String getType() { return type; } public void setType(String type) { this.type = type; } }
16.133333
48
0.640496
eee6ac1edf7000c55c4299bf3d2a3a9d53ad803a
747
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: packimports(3) // Source File Name: DataSourceConnectionImpl.java package com.ibm.tivoli.maximo.report.birt.datasource; import java.sql.Connection; // Referenced classes of package com.ibm.tivoli.maximo.report.birt.datasource: // DataSourceConnection public class DataSourceConnectionImpl implements DataSourceConnection { public DataSourceConnectionImpl(Connection connection) { this.connection = null; this.connection = connection; } public Connection getConnection() { return connection; } private Connection connection; }
24.9
78
0.725569
6121d234102c55fe88d487c73d510d12debe47e7
206
package edu.bator.cards.todo; import edu.bator.cards.Card; public class EmoreCrossbow extends Card { public EmoreCrossbow() { } public EmoreCrossbow(Card cloneFrom) { super(cloneFrom); } }
13.733333
41
0.713592
9675e9793082328fb174e7156ef85e711293d6a9
23,698
/* * Copyright (C) 2014 The Android Open Source 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 libcore.java.nio.channels; import junit.framework.TestCase; import android.system.OsConstants; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InterruptedIOException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; import libcore.io.Libcore; import static libcore.io.IoUtils.closeQuietly; /** * A test for file interrupt behavior. Because forcing a real file to block on read or write is * difficult this test uses Unix FIFO / Named Pipes. FIFOs appear to Java as files but the test * has more control over the available data. Reader will block until the other end writes, and * writers can also be made to block. * * <p>Using FIFOs has a few drawbacks: * <ol> * <li>FIFOs are not supported from Java or the command-line on Android, so this test includes * native code to create the FIFO. * <li>FIFOs will not open() until there is both a reader and a writer of the FIFO; each test must * always attach both ends or experience a blocked test. * <li>FIFOs are not supported on some file systems. e.g. VFAT, so the test has to be particular * about the temporary directory it uses to hold the FIFO. * <li>Writes to FIFOs are buffered by the OS which makes blocking behavior more difficult to * induce. See {@link ChannelWriter} and {@link StreamWriter}. * </ol> */ public class FileIOInterruptTest extends TestCase { private static File VOGAR_DEVICE_TEMP_DIR = new File("/data/data/file_io_interrupt_test"); private File fifoFile; @Override public void setUp() throws Exception { super.setUp(); // This test relies on a FIFO file. The file system must support FIFOs, so we check the path. String tmpDirName = System.getProperty("java.io.tmpdir"); File tmpDir; if (tmpDirName.startsWith("/sdcard")) { // Vogar execution on device runs in /sdcard. Unfortunately the file system used does not // support FIFOs so the test must use one that is more likely to work. if (!VOGAR_DEVICE_TEMP_DIR.exists()) { assertTrue(VOGAR_DEVICE_TEMP_DIR.mkdir()); } VOGAR_DEVICE_TEMP_DIR.deleteOnExit(); tmpDir = VOGAR_DEVICE_TEMP_DIR; } else { tmpDir = new File(tmpDirName); } fifoFile = new File(tmpDir, "fifo_file.tmp"); if (fifoFile.exists()) { fifoFile.delete(); } fifoFile.deleteOnExit(); // Create the fifo. This will throw an exception if the file system does not support it. Libcore.os.mkfifo(fifoFile.getAbsolutePath(), OsConstants.S_IRWXU); } @Override public void tearDown() throws Exception { super.tearDown(); fifoFile.delete(); VOGAR_DEVICE_TEMP_DIR.delete(); // Clear the interrupted state, if set. Thread.interrupted(); } public void testStreamRead_exceptionWhenAlreadyClosed() throws Exception { FifoWriter fifoWriter = new FifoWriter(fifoFile); fifoWriter.start(); FileInputStream fis = new FileInputStream(fifoFile); fis.close(); byte[] buffer = new byte[10]; try { fis.read(buffer); fail(); } catch (IOException expected) { assertSame(IOException.class, expected.getClass()); } fifoWriter.tidyUp(); } // This test fails on the RI: close() does not wake up a blocking FileInputStream.read() call. public void testStreamRead_exceptionOnCloseWhenBlocked() throws Exception { FifoWriter fifoWriter = new FifoWriter(fifoFile); fifoWriter.start(); FileInputStream fis = new FileInputStream(fifoFile); StreamReader streamReader = new StreamReader(fis); Thread streamReaderThread = createAndStartThread("StreamReader", streamReader); // Delay until we can be fairly sure the reader thread is blocking. streamReader.waitForThreadToBlock(); // Now close the OutputStream to see what happens. fis.close(); // Test for expected behavior in the reader thread. waitToDie(streamReaderThread); assertSame(InterruptedIOException.class, streamReader.ioe.getClass()); assertFalse(streamReader.wasInterrupted); // Tidy up the writer thread. fifoWriter.tidyUp(); } public void testStreamWrite_exceptionWhenAlreadyClosed() throws Exception { FifoReader fifoReader = new FifoReader(fifoFile); fifoReader.start(); FileOutputStream fos = new FileOutputStream(fifoFile); byte[] buffer = new byte[10]; fos.close(); try { fos.write(buffer); fail(); } catch (IOException expected) { assertSame(IOException.class, expected.getClass()); } fifoReader.tidyUp(); } // This test fails on the RI: close() does not wake up a blocking FileInputStream.write() call. public void testStreamWrite_exceptionOnCloseWhenBlocked() throws Exception { FifoReader fifoReader = new FifoReader(fifoFile); fifoReader.start(); FileOutputStream fos = new FileOutputStream(fifoFile); StreamWriter streamWriter = new StreamWriter(fos); Thread streamWriterThread = createAndStartThread("StreamWriter", streamWriter); // Delay until we can be fairly sure the writer thread is blocking. streamWriter.waitForThreadToBlock(); // Now close the OutputStream to see what happens. fos.close(); // Test for expected behavior in the writer thread. waitToDie(streamWriterThread); assertSame(InterruptedIOException.class, streamWriter.ioe.getClass()); assertFalse(streamWriter.wasInterrupted); // Tidy up the reader thread. fifoReader.tidyUp(); } public void testChannelRead_exceptionWhenAlreadyClosed() throws Exception { testChannelRead_exceptionWhenAlreadyClosed(ChannelReader.Method.READ); } public void testChannelReadV_exceptionWhenAlreadyClosed() throws Exception { testChannelRead_exceptionWhenAlreadyClosed(ChannelReader.Method.READV); } private void testChannelRead_exceptionWhenAlreadyClosed(ChannelReader.Method method) throws Exception { FifoWriter fifoWriter = new FifoWriter(fifoFile); fifoWriter.start(); FileInputStream fis = new FileInputStream(fifoFile); FileChannel fileInputChannel = fis.getChannel(); fileInputChannel.close(); ByteBuffer buffer = ByteBuffer.allocateDirect(10); try { if (method == ChannelReader.Method.READ) { fileInputChannel.read(buffer); } else { ByteBuffer buffer2 = ByteBuffer.allocateDirect(10); fileInputChannel.read(new ByteBuffer[] { buffer, buffer2}); } fail(); } catch (IOException expected) { assertSame(ClosedChannelException.class, expected.getClass()); } fifoWriter.tidyUp(); } public void testChannelRead_exceptionWhenAlreadyInterrupted() throws Exception { testChannelRead_exceptionWhenAlreadyInterrupted(ChannelReader.Method.READ); } public void testChannelReadV_exceptionWhenAlreadyInterrupted() throws Exception { testChannelRead_exceptionWhenAlreadyInterrupted(ChannelReader.Method.READV); } private void testChannelRead_exceptionWhenAlreadyInterrupted(ChannelReader.Method method) throws Exception { FifoWriter fifoWriter = new FifoWriter(fifoFile); fifoWriter.start(); FileInputStream fis = new FileInputStream(fifoFile); FileChannel fileInputChannel = fis.getChannel(); Thread.currentThread().interrupt(); ByteBuffer buffer = ByteBuffer.allocateDirect(10); try { if (method == ChannelReader.Method.READ) { fileInputChannel.read(buffer); } else { ByteBuffer buffer2 = ByteBuffer.allocateDirect(10); fileInputChannel.read(new ByteBuffer[] { buffer, buffer2}); } fail(); } catch (IOException expected) { assertSame(ClosedByInterruptException.class, expected.getClass()); } // Check but also clear the interrupted status, so we can wait for the FifoWriter thread in // tidyUp(). assertTrue(Thread.interrupted()); fifoWriter.tidyUp(); } public void testChannelRead_exceptionOnCloseWhenBlocked() throws Exception { testChannelRead_exceptionOnCloseWhenBlocked(ChannelReader.Method.READ); } public void testChannelReadV_exceptionOnCloseWhenBlocked() throws Exception { testChannelRead_exceptionOnCloseWhenBlocked(ChannelReader.Method.READV); } private void testChannelRead_exceptionOnCloseWhenBlocked(ChannelReader.Method method) throws Exception { FifoWriter fifoWriter = new FifoWriter(fifoFile); fifoWriter.start(); FileInputStream fis = new FileInputStream(fifoFile); FileChannel fileInputChannel = fis.getChannel(); ChannelReader channelReader = new ChannelReader(fileInputChannel, method); Thread channelReaderThread = createAndStartThread("ChannelReader", channelReader); // Delay until we can be fairly sure the reader thread is blocking. channelReader.waitForThreadToBlock(); // Now close the FileChannel to see what happens. fileInputChannel.close(); // Test for expected behavior in the reader thread. waitToDie(channelReaderThread); assertSame(AsynchronousCloseException.class, channelReader.ioe.getClass()); assertFalse(channelReader.wasInterrupted); // Tidy up the writer thread. fifoWriter.tidyUp(); } public void testChannelRead_exceptionOnInterrupt() throws Exception { testChannelRead_exceptionOnInterrupt(ChannelReader.Method.READ); } public void testChannelReadV_exceptionOnInterrupt() throws Exception { testChannelRead_exceptionOnInterrupt(ChannelReader.Method.READV); } private void testChannelRead_exceptionOnInterrupt(ChannelReader.Method method) throws Exception { FifoWriter fifoWriter = new FifoWriter(fifoFile); fifoWriter.start(); FileChannel fileChannel = new FileInputStream(fifoFile).getChannel(); ChannelReader channelReader = new ChannelReader(fileChannel, method); Thread channelReaderThread = createAndStartThread("ChannelReader", channelReader); // Delay until we can be fairly sure the reader thread is blocking. channelReader.waitForThreadToBlock(); // Now interrupt the reader thread to see what happens. channelReaderThread.interrupt(); // Test for expected behavior in the reader thread. waitToDie(channelReaderThread); assertSame(ClosedByInterruptException.class, channelReader.ioe.getClass()); assertTrue(channelReader.wasInterrupted); // Tidy up the writer thread. fifoWriter.tidyUp(); } public void testChannelWrite_exceptionWhenAlreadyClosed() throws Exception { testChannelWrite_exceptionWhenAlreadyClosed(ChannelWriter.Method.WRITE); } public void testChannelWriteV_exceptionWhenAlreadyClosed() throws Exception { testChannelWrite_exceptionWhenAlreadyClosed(ChannelWriter.Method.WRITEV); } private void testChannelWrite_exceptionWhenAlreadyClosed(ChannelWriter.Method method) throws Exception { FifoReader fifoReader = new FifoReader(fifoFile); fifoReader.start(); FileChannel fileOutputChannel = new FileOutputStream(fifoFile).getChannel(); fileOutputChannel.close(); ByteBuffer buffer = ByteBuffer.allocateDirect(10); try { if (method == ChannelWriter.Method.WRITE) { fileOutputChannel.write(buffer); } else { ByteBuffer buffer2 = ByteBuffer.allocateDirect(10); fileOutputChannel.write(new ByteBuffer[] { buffer, buffer2 }); } fail(); } catch (IOException expected) { assertSame(ClosedChannelException.class, expected.getClass()); } fifoReader.tidyUp(); } public void testChannelWrite_exceptionWhenAlreadyInterrupted() throws Exception { testChannelWrite_exceptionWhenAlreadyInterrupted(ChannelWriter.Method.WRITE); } public void testChannelWriteV_exceptionWhenAlreadyInterrupted() throws Exception { testChannelWrite_exceptionWhenAlreadyInterrupted(ChannelWriter.Method.WRITEV); } private void testChannelWrite_exceptionWhenAlreadyInterrupted(ChannelWriter.Method method) throws Exception { FifoReader fifoReader = new FifoReader(fifoFile); fifoReader.start(); FileOutputStream fos = new FileOutputStream(fifoFile); FileChannel fileInputChannel = fos.getChannel(); Thread.currentThread().interrupt(); ByteBuffer buffer = ByteBuffer.allocateDirect(10); try { if (method == ChannelWriter.Method.WRITE) { fileInputChannel.write(buffer); } else { ByteBuffer buffer2 = ByteBuffer.allocateDirect(10); fileInputChannel.write(new ByteBuffer[] { buffer, buffer2 }); } fail(); } catch (IOException expected) { assertSame(ClosedByInterruptException.class, expected.getClass()); } // Check but also clear the interrupted status, so we can wait for the FifoReader thread in // tidyUp(). assertTrue(Thread.interrupted()); fifoReader.tidyUp(); } public void testChannelWrite_exceptionOnCloseWhenBlocked() throws Exception { testChannelWrite_exceptionOnCloseWhenBlocked(ChannelWriter.Method.WRITE); } public void testChannelWriteV_exceptionOnCloseWhenBlocked() throws Exception { testChannelWrite_exceptionOnCloseWhenBlocked(ChannelWriter.Method.WRITEV); } private void testChannelWrite_exceptionOnCloseWhenBlocked(ChannelWriter.Method method) throws Exception { FifoReader fifoReader = new FifoReader(fifoFile); fifoReader.start(); FileChannel fileOutputChannel = new FileOutputStream(fifoFile).getChannel(); ChannelWriter channelWriter = new ChannelWriter(fileOutputChannel, method); Thread channelWriterThread = createAndStartThread("ChannelWriter", channelWriter); // Delay until we can be fairly sure the writer thread is blocking. channelWriter.waitForThreadToBlock(); // Now close the channel to see what happens. fileOutputChannel.close(); // Test for expected behavior in the writer thread. waitToDie(channelWriterThread); // // The RI throws ChannelClosedException. AsynchronousCloseException is more correct according to // // the docs. // // Lies. RI throws AsynchronousCloseException only if NO data was written before interrupt. // I altered the ChannelWriter to write exactly 32k bytes and this triggers this behavior. // the AsynchronousCloseException. If some of data is written, the #write will return the number // of bytes written, and then the FOLLOWING #write will throw ChannelClosedException because // file has been closed. Android is actually doing a wrong thing by always throwing the // AsynchronousCloseException. Client application have no idea that SOME data // was written in this case. assertSame(AsynchronousCloseException.class, channelWriter.ioe.getClass()); assertFalse(channelWriter.wasInterrupted); // Tidy up the writer thread. fifoReader.tidyUp(); } public void testChannelWrite_exceptionOnInterrupt() throws Exception { testChannelWrite_exceptionOnInterrupt(ChannelWriter.Method.WRITE); } public void testChannelWriteV_exceptionOnInterrupt() throws Exception { testChannelWrite_exceptionOnInterrupt(ChannelWriter.Method.WRITEV); } private void testChannelWrite_exceptionOnInterrupt(ChannelWriter.Method method) throws Exception { FifoReader fifoReader = new FifoReader(fifoFile); fifoReader.start(); FileChannel fileChannel = new FileOutputStream(fifoFile).getChannel(); ChannelWriter channelWriter = new ChannelWriter(fileChannel, method); Thread channelWriterThread = createAndStartThread("ChannelWriter", channelWriter); // Delay until we can be fairly sure the writer thread is blocking. channelWriter.waitForThreadToBlock(); // Now interrupt the writer thread to see what happens. channelWriterThread.interrupt(); // Test for expected behavior in the writer thread. waitToDie(channelWriterThread); assertSame(ClosedByInterruptException.class, channelWriter.ioe.getClass()); assertTrue(channelWriter.wasInterrupted); // Tidy up the reader thread. fifoReader.tidyUp(); } private static class StreamReader implements Runnable { private final FileInputStream inputStream; volatile boolean started; volatile IOException ioe; volatile boolean wasInterrupted; StreamReader(FileInputStream inputStream) { this.inputStream = inputStream; } @Override public void run() { byte[] buffer = new byte[10]; try { started = true; int bytesRead = inputStream.read(buffer); fail("This isn't supposed to happen: read() returned: " + bytesRead); } catch (IOException e) { this.ioe = e; } wasInterrupted = Thread.interrupted(); } public void waitForThreadToBlock() { for (int i = 0; i < 10 && !started; i++) { delay(100); } assertTrue(started); // Just give it some more time to start blocking. delay(100); } } private static class StreamWriter implements Runnable { private final FileOutputStream outputStream; volatile int bytesWritten; volatile IOException ioe; volatile boolean wasInterrupted; StreamWriter(FileOutputStream outputStream) { this.outputStream = outputStream; } @Override public void run() { // Writes to FIFOs are buffered. We try to fill the buffer and induce blocking (the // buffer is typically 64k). byte[] buffer = new byte[10000]; while (true) { try { outputStream.write(buffer); bytesWritten += buffer.length; } catch (IOException e) { this.ioe = e; break; } wasInterrupted = Thread.interrupted(); } } public void waitForThreadToBlock() { int lastCount = bytesWritten; for (int i = 0; i < 10; i++) { delay(500); int newBytesWritten = bytesWritten; if (newBytesWritten > 0 && lastCount == newBytesWritten) { // The thread is probably blocking. return; } lastCount = bytesWritten; } fail("Writer never started blocking. Bytes written: " + bytesWritten); } } private static class ChannelReader implements Runnable { enum Method { READ, READV, } private final FileChannel channel; private final Method method; volatile boolean started; volatile IOException ioe; volatile boolean wasInterrupted; ChannelReader(FileChannel channel, Method method) { this.channel = channel; this.method = method; } @Override public void run() { ByteBuffer buffer = ByteBuffer.allocateDirect(10); try { started = true; if (method == Method.READ) { channel.read(buffer); } else { ByteBuffer buffer2 = ByteBuffer.allocateDirect(10); channel.read(new ByteBuffer[] { buffer, buffer2 }); } fail("All tests should block until an exception"); } catch (IOException e) { this.ioe = e; } wasInterrupted = Thread.interrupted(); } public void waitForThreadToBlock() { for (int i = 0; i < 10 && !started; i++) { delay(100); } assertTrue(started); // Just give it some more time to start blocking. delay(100); } } private static class ChannelWriter implements Runnable { enum Method { WRITE, WRITEV, } private final FileChannel channel; private final Method method; volatile int bytesWritten; volatile IOException ioe; volatile boolean wasInterrupted; ChannelWriter(FileChannel channel, Method method) { this.channel = channel; this.method = method; } @Override public void run() { ByteBuffer buffer1 = ByteBuffer.allocateDirect(32000); ByteBuffer buffer2 = ByteBuffer.allocateDirect(32000); // Writes to FIFOs are buffered. We try to fill the buffer and induce blocking (the // buffer is typically 64k). while (true) { // Make the buffers look non-empty. buffer1.position(0).limit(buffer1.capacity()); buffer2.position(0).limit(buffer2.capacity()); try { if (method == Method.WRITE) { bytesWritten += channel.write(buffer1); } else { bytesWritten += channel.write(new ByteBuffer[]{ buffer1, buffer2 }); } } catch (IOException e) { this.ioe = e; break; } } wasInterrupted = Thread.interrupted(); } public void waitForThreadToBlock() { int lastCount = bytesWritten; for (int i = 0; i < 10; i++) { delay(500); int newBytesWritten = bytesWritten; if (newBytesWritten > 0 && lastCount == newBytesWritten) { // The thread is probably blocking. return; } lastCount = bytesWritten; } fail("Writer never started blocking. Bytes written: " + bytesWritten); } } /** * Opens a FIFO for writing. Exists to unblock the other end of the FIFO. */ private static class FifoWriter extends Thread { private final File file; private FileOutputStream fos; public FifoWriter(File file) { super("FifoWriter"); this.file = file; } @Override public void run() { try { fos = new FileOutputStream(file); } catch (IOException ignored) { } } public void tidyUp() { FileIOInterruptTest.waitToDie(this); closeQuietly(fos); } } /** * Opens a FIFO for reading. Exists to unblock the other end of the FIFO. */ private static class FifoReader extends Thread { private final File file; private FileInputStream fis; public FifoReader(File file) { super("FifoReader"); this.file = file; } @Override public void run() { try { fis = new FileInputStream(file); } catch (IOException ignored) { } } public void tidyUp() { FileIOInterruptTest.waitToDie(this); closeQuietly(fis); } } private static Thread createAndStartThread(String name, Runnable runnable) { Thread t = new Thread(runnable, name); t.setDaemon(true); t.start(); return t; } private static void waitToDie(Thread thread) { // Protect against this thread already being interrupted, which would prevent the test waiting // for the requested time. assertFalse(Thread.currentThread().isInterrupted()); try { thread.join(5000); } catch (InterruptedException ignored) { } if (thread.isAlive()) { fail("Thread \"" + thread.getName() + "\" did not exit."); } } private static void delay(int millis) { // Protect against this thread being interrupted, which would prevent us waiting. assertFalse(Thread.currentThread().isInterrupted()); try { Thread.sleep(millis); } catch (InterruptedException ignored) { } } }
33.005571
103
0.70449
a48423d090103fa5b4288e369657428625c01b3d
4,641
package bt.runtime.evnt; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import bt.types.number.MutableInt; import bt.utils.Null; /** * A basic data dispatcher for generic dispatching of i.e. events to listeners. * * @author &#8904 * */ public class Dispatcher { /** A map of class (type of the data that is dispatched) to SubDispatcher. */ private Map<Class, SubDispatcher> subDispatchers; /** * Creates a new instance. */ public Dispatcher() { this.subDispatchers = new ConcurrentHashMap<>(); } /** * Subscribes the given consumer implementation to the given data type. * * <p> * If the given data type is {@link #dispatch}ed by this instance, all consumers that are subscribed to the given * type are executed and the dispatched data is passed. * </p> * * @param type * @param listener */ public <T> void subscribeTo(Class<T> type, Consumer<T> consumer) { if (!this.subDispatchers.containsKey(type)) { this.subDispatchers.put(type, new SubDispatcher<>(type)); } var dispatcher = (SubDispatcher<T>)this.subDispatchers.get(type); dispatcher.subscribe(consumer); } /** * Unsubscribes the given comsumer from receiving data of the given type. * * @param type * @param listener * * @return true if the given consumer was subscribed. */ public <T> boolean unsubscribeFrom(Class<T> type, Consumer<T> consumer) { if (!this.subDispatchers.containsKey(type)) { return false; } var dispatcher = (SubDispatcher<T>)this.subDispatchers.get(type); return dispatcher.unsubscribe(consumer); } /** * Subscribes the given runnable implementation to the given data type. * * <p> * If the given data type is {@link #dispatch}ed by this instance, all subscribers of the given type are executed * and the dispatched data is passed. * </p> * * @param type * @param listener */ public <T> void subscribeTo(Class<T> type, Runnable runnable) { if (!this.subDispatchers.containsKey(type)) { this.subDispatchers.put(type, new SubDispatcher<>(type)); } var dispatcher = (SubDispatcher<T>)this.subDispatchers.get(type); dispatcher.subscribe(runnable); } /** * Unsubscribes the given runnable from receiving data of the given type. * * @param type * @param listener * * @return true if the given runnable was subscribed. */ public <T> boolean unsubscribeFrom(Class<T> type, Runnable runnable) { if (!this.subDispatchers.containsKey(type)) { return false; } var dispatcher = (SubDispatcher<T>)this.subDispatchers.get(type); return dispatcher.unsubscribe(runnable); } /** * Dispatches the given data to all instances that are subscribed to that specific data type or any of its super * types. * * @param data * @return The number of subscribers that received the data. */ public <T> int dispatch(T data) { MutableInt dispatchCount = new MutableInt(0); this.subDispatchers.values() .stream() .filter(d -> d.getType().isInstance(data)) .forEach(d -> dispatchCount.add(d.dispatch(data))); return dispatchCount.get(); } /** * Gets a list containing all subscribers of this instance that are subscribed to the given data type. * * <p> * All elements in the list will be {@link Consumer}s. Any {@link Runnable} subscriber will be wrapped in a new * Consumer. * </p> * * @return The list of subscribers. */ public <T> List<Consumer<T>> getSubscribers(Class<T> type) { if (!this.subDispatchers.containsKey(type)) { return new ArrayList<>(); } var dispatcher = (SubDispatcher<T>)this.subDispatchers.get(type); return dispatcher.getSubscribers(); } /** * Creals all subscribers to the given type. * * @param <T> * @param type */ public <T> void clear(Class<T> type) { var subDispatcher = this.subDispatchers.get(type); Null.checkRun(subDispatcher, subDispatcher::clear); } }
27.957831
117
0.59707
5c68ba95ba391c15cf13448bf1c06a48f52ddf02
1,109
package prot3ct.workit.views.edit_profile; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import prot3ct.workit.R; import prot3ct.workit.views.edit_profile.base.EditProfileContract; public class EditProfileActivity extends AppCompatActivity { private EditProfileContract.Presenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_profile); EditProfileFragment editProfileFragment = (EditProfileFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container); if (editProfileFragment == null) { editProfileFragment = EditProfileFragment.newInstance(); getSupportFragmentManager() .beginTransaction() .add(R.id.fragment_container, editProfileFragment) .commit(); } this.presenter = new EditProfilePresenter(editProfileFragment, this); editProfileFragment.setPresenter(this.presenter); } }
34.65625
108
0.711452
a30c96b22055cf1f4e7d1eb2e146853eafe9b7e5
1,161
package interpreter.bytecode; import interpreter.VirtualMachine; import java.util.List; /** Used prior to calling a function. This instruction is immediately followed by the CALL instruction; the function has n args so ARGS n instructs the interpreter to set up a new frame n down from the top of the runtime stack.This will include the arguments in the new frame for the function. E.G ARGS 4 ARGS 0 ARGS 2 */ public class ArgsCode extends ByteCode{ //Variable stores number of arguments will pass into function private int numberOfArgs; @Override public void init(List<String> args) { //Sets the number of arguments needed for calling function numberOfArgs=Integer.parseInt(args.get(1)); } @Override public void execute(VirtualMachine vm) { //Stores addresses to return to after called function is finished executing vm.pushReturnAddress(); //Creates new frame using number of args as perimeter vm.newFrameAt(numberOfArgs); } /** * For Dumping * @return */ @Override public String toString() { return "ARGS "+numberOfArgs; } }
27
108
0.695952
434d5bbf32fdefadd675ccce48e452677a310081
11,882
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.hotspot.management; import org.graalvm.compiler.phases.common.jmx.HotSpotMBeanOperationProvider; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.ObjectName; import javax.management.ReflectionException; import jdk.internal.vm.compiler.collections.EconomicMap; import org.graalvm.compiler.core.common.SuppressFBWarnings; import org.graalvm.compiler.debug.TTY; import org.graalvm.compiler.hotspot.HotSpotGraalRuntime; import org.graalvm.compiler.options.OptionDescriptor; import org.graalvm.compiler.options.OptionDescriptors; import org.graalvm.compiler.options.OptionsParser; import org.graalvm.compiler.serviceprovider.GraalServices; import jdk.vm.ci.services.Services; /** * MBean used to access properties and operations of a {@link HotSpotGraalRuntime} instance. */ final class HotSpotGraalRuntimeMBean implements DynamicMBean { /** * The runtime instance to which this bean provides a management connection. */ private final HotSpotGraalRuntime runtime; /** * The object name under which the bean is registered. */ private final ObjectName objectName; HotSpotGraalRuntimeMBean(ObjectName objectName, HotSpotGraalRuntime runtime) { this.objectName = objectName; this.runtime = runtime; } ObjectName getObjectName() { return objectName; } HotSpotGraalRuntime getRuntime() { return runtime; } private static final boolean DEBUG = initDebug(); private static boolean initDebug() { try { return Boolean.parseBoolean(Services.getSavedProperties().get(HotSpotGraalRuntimeMBean.class.getSimpleName() + ".debug")); } catch (SecurityException e) { // Swallow the exception return false; } } @Override public Object getAttribute(String name) throws AttributeNotFoundException { String[] result = runtime.getOptionValues(name); String value = result[0]; if (value == null) { throw new AttributeNotFoundException(name); } if (DEBUG) { System.out.printf("getAttribute: %s = %s (type: %s)%n", name, value, value == null ? "null" : value.getClass().getName()); } return result[0]; } @SuppressFBWarnings(value = "ES_COMPARING_STRINGS_WITH_EQ", justification = "reference equality on the receiver is what we want") @Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException { String name = attribute.getName(); Object value = attribute.getValue(); String svalue = String.valueOf(value); if (DEBUG) { System.out.printf("setAttribute: %s = %s (type: %s)%n", name, svalue, value == null ? "null" : value.getClass().getName()); } String[] result = runtime.setOptionValues(new String[]{name}, new String[]{svalue}); if (result[0] != name) { if (result[0] == null) { throw new AttributeNotFoundException(name); } throw new InvalidAttributeValueException(result[0]); } } @Override public AttributeList getAttributes(String[] names) { String[] values = runtime.getOptionValues(names); AttributeList list = new AttributeList(); for (int i = 0; i < names.length; i++) { String value = values[i]; String name = names[i]; if (value == null) { TTY.printf("No such option named %s%n", name); } else { if (DEBUG) { System.out.printf("getAttributes: %s = %s (type: %s)%n", name, value, value == null ? "null" : value.getClass().getName()); } list.add(new Attribute(name, value)); } } return list; } @SuppressFBWarnings(value = "ES_COMPARING_STRINGS_WITH_EQ", justification = "reference equality on the receiver is what we want") @Override public AttributeList setAttributes(AttributeList attributes) { String[] names = new String[attributes.size()]; String[] values = new String[attributes.size()]; int i = 0; for (Attribute attr : attributes.asList()) { String name = attr.getName(); names[i] = name; Object value = attr.getValue(); String svalue = String.valueOf(value); values[i] = svalue; if (DEBUG) { System.out.printf("setAttributes: %s = %s (type: %s)%n", name, svalue, value == null ? "null" : value.getClass().getName()); } i++; } String[] result = runtime.setOptionValues(names, values); AttributeList setOk = new AttributeList(); i = 0; for (Attribute attr : attributes.asList()) { if (names[i] == result[i]) { setOk.add(attr); } else if (result[i] == null) { TTY.printf("Error setting %s to %s: unknown option%n", attr.getName(), attr.getValue()); } else { TTY.printf("Error setting %s to %s: %s%n", attr.getName(), attr.getValue(), result[i]); } i++; } return setOk; } @Override public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException { try { if (DEBUG) { System.out.printf("invoke: %s%s%n", actionName, Arrays.asList(params)); } Object retvalue = null; if ("dumpMethod".equals(actionName)) { retvalue = runtime.invokeManagementAction(actionName, params); } else { boolean found = false; for (HotSpotMBeanOperationProvider p : GraalServices.load(HotSpotMBeanOperationProvider.class)) { List<MBeanOperationInfo> info = new ArrayList<>(); p.registerOperations(MBeanOperationInfo.class, info); for (MBeanOperationInfo op : info) { if (actionName.equals(op.getName())) { retvalue = p.invoke(actionName, params, signature); found = true; break; } } } if (!found) { throw new MBeanException(new IllegalStateException("Cannot find operation " + actionName)); } } if (DEBUG) { System.out.printf("invoke: %s%s = %s%n", actionName, Arrays.asList(params), retvalue); } return retvalue; } catch (MBeanException ex) { throw ex; } catch (Exception ex) { throw new ReflectionException(ex); } } @Override public MBeanInfo getMBeanInfo() { List<MBeanAttributeInfo> attrs = new ArrayList<>(); for (OptionDescriptor option : getOptionDescriptors().getValues()) { Class<?> optionValueType = option.getOptionValueType(); if (Enum.class.isAssignableFrom(optionValueType)) { // Enum values are passed through // the management interface as Strings. optionValueType = String.class; } attrs.add(new MBeanAttributeInfo(option.getName(), optionValueType.getName(), option.getHelp(), true, true, false)); } attrs.sort(new Comparator<MBeanAttributeInfo>() { @Override public int compare(MBeanAttributeInfo o1, MBeanAttributeInfo o2) { return o1.getName().compareTo(o2.getName()); } }); List<MBeanOperationInfo> opts = new ArrayList<>(); opts.add(new MBeanOperationInfo("dumpMethod", "Enable IGV dumps for provided method", new MBeanParameterInfo[]{ new MBeanParameterInfo("className", "java.lang.String", "Class to observe"), new MBeanParameterInfo("methodName", "java.lang.String", "Method to observe"), }, "void", MBeanOperationInfo.ACTION)); opts.add(new MBeanOperationInfo("dumpMethod", "Enable IGV dumps for provided method", new MBeanParameterInfo[]{ new MBeanParameterInfo("className", "java.lang.String", "Class to observe"), new MBeanParameterInfo("methodName", "java.lang.String", "Method to observe"), new MBeanParameterInfo("filter", "java.lang.String", "The parameter for Dump option"), }, "void", MBeanOperationInfo.ACTION)); opts.add(new MBeanOperationInfo("dumpMethod", "Enable IGV dumps for provided method", new MBeanParameterInfo[]{ new MBeanParameterInfo("className", "java.lang.String", "Class to observe"), new MBeanParameterInfo("methodName", "java.lang.String", "Method to observe"), new MBeanParameterInfo("filter", "java.lang.String", "The parameter for Dump option"), new MBeanParameterInfo("host", "java.lang.String", "The host where the IGV tool is running at"), new MBeanParameterInfo("port", "int", "The port where the IGV tool is listening at"), }, "void", MBeanOperationInfo.ACTION)); for (HotSpotMBeanOperationProvider p : GraalServices.load(HotSpotMBeanOperationProvider.class)) { p.registerOperations(MBeanOperationInfo.class, opts); } return new MBeanInfo( HotSpotGraalRuntimeMBean.class.getName(), "Graal", attrs.toArray(new MBeanAttributeInfo[attrs.size()]), null, opts.toArray(new MBeanOperationInfo[opts.size()]), null); } private static EconomicMap<String, OptionDescriptor> getOptionDescriptors() { EconomicMap<String, OptionDescriptor> result = EconomicMap.create(); for (OptionDescriptors set : OptionsParser.getOptionsLoader()) { for (OptionDescriptor option : set) { result.put(option.getName(), option); } } return result; } }
43.050725
143
0.61833
d766dc90e518fb16f40d52633defcd90789efe3a
253
package com.revature.dao; import java.sql.SQLException; import com.revature.project0.Customer; public interface CustomerDao { public void regNewCustomer(Customer c) throws SQLException; public Customer retrieveById(int id) throws SQLException; }
21.083333
60
0.810277
322667cccaa0a581f2bd7830bf771334203f90f0
2,347
package com.herle.hibernate; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "stock") public class Stock implements java.io.Serializable { @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "STOCK_ID", unique = true, nullable = false) private Integer stockId; @Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10) private String stockCode; @Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20) private String stockName; public Stock() { } public Stock(String stockCode, String stockName) { this.stockCode = stockCode; this.stockName = stockName; } public Integer getStockId() { return this.stockId; } public void setStockId(Integer stockId) { this.stockId = stockId; } public String getStockCode() { return this.stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; } public String getStockName() { return this.stockName; } public void setStockName(String stockName) { this.stockName = stockName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((stockCode == null) ? 0 : stockCode.hashCode()); result = prime * result + ((stockId == null) ? 0 : stockId.hashCode()); result = prime * result + ((stockName == null) ? 0 : stockName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Stock other = (Stock) obj; if (stockCode == null) { if (other.stockCode != null) return false; } else if (!stockCode.equals(other.stockCode)) return false; if (stockId == null) { if (other.stockId != null) return false; } else if (!stockId.equals(other.stockId)) return false; if (stockName == null) { if (other.stockName != null) return false; } else if (!stockName.equals(other.stockName)) return false; return true; } @Override public String toString() { return "Stock [stockId=" + stockId + ", stockCode=" + stockCode + ", stockName=" + stockName + "]"; } }
23.707071
101
0.684704
b308b982aefdadc9e9d23ad60a58fab67fc5d8ee
20,645
package org.apache.helix.api.accessor; /* * 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. */ import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.helix.HelixConstants.StateModelToken; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixDefinedState; import org.apache.helix.PropertyKey; import org.apache.helix.api.Resource; import org.apache.helix.api.Scope; import org.apache.helix.api.State; import org.apache.helix.api.config.ResourceConfig; import org.apache.helix.api.config.ResourceConfig.ResourceType; import org.apache.helix.api.config.UserConfig; import org.apache.helix.api.id.ParticipantId; import org.apache.helix.api.id.PartitionId; import org.apache.helix.api.id.ResourceId; import org.apache.helix.controller.rebalancer.config.BasicRebalancerConfig; import org.apache.helix.controller.rebalancer.config.CustomRebalancerConfig; import org.apache.helix.controller.rebalancer.config.PartitionedRebalancerConfig; import org.apache.helix.controller.rebalancer.config.RebalancerConfig; import org.apache.helix.controller.rebalancer.config.RebalancerConfigHolder; import org.apache.helix.controller.rebalancer.config.SemiAutoRebalancerConfig; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.IdealState.RebalanceMode; import org.apache.helix.model.InstanceConfig; import org.apache.helix.model.ResourceAssignment; import org.apache.helix.model.ResourceConfiguration; import org.apache.helix.model.StateModelDefinition; import org.apache.log4j.Logger; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class ResourceAccessor { private static final Logger LOG = Logger.getLogger(ResourceAccessor.class); private final HelixDataAccessor _accessor; private final PropertyKey.Builder _keyBuilder; public ResourceAccessor(HelixDataAccessor accessor) { _accessor = accessor; _keyBuilder = accessor.keyBuilder(); } /** * Read a single snapshot of a resource * @param resourceId the resource id to read * @return Resource or null if not present */ public Resource readResource(ResourceId resourceId) { ResourceConfiguration config = _accessor.getProperty(_keyBuilder.resourceConfig(resourceId.stringify())); IdealState idealState = _accessor.getProperty(_keyBuilder.idealStates(resourceId.stringify())); if (config == null && idealState == null) { LOG.error("Resource " + resourceId + " not present on the cluster"); return null; } ExternalView externalView = _accessor.getProperty(_keyBuilder.externalView(resourceId.stringify())); ResourceAssignment resourceAssignment = _accessor.getProperty(_keyBuilder.resourceAssignment(resourceId.stringify())); return createResource(resourceId, config, idealState, externalView, resourceAssignment); } /** * Update a resource configuration * @param resourceId the resource id to update * @param resourceDelta changes to the resource * @return ResourceConfig, or null if the resource is not persisted */ public ResourceConfig updateResource(ResourceId resourceId, ResourceConfig.Delta resourceDelta) { Resource resource = readResource(resourceId); if (resource == null) { LOG.error("Resource " + resourceId + " does not exist, cannot be updated"); return null; } ResourceConfig config = resourceDelta.mergeInto(resource.getConfig()); setResource(config); return config; } /** * save resource assignment * @param resourceId * @param resourceAssignment * @return true if set, false otherwise */ public boolean setResourceAssignment(ResourceId resourceId, ResourceAssignment resourceAssignment) { return _accessor.setProperty(_keyBuilder.resourceAssignment(resourceId.stringify()), resourceAssignment); } /** * get resource assignment * @param resourceId * @return resource assignment or null */ public ResourceAssignment getResourceAssignment(ResourceId resourceId) { return _accessor.getProperty(_keyBuilder.resourceAssignment(resourceId.stringify())); } /** * Set a physical resource configuration, which may include user-defined configuration, as well as * rebalancer configuration * @param resourceId * @param configuration * @return true if set, false otherwise */ private boolean setConfiguration(ResourceId resourceId, ResourceConfiguration configuration, RebalancerConfig rebalancerConfig) { boolean status = _accessor.setProperty(_keyBuilder.resourceConfig(resourceId.stringify()), configuration); // set an ideal state if the resource supports it IdealState idealState = rebalancerConfigToIdealState(rebalancerConfig, configuration.getBucketSize(), configuration.getBatchMessageMode()); if (idealState != null) { _accessor.setProperty(_keyBuilder.idealStates(resourceId.stringify()), idealState); } return status; } /** * Set the config of the rebalancer. This includes all properties required for rebalancing this * resource * @param resourceId the resource to update * @param config the new rebalancer config * @return true if the config was set, false otherwise */ public boolean setRebalancerConfig(ResourceId resourceId, RebalancerConfig config) { ResourceConfiguration resourceConfig = new ResourceConfiguration(resourceId); PartitionedRebalancerConfig partitionedConfig = PartitionedRebalancerConfig.from(config); if (partitionedConfig == null || partitionedConfig.getRebalanceMode() == RebalanceMode.USER_DEFINED) { // only persist if this is not easily convertible to an ideal state resourceConfig.addNamespacedConfig(new RebalancerConfigHolder(config).toNamespacedConfig()); } // update the ideal state if applicable IdealState oldIdealState = _accessor.getProperty(_keyBuilder.idealStates(resourceId.stringify())); if (oldIdealState != null) { IdealState idealState = rebalancerConfigToIdealState(config, oldIdealState.getBucketSize(), oldIdealState.getBatchMessageMode()); if (idealState != null) { _accessor.setProperty(_keyBuilder.idealStates(resourceId.stringify()), idealState); } } return _accessor.updateProperty(_keyBuilder.resourceConfig(resourceId.stringify()), resourceConfig); } /** * Read the user config of the resource * @param resourceId the resource to to look up * @return UserConfig, or null */ public UserConfig readUserConfig(ResourceId resourceId) { ResourceConfiguration resourceConfig = _accessor.getProperty(_keyBuilder.resourceConfig(resourceId.stringify())); return resourceConfig != null ? UserConfig.from(resourceConfig) : null; } /** * Read the rebalancer config of the resource * @param resourceId the resource to to look up * @return RebalancerConfig, or null */ public RebalancerConfig readRebalancerConfig(ResourceId resourceId) { IdealState idealState = _accessor.getProperty(_keyBuilder.idealStates(resourceId.stringify())); if (idealState != null && idealState.getRebalanceMode() != RebalanceMode.USER_DEFINED) { return PartitionedRebalancerConfig.from(idealState); } ResourceConfiguration resourceConfig = _accessor.getProperty(_keyBuilder.resourceConfig(resourceId.stringify())); return resourceConfig.getRebalancerConfig(RebalancerConfig.class); } /** * Set the user config of the resource, overwriting existing user configs * @param resourceId the resource to update * @param userConfig the new user config * @return true if the user config was set, false otherwise */ public boolean setUserConfig(ResourceId resourceId, UserConfig userConfig) { ResourceConfig.Delta delta = new ResourceConfig.Delta(resourceId).setUserConfig(userConfig); return updateResource(resourceId, delta) != null; } /** * Add user configuration to the existing resource user configuration. Overwrites properties with * the same key * @param resourceId the resource to update * @param userConfig the user config key-value pairs to add * @return true if the user config was updated, false otherwise */ public boolean updateUserConfig(ResourceId resourceId, UserConfig userConfig) { ResourceConfiguration resourceConfig = new ResourceConfiguration(resourceId); resourceConfig.addNamespacedConfig(userConfig); return _accessor.updateProperty(_keyBuilder.resourceConfig(resourceId.stringify()), resourceConfig); } /** * Clear any user-specified configuration from the resource * @param resourceId the resource to update * @return true if the config was cleared, false otherwise */ public boolean dropUserConfig(ResourceId resourceId) { return setUserConfig(resourceId, new UserConfig(Scope.resource(resourceId))); } /** * Persist an existing resource's logical configuration * @param resourceConfig logical resource configuration * @return true if resource is set, false otherwise */ public boolean setResource(ResourceConfig resourceConfig) { if (resourceConfig == null || resourceConfig.getRebalancerConfig() == null) { LOG.error("Resource not fully defined with a rebalancer context"); return false; } ResourceId resourceId = resourceConfig.getId(); ResourceConfiguration config = new ResourceConfiguration(resourceId); config.addNamespacedConfig(resourceConfig.getUserConfig()); PartitionedRebalancerConfig partitionedConfig = PartitionedRebalancerConfig.from(resourceConfig.getRebalancerConfig()); if (partitionedConfig == null || partitionedConfig.getRebalanceMode() == RebalanceMode.USER_DEFINED) { // only persist if this is not easily convertible to an ideal state config.addNamespacedConfig(new RebalancerConfigHolder(resourceConfig.getRebalancerConfig()) .toNamespacedConfig()); } config.setBucketSize(resourceConfig.getBucketSize()); config.setBatchMessageMode(resourceConfig.getBatchMessageMode()); setConfiguration(resourceId, config, resourceConfig.getRebalancerConfig()); return true; } /** * Get a resource configuration, which may include user-defined configuration, as well as * rebalancer configuration * @param resourceId * @return configuration or null */ public ResourceConfiguration getConfiguration(ResourceId resourceId) { return _accessor.getProperty(_keyBuilder.resourceConfig(resourceId.stringify())); } /** * set external view of a resource * @param resourceId * @param extView * @return true if set, false otherwise */ public boolean setExternalView(ResourceId resourceId, ExternalView extView) { return _accessor.setProperty(_keyBuilder.externalView(resourceId.stringify()), extView); } /** * get the external view of a resource * @param resourceId the resource to look up * @return external view or null */ public ExternalView readExternalView(ResourceId resourceId) { return _accessor.getProperty(_keyBuilder.externalView(resourceId.stringify())); } /** * drop external view of a resource * @param resourceId * @return true if dropped, false otherwise */ public boolean dropExternalView(ResourceId resourceId) { return _accessor.removeProperty(_keyBuilder.externalView(resourceId.stringify())); } /** * reset resources for all participants * @param resetResourceIdSet the resources to reset * @return true if they were reset, false otherwise */ public boolean resetResources(Set<ResourceId> resetResourceIdSet) { ParticipantAccessor accessor = participantAccessor(); List<ExternalView> extViews = _accessor.getChildValues(_keyBuilder.externalViews()); for (ExternalView extView : extViews) { if (!resetResourceIdSet.contains(extView.getResourceId())) { continue; } Map<ParticipantId, Set<PartitionId>> resetPartitionIds = Maps.newHashMap(); for (PartitionId partitionId : extView.getPartitionIdSet()) { Map<ParticipantId, State> stateMap = extView.getStateMap(partitionId); for (ParticipantId participantId : stateMap.keySet()) { State state = stateMap.get(participantId); if (state.equals(State.from(HelixDefinedState.ERROR))) { if (!resetPartitionIds.containsKey(participantId)) { resetPartitionIds.put(participantId, new HashSet<PartitionId>()); } resetPartitionIds.get(participantId).add(partitionId); } } } for (ParticipantId participantId : resetPartitionIds.keySet()) { accessor.resetPartitionsForParticipant(participantId, extView.getResourceId(), resetPartitionIds.get(participantId)); } } return true; } /** * Generate a default assignment for partitioned resources * @param resourceId the resource to update * @param replicaCount the new replica count (or -1 to use the existing one) * @param participantGroupTag the new participant group tag (or null to use the existing one) * @return true if assignment successful, false otherwise */ public boolean generateDefaultAssignment(ResourceId resourceId, int replicaCount, String participantGroupTag) { Resource resource = readResource(resourceId); RebalancerConfig config = resource.getRebalancerConfig(); PartitionedRebalancerConfig partitionedConfig = PartitionedRebalancerConfig.from(config); if (partitionedConfig == null) { LOG.error("Only partitioned resource types are supported"); return false; } if (replicaCount != -1) { partitionedConfig.setReplicaCount(replicaCount); } if (participantGroupTag != null) { partitionedConfig.setParticipantGroupTag(participantGroupTag); } StateModelDefinition stateModelDef = _accessor.getProperty(_keyBuilder.stateModelDef(partitionedConfig.getStateModelDefId() .stringify())); List<InstanceConfig> participantConfigs = _accessor.getChildValues(_keyBuilder.instanceConfigs()); Set<ParticipantId> participantSet = Sets.newHashSet(); for (InstanceConfig participantConfig : participantConfigs) { participantSet.add(participantConfig.getParticipantId()); } partitionedConfig.generateDefaultConfiguration(stateModelDef, participantSet); setRebalancerConfig(resourceId, partitionedConfig); return true; } /** * Get an ideal state from a rebalancer config if the resource is partitioned * @param config RebalancerConfig instance * @param bucketSize bucket size to use * @param batchMessageMode true if batch messaging allowed, false otherwise * @return IdealState, or null */ static IdealState rebalancerConfigToIdealState(RebalancerConfig config, int bucketSize, boolean batchMessageMode) { PartitionedRebalancerConfig partitionedConfig = PartitionedRebalancerConfig.from(config); if (partitionedConfig != null) { IdealState idealState = new IdealState(partitionedConfig.getResourceId()); idealState.setRebalanceMode(partitionedConfig.getRebalanceMode()); idealState.setRebalancerRef(partitionedConfig.getRebalancerRef()); String replicas = null; if (partitionedConfig.anyLiveParticipant()) { replicas = StateModelToken.ANY_LIVEINSTANCE.toString(); } else { replicas = Integer.toString(partitionedConfig.getReplicaCount()); } idealState.setReplicas(replicas); idealState.setNumPartitions(partitionedConfig.getPartitionSet().size()); idealState.setInstanceGroupTag(partitionedConfig.getParticipantGroupTag()); idealState.setMaxPartitionsPerInstance(partitionedConfig.getMaxPartitionsPerParticipant()); idealState.setStateModelDefId(partitionedConfig.getStateModelDefId()); idealState.setStateModelFactoryId(partitionedConfig.getStateModelFactoryId()); idealState.setBucketSize(bucketSize); idealState.setBatchMessageMode(batchMessageMode); if (partitionedConfig.getRebalanceMode() == RebalanceMode.SEMI_AUTO) { SemiAutoRebalancerConfig semiAutoConfig = BasicRebalancerConfig.convert(config, SemiAutoRebalancerConfig.class); for (PartitionId partitionId : semiAutoConfig.getPartitionSet()) { idealState.setPreferenceList(partitionId, semiAutoConfig.getPreferenceList(partitionId)); } } else if (partitionedConfig.getRebalanceMode() == RebalanceMode.CUSTOMIZED) { CustomRebalancerConfig customConfig = BasicRebalancerConfig.convert(config, CustomRebalancerConfig.class); for (PartitionId partitionId : customConfig.getPartitionSet()) { idealState .setParticipantStateMap(partitionId, customConfig.getPreferenceMap(partitionId)); } } else { for (PartitionId partitionId : partitionedConfig.getPartitionSet()) { List<ParticipantId> preferenceList = Collections.emptyList(); idealState.setPreferenceList(partitionId, preferenceList); Map<ParticipantId, State> participantStateMap = Collections.emptyMap(); idealState.setParticipantStateMap(partitionId, participantStateMap); } } return idealState; } return null; } /** * Create a resource snapshot instance from the physical model * @param resourceId the resource id * @param resourceConfiguration physical resource configuration * @param idealState ideal state of the resource * @param externalView external view of the resource * @param resourceAssignment current resource assignment * @return Resource */ static Resource createResource(ResourceId resourceId, ResourceConfiguration resourceConfiguration, IdealState idealState, ExternalView externalView, ResourceAssignment resourceAssignment) { UserConfig userConfig; RebalancerConfig rebalancerConfig = null; ResourceType type = ResourceType.DATA; if (resourceConfiguration != null) { userConfig = resourceConfiguration.getUserConfig(); type = resourceConfiguration.getType(); } else { userConfig = new UserConfig(Scope.resource(resourceId)); } int bucketSize = 0; boolean batchMessageMode = false; if (idealState != null) { if (resourceConfiguration != null && idealState.getRebalanceMode() == RebalanceMode.USER_DEFINED) { // prefer rebalancer config for user_defined data rebalancing rebalancerConfig = resourceConfiguration.getRebalancerConfig(PartitionedRebalancerConfig.class); } if (rebalancerConfig == null) { // prefer ideal state for non-user_defined data rebalancing rebalancerConfig = PartitionedRebalancerConfig.from(idealState); } bucketSize = idealState.getBucketSize(); batchMessageMode = idealState.getBatchMessageMode(); idealState.updateUserConfig(userConfig); } else if (resourceConfiguration != null) { bucketSize = resourceConfiguration.getBucketSize(); batchMessageMode = resourceConfiguration.getBatchMessageMode(); rebalancerConfig = resourceConfiguration.getRebalancerConfig(RebalancerConfig.class); } if (rebalancerConfig == null) { rebalancerConfig = new PartitionedRebalancerConfig(); } return new Resource(resourceId, type, idealState, resourceAssignment, externalView, rebalancerConfig, userConfig, bucketSize, batchMessageMode); } /** * Get a ParticipantAccessor instance * @return ParticipantAccessor */ protected ParticipantAccessor participantAccessor() { return new ParticipantAccessor(_accessor); } }
42.392197
102
0.744248
1fa876b78b24768579b6d53eff11e484d8577d56
2,398
package consultorio.classes; import consultorio.classes.Enum.Especializacoes; public class Odontologista extends Pessoa{ protected String crm; protected int iddentista; protected Especializacoes especializacoes; public Odontologista(String nome, String cpf, String telefone, String email, String sexo, int idade, String pais, String estado, String cidade, String bairro, String rua, String numero, String complemento, String crm, String especializacao) { super(nome, cpf, telefone, email, sexo, idade, pais, estado, cidade, bairro, rua, numero, complemento); this.especializacoes = comparadorEspecialidade(especializacao); this.crm = crm; } public Odontologista(String endereco, String nome, String cpf, String telefone, String email, String sexo, int idade, String crm, int iddentista, String especializacao) { super(endereco, nome, cpf, telefone, email, sexo, idade); this.crm = crm; this.iddentista = iddentista; this.especializacoes = comparadorEspecialidade(especializacao); } public Odontologista(String endereco, String nome, String cpf, String telefone, String email, String sexo, int idade, String crm, String especializacao) { super(endereco, nome, cpf, telefone, email, sexo, idade); this.crm = crm; this.especializacoes = comparadorEspecialidade(especializacao); } public String getCrm() { return crm; } public void setCrm(String crm) { this.crm = crm; } public int getIddentista() { return iddentista; } public void setIddentista(int iddentista) { this.iddentista = iddentista; } public Especializacoes getEspecializacoes() { return especializacoes; } public void setEspecializacoes(Especializacoes especializacoes) { this.especializacoes = especializacoes; } @Override public void infoBasic(){ System.out.printf("%d %s %s %s %s %s%n", getIddentista(), getNome(), getCpf(), getEmail(), getTelefone(), getEndereco()); } public static Especializacoes comparadorEspecialidade(String string){ if (string.equals(Especializacoes.PROTETICO.toString())){ return Especializacoes.PROTETICO; } else if (string.equals(Especializacoes.DENTISTA.toString())){ return Especializacoes.DENTISTA; } else if (string.equals(Especializacoes.CIRURGIAO.toString())){ return Especializacoes.CIRURGIAO; } else { return null; } } }
31.973333
123
0.728941
4dc5e74662742d9d3dc83eb32072b38fa623235e
2,097
package seedu.expensela.logic.parser; import static seedu.expensela.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.expensela.logic.parser.CliSyntax.PREFIX_BUDGET; import static seedu.expensela.logic.parser.CliSyntax.PREFIX_RECURRING; import java.util.stream.Stream; import seedu.expensela.logic.commands.BudgetCommand; import seedu.expensela.logic.parser.exceptions.ParseException; import seedu.expensela.model.monthlydata.Budget; /** * Parses input arguments and creates a new BudgetCommand object */ public class BudgetCommandParser implements Parser<BudgetCommand> { /** * Parses the given {@code String} of arguments in the context of the BudgetCommand * and returns a BudgetCommand object for execution. * @throws ParseException if the user input does not conform the expected format */ public BudgetCommand parse(String args) throws ParseException { ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_BUDGET, PREFIX_RECURRING); if (!arePrefixesPresent(argMultimap, PREFIX_BUDGET) || !argMultimap.getPreamble().isEmpty()) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, BudgetCommand.MESSAGE_USAGE)); } try { Budget budget = ParserUtil.parseBudget(argMultimap.getValue(PREFIX_BUDGET).get()); boolean recurring = false; if (arePrefixesPresent(argMultimap, PREFIX_RECURRING)) { recurring = true; } return new BudgetCommand(budget.budgetAmount, recurring); } catch (IllegalArgumentException e) { throw new ParseException(e.getMessage()); } } /** * Returns true if none of the prefixes contains empty {@code Optional} values in the given * {@code ArgumentMultimap}. */ private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent()); } }
39.566038
113
0.713877
d368e2f4fd7cd3cedc387f60b0a70ff739f917aa
456
package frc.robot.commands; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Climber; public class ZeroClimber extends CommandBase { private final Climber m_climber; public ZeroClimber(Climber climber) { m_climber = climber; addRequirements(climber); } @Override public void execute() { m_climber.zeroPose(); } }
21.714286
59
0.719298
8d311c6a7b6cf756f95c903cf5e034f098a49e7d
3,430
package org.codehaus.xfire.wsdl11; import java.util.Collection; import java.util.Map; import javax.xml.namespace.QName; import org.codehaus.xfire.service.Endpoint; import org.codehaus.xfire.service.MessageInfo; import org.codehaus.xfire.service.MessagePartContainer; import org.codehaus.xfire.service.MessagePartInfo; import org.codehaus.xfire.service.OperationInfo; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.binding.MessageBindingProvider; import org.codehaus.xfire.soap.AbstractSoapBinding; import org.codehaus.xfire.test.AbstractXFireTest; import org.codehaus.xfire.wsdl11.parser.WSDLServiceBuilder; /** * @author <a href="mailto:[email protected]">Dan Diephouse</a> */ public class HeaderTest extends AbstractXFireTest { public void testVisitor() throws Exception { WSDLServiceBuilder builder = new WSDLServiceBuilder(getResourceAsStream("echoHeader.wsdl")); builder.setBindingProvider(new MessageBindingProvider()); builder.build(); Map serviceMap = builder.getServices(); assertEquals(1, serviceMap.size()); Collection services = builder.getAllServices(); assertEquals(1, services.size()); Service service = (Service) services.iterator().next(); QName name = service.getName(); assertNotNull(name); assertEquals(new QName("urn:Echo", "Echo"), name); Collection operations = service.getServiceInfo().getOperations(); assertEquals(1, operations.size()); OperationInfo opInfo = (OperationInfo) operations.iterator().next(); assertEquals("echo", opInfo.getName()); // Check the input message MessageInfo message = opInfo.getInputMessage(); assertNotNull(message); Collection parts = message.getMessageParts(); assertEquals(1, parts.size()); MessagePartInfo part = (MessagePartInfo) parts.iterator().next(); assertEquals(new QName("urn:Echo", "echoRequest"), part.getName()); // Check the output message message = opInfo.getOutputMessage(); assertNotNull(message); parts = message.getMessageParts(); assertEquals(1, parts.size()); part = (MessagePartInfo) parts.iterator().next(); assertEquals(new QName("urn:Echo", "echoResponse"), part.getName()); // Is the SOAP binding stuff around? AbstractSoapBinding soapBinding = (AbstractSoapBinding) service.getBindings().iterator().next(); assertNotNull(soapBinding); assertEquals("literal", soapBinding.getUse()); assertEquals("", soapBinding.getSoapAction(opInfo)); MessagePartContainer c = soapBinding.getHeaders(opInfo.getInputMessage()); assertEquals(1, c.getMessageParts().size()); part = c.getMessagePart(new QName("urn:Echo", "echoHeader")); assertNotNull(part); Collection endpoints = service.getEndpoints(); assertEquals(1, endpoints.size()); Endpoint endpoint = (Endpoint) endpoints.iterator().next(); assertEquals(new QName("urn:Echo", "EchoHttpPort"), endpoint.getName()); assertNotNull(endpoint.getBinding()); assertEquals("http://localhost:8080/xfire/services/Echo", endpoint.getUrl()); } }
37.692308
104
0.664723
0a04d77c793743c58d6d6a229116f9c6d682a6ce
414
package com.broadcom; import com.broadcom.apdk.api.BaseAction; import com.broadcom.apdk.api.annotations.Action; import com.broadcom.apdk.api.annotations.ActionPacks; @Action( name = "ACTION3", title = "Action #3 for testing the API" ) @ActionPacks({TestActionPack2.class}) public class TestAction3 extends BaseAction { @Override public void run() { System.out.println(this.getClass().getName()); } }
20.7
53
0.748792
d8409c6324c13b795c30176bbc1b825f88fefba8
1,019
package cn.fjc.reflectiontutorial; /** * Created by shiqifeng on 2017/1/9. * Mail [email protected] */ public class ExampleObject extends FatherObject { public int age = 30; public String name = "byhieg"; private Integer score = 60; public void printName() { System.out.println(name); } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public ExampleObject() { } public ExampleObject(String name) { } public ExampleObject(int age, Integer score) { } @Override public void doSomething() { super.doSomething(); } @Override public void run() { System.out.println("run......"); } }
16.435484
50
0.57213
6904cf9f0f6ab0ba6fda67674adf33209fdd5cfb
1,372
package com.venus.demo.dao.model; public class User { private Long id; private String name; private String email; private String gender; private Integer age; private String address; private String qq; 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 == null ? null : name.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender == null ? null : gender.trim(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq == null ? null : qq.trim(); } }
18.794521
64
0.528426
c40254435c5407a97eba8026231dc65b4e3e7a2f
8,645
/* * 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.autoupdate.services; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.logging.Level; import org.netbeans.api.autoupdate.DefaultTestCase; import org.netbeans.api.autoupdate.InstallSupport; import org.netbeans.api.autoupdate.InstallSupport.Installer; import org.netbeans.api.autoupdate.InstallSupport.Validator; import org.netbeans.api.autoupdate.OperationContainer; import org.netbeans.api.autoupdate.OperationSupport.Restarter; import org.netbeans.api.autoupdate.UpdateUnit; import org.netbeans.api.autoupdate.UpdateUnitProvider.CATEGORY; import org.netbeans.junit.MockServices; import org.netbeans.junit.NbTestCase; import org.netbeans.spi.autoupdate.UpdateItem; import org.netbeans.spi.autoupdate.UpdateLicense; import org.netbeans.spi.autoupdate.UpdateProvider; import org.netbeans.updater.UpdaterInternal; import org.openide.filesystems.FileUtil; import org.openide.modules.ModuleInfo; import org.openide.util.Lookup; /** * * @author Jaroslav Tulach */ public class UpdateDisabledModuleTest extends NbTestCase { static Manifest man; private File ud; public UpdateDisabledModuleTest(String testName) { super(testName); } @Override protected Level logLevel() { return Level.FINE; } @Override protected void setUp() throws Exception { clearWorkDir(); man = new Manifest (); man.getMainAttributes ().putValue ("Manifest-Version", "1.0"); man.getMainAttributes ().putValue ("OpenIDE-Module", "com.example.testmodule.cluster"); man.getMainAttributes ().putValue ("OpenIDE-Module-Public-Packages", "-"); ud = new File(getWorkDir(), "ud"); System.setProperty("netbeans.user", ud.getPath()); new File(ud, "config").mkdirs(); final File install = new File(getWorkDir(), "install"); File platform = new File(install, "platform"); System.setProperty("netbeans.home", platform.getPath()); new File(platform, "config").mkdirs(); File middle = new File(install, "middle"); File last = new File(install, "last"); System.setProperty("netbeans.dirs", middle.getPath() + File.pathSeparator + last.getPath()); final String fn = moduleCodeNameBaseForTest().replace('.', '-') + ".xml"; File conf = new File(new File(new File(middle, "config"), "Modules"), fn); conf.getParentFile().mkdirs(); writeConfXML(conf, false); final File jar = new File(new File(last, "modules"), "com-example-testmodule-cluster.jar"); jar.getParentFile().mkdirs(); JarOutputStream os = new JarOutputStream(new FileOutputStream(jar), man); os.close(); File real = new File(new File(new File(last, "config"), "Modules"), fn); real.getParentFile().mkdirs(); writeConfXML(real, true); FileUtil.getConfigRoot().getFileSystem().refresh(true); File ut = new File(new File(last, "update_tracking"), fn); ut.getParentFile().mkdirs(); OutputStream utos = new FileOutputStream(ut); String utcfg = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<module codename=\"com.example.testmodule.cluster\">\n" + " <module_version install_time=\"1280356738644\" last=\"true\" origin=\"installer\" specification_version=\"0.99\">\n" + " <file crc=\"3486416273\" name=\"config/Modules/com-example-testmodule-cluster.xml\"/>\n" + " <file crc=\"3486416273\" name=\"modules/com-example-testmodule-cluster.jar\"/>\n" + " </module_version>\n" + "</module>\n"; utos.write(utcfg.getBytes(StandardCharsets.UTF_8)); utos.close(); StringBuilder msg = new StringBuilder(); for (ModuleInfo mi : Lookup.getDefault().lookupAll(ModuleInfo.class)) { msg.append(mi.getCodeNameBase()).append("\n"); if (mi.getCodeNameBase().equals("com.example.testmodule.cluster")) { assertFalse("Disabled", mi.isEnabled()); return; } } fail("No com.example.testmodule.cluster module found:\n" + msg); } private void writeConfXML(File conf, boolean enabled) throws FileNotFoundException, IOException { OutputStream os = new FileOutputStream(conf); String cfg = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<!DOCTYPE module PUBLIC '-//NetBeans//DTD Module Status 1.0//EN' 'http://www.netbeans.org/dtds/module-status-1_0.dtd'>\n" + "<module name='com.example.testmodule.cluster'>\n" + " <param name='autoload'>false</param>\n" + " <param name='eager'>false</param>\n" + " <param name='enabled'>" + enabled + "</param>\n" + " <param name='jar'>modules/com-example-testmodule-cluster.jar</param>\n" + " <param name='reloadable'>false</param>\n" + " <param name='specversion'>1.0</param>\n" + "</module>\n" + "\n"; os.write(cfg.getBytes(StandardCharsets.UTF_8)); os.close(); } String moduleCodeNameBaseForTest() { return "com.example.testmodule.cluster"; //NOI18N } public void testSelf() throws Exception { File f = new File(new File(new File(ud, "config"), "Modules"), "com-example-testmodule-cluster.xml"); f.delete(); assertFalse("No Config file before: " + f, f.exists()); MockServices.setServices(UP.class); UpdateUnit update = UpdateManagerImpl.getInstance().getUpdateUnit(moduleCodeNameBaseForTest()); assertNotNull("There is an NBM to update", update); OperationContainer<InstallSupport> oc = OperationContainer.createForUpdate(); oc.add(update, update.getAvailableUpdates().get(0)); final InstallSupport support = oc.getSupport(); Validator down = support.doDownload(null, true); Installer inst = support.doValidate(down, null); Restarter res = support.doInstall(inst, null); System.setProperty("netbeans.close.no.exit", "true"); support.doRestart(res, null); UpdaterInternal.update(null, null, null); assertFalse("No Config file created in for upgrade: " + f, f.exists()); } public static final class UP implements UpdateProvider { @Override public String getName() { return "test"; } @Override public String getDisplayName() { return "test view"; } @Override public String getDescription() { return "none"; } @Override public CATEGORY getCategory() { return CATEGORY.STANDARD; } @Override public Map<String, UpdateItem> getUpdateItems() throws IOException { Map<String, UpdateItem> m = new HashMap<String, UpdateItem>(); m.put("com.example.testmodule.cluster", UpdateItem.createModule( "com.example.testmodule.cluster", "1.0", DefaultTestCase.class.getResource("data/com-example-testmodule-cluster.nbm"), "jarda", "4000", "http://netbeans.de", "2010/10/27", "OK", man, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE, "platform", UpdateLicense.createUpdateLicense("CDDL", "Free to use") )); return m; } @Override public boolean refresh(boolean force) throws IOException { return true; } } }
39.474886
140
0.646617
c783cbf3bc94f0d2a13bd987674b6076a8e37900
236
package com.example.errorutil; import android.util.Log; public class LogError { private static final String TAG = "MY_MODULE"; public static void errorPrinter(String TAG, String message){ Log.e(TAG, message); } }
19.666667
64
0.699153
6f6410bc219dabc3b100670d6d4fdc985828895d
278
package buzz.song.facilitator.repository; import buzz.song.facilitator.model.Track; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; public interface TrackRepository extends JpaRepository<Track, Track.TrackID> {}
34.75
79
0.848921
a60230191153f5d03fe5c63017c7d8acc9ed664f
65
package com.zb.basic.mvp.model; public interface IBaseModel { }
13
31
0.769231
40d04c27cf3a5b8786e849bf7c48bc539d409c31
14,478
package info.smart_tools.smartactors.message_processing.wrapper_generator; import info.smart_tools.smartactors.base.exception.invalid_argument_exception.InvalidArgumentException; import info.smart_tools.smartactors.class_management.class_generator_with_java_compile_api.FromStringClassGenerator; import info.smart_tools.smartactors.class_management.class_generator_with_java_compile_api.class_builder.ClassBuilder; import info.smart_tools.smartactors.class_management.class_generator_with_java_compile_api.class_builder.Modifiers; import info.smart_tools.smartactors.class_management.interfaces.iclass_generator.IClassGenerator; import info.smart_tools.smartactors.field.field.Field; import info.smart_tools.smartactors.iobject.field_name.FieldName; import info.smart_tools.smartactors.iobject.ifield.IField; import info.smart_tools.smartactors.iobject.ifield_name.IFieldName; import info.smart_tools.smartactors.iobject.iobject.exception.ChangeValueException; import info.smart_tools.smartactors.iobject.iobject.exception.DeleteValueException; import info.smart_tools.smartactors.iobject.iobject.exception.ReadValueException; import info.smart_tools.smartactors.iobject.iobject.exception.SerializeException; import info.smart_tools.smartactors.iobject.iobject_wrapper.IObjectWrapper; import info.smart_tools.smartactors.message_processing_interfaces.iwrapper_generator.IWrapperGenerator; import info.smart_tools.smartactors.message_processing_interfaces.iwrapper_generator.exception.WrapperGeneratorException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Implementation of {@link IWrapperGenerator}. * <pre> * Main features of implementation: * - use class generator based on java compile API; * - use supporting class Field; * </pre> */ public class WrapperGenerator implements IWrapperGenerator { private IClassGenerator<String> classGenerator; /** * Constructor. * Create new instance of {@link WrapperGenerator} by given {@link ClassLoader} */ public WrapperGenerator() { this.classGenerator = new FromStringClassGenerator(); } @Override public <T> T generate(final Class<T> targetInterface) throws InvalidArgumentException, WrapperGeneratorException { T instance = null; if (null == targetInterface) { throw new InvalidArgumentException("Target class should not be null!"); } if (!targetInterface.isInterface()) { throw new InvalidArgumentException("Target class should be an interface!"); } try { Class<T> clazz = (Class<T>) targetInterface.getClassLoader().loadClass( targetInterface.getName()+"Impl" ); return clazz.newInstance(); } catch (Throwable e) { // do nothing in case if wrapper implementation class failed to be loaded // or new instance of wrapper implementation failed to be created } try { Class<T> clazz = generateClass(targetInterface); try { return clazz.newInstance(); } catch (Throwable e) { throw new RuntimeException("Error on creation instance of wrapper.", e); } } catch (Throwable e) { throw new WrapperGeneratorException( "Could not implement wrapper interface because of the following error:", e ); } } private <T> Class<T> generateClass(final Class<T> targetInterface) throws Exception { ClassBuilder cb = new ClassBuilder("\t", "\n"); // Add package name and imports. cb .addPackageName(targetInterface.getPackage().getName()) .addImport(IField.class.getCanonicalName()) .addImport(Field.class.getCanonicalName()) .addImport(FieldName.class.getCanonicalName()) .addImport(InvalidArgumentException.class.getCanonicalName()) .addImport(targetInterface.getCanonicalName()) .addImport("info.smart_tools.smartactors.iobject.iobject.IObject") .addImport(IObjectWrapper.class.getCanonicalName()) .addImport(ReadValueException.class.getCanonicalName()) .addImport(ChangeValueException.class.getCanonicalName()) .addImport("info.smart_tools.smartactors.iobject.ifield_name.IFieldName") .addImport(DeleteValueException.class.getCanonicalName()) .addImport(SerializeException.class.getCanonicalName()) .addImport(Iterator.class.getCanonicalName()) .addImport(Map.class.getCanonicalName()) .addImport(HashMap.class.getCanonicalName()); Map<Class<?>, String> types = new HashMap<>(); for (Method m : targetInterface.getMethods()) { Class<?> returnType = m.getReturnType(); if (!returnType.isPrimitive()) { types.put(returnType, returnType.getCanonicalName()); } Class<?>[] args = m.getParameterTypes(); for (Class<?> c : args) { if (!c.isPrimitive()) { types.put(c, c.getCanonicalName()); } } } for (Object o : types.entrySet()) { Map.Entry entry = (Map.Entry) o; cb.addImport((String) entry.getValue()); } // Add class header cb .addClass() .setClassModifier(Modifiers.PUBLIC) .setClassName(targetInterface.getSimpleName() + "Impl") .setInterfaces("IObjectWrapper") .setInterfaces("IObject") .setInterfaces(targetInterface.getSimpleName()); // Add class fields for (Method m : targetInterface.getMethods()) { String methodPrefix; if (Void.TYPE == m.getGenericReturnType()) { methodPrefix = "out"; } else { methodPrefix = "in"; } cb .addField().setModifier(Modifiers.PRIVATE).setType("IField") .setName("fieldFor_" + methodPrefix + "_" + m.getName()); } cb .addField() .setModifier(Modifiers.PRIVATE) .setType(Map.class.getSimpleName()) .setInnerGenericType(IFieldName.class.getSimpleName() + "," + Field.class.getSimpleName()) .setName("fields"); // Add class constructors StringBuilder builder = new StringBuilder(); builder.append("\t\t").append("try {\n"); for (Method m : targetInterface.getMethods()) { String methodPrefix = Void.TYPE == m.getGenericReturnType() ? "out" : "in"; builder .append("\t\t\t").append("this.fieldFor_") .append(methodPrefix) .append("_") .append(m.getName()) .append(" = new ") .append("Field(new FieldName(\"") .append(methodPrefix).append("_").append(m.getName()).append("\"" + "));\n"); } builder.append("this.fields = new HashMap<>();\n"); builder .append("\t\t").append("} catch (Exception e) {\n").append("\t\t\t") .append("throw new InvalidArgumentException(\"\", e);\n") .append("\t\t").append("}"); cb .addConstructor().setModifier(Modifiers.PUBLIC).setExceptions("InvalidArgumentException") .addStringToBody(builder.toString()); // Add 'IObject[] args;' field cb .addField().setModifier(Modifiers.PRIVATE).setType("IObject").setName("env"); // Add init method cb .addMethod().setModifier(Modifiers.PUBLIC).setReturnType("void").setName("init") .addParameter() .setType("IObject").setName("environments").next() .addStringToBody("this.env = environments;"); // Add 'getIObjects' method cb .addMethod().setModifier(Modifiers.PUBLIC).setReturnType("IObject").setName("getEnvironmentIObject") .addParameter() .setType("IFieldName") .setName("fieldName") .next() .setExceptions("InvalidArgumentException") .addStringToBody("try {") .addStringToBody("\tif (IObjectWrapper.class.isAssignableFrom(this.env.getClass())) {") .addStringToBody("\t\treturn ((IObjectWrapper) this.env).getEnvironmentIObject(fieldName);") .addStringToBody("\t}") .addStringToBody("\treturn (IObject) this.env.getValue(fieldName);") .addStringToBody("} catch (Throwable e) {") .addStringToBody("throw new InvalidArgumentException(\"Could not get IObject from environments.\", e);") .addStringToBody("}"); // Add getters and setters for (Method m : targetInterface.getMethods()) { String methodPrefix = Void.TYPE == m.getGenericReturnType() ? "out" : "in"; if (!m.getReturnType().equals(Void.TYPE)) { cb .addMethod().setModifier(Modifiers.PUBLIC).setReturnType(m.getGenericReturnType().getTypeName()) .setName(m.getName()).setExceptions("ReadValueException") .addStringToBody("try {") .addStringToBody( "\treturn fieldFor_" + methodPrefix + "_" + m.getName() + ".in(this.env, " + m.getReturnType().getSimpleName() + ".class);" ) .addStringToBody("} catch(Throwable e) {") .addStringToBody("\tthrow new ReadValueException(\"Could not get value from iobject.\", e);") .addStringToBody("}"); } else { cb .addMethod().setModifier(Modifiers.PUBLIC).setReturnType("void").setName(m.getName()) .setExceptions("ChangeValueException") .addParameter() .setType(m.getGenericParameterTypes()[0].getTypeName()).setName("value").next() .addStringToBody("try {") .addStringToBody( "\tthis.fieldFor_" + methodPrefix + "_" + m.getName() + ".out(this.env, value);" ) .addStringToBody("} catch (Throwable e) {") .addStringToBody("\tthrow new ChangeValueException(\"Could not set value from iobject.\", e);") .addStringToBody("}"); } } // Add 'IObject' methods cb .addMethod() .setModifier(Modifiers.PUBLIC) .setReturnType(Object.class.getSimpleName()) .setName("getValue") .addParameter() .setType(IFieldName.class.getSimpleName()) .setName("name") .next() .setExceptions(ReadValueException.class.getSimpleName()) .setExceptions(InvalidArgumentException.class.getSimpleName()) .addStringToBody("Field field = fields.get(name);") .addStringToBody("if (null == field) {") .addStringToBody("\tfield = new Field(name);") .addStringToBody("\tfields.put(name, field);") .addStringToBody("}") .addStringToBody("return new Field(name).in(this.env);"); cb .addMethod() .setModifier(Modifiers.PUBLIC) .setReturnType("void") .setName("setValue") .addParameter() .setType(IFieldName.class.getSimpleName()) .setName("name") .next() .addParameter() .setType(Object.class.getSimpleName()) .setName("value") .next() .setExceptions(ChangeValueException.class.getSimpleName()) .setExceptions(InvalidArgumentException.class.getSimpleName()) .addStringToBody("Field field = fields.get(name);") .addStringToBody("if (null == field) {") .addStringToBody("\tfield = new Field(name);") .addStringToBody("\tfields.put(name, field);") .addStringToBody("}") .addStringToBody("new Field(name).out(env, value);"); cb .addMethod() .setModifier(Modifiers.PUBLIC) .setReturnType("void") .setName("deleteField") .addParameter() .setType(IFieldName.class.getSimpleName()) .setName("name") .next() .setExceptions(DeleteValueException.class.getSimpleName()) .setExceptions(InvalidArgumentException.class.getSimpleName()) .addStringToBody("throw new DeleteValueException(\"Method not implemented.\");"); cb .addMethod() .setModifier(Modifiers.PUBLIC) .setReturnType("<T> T") .setName("serialize") .setExceptions(SerializeException.class.getSimpleName()) .addStringToBody("throw new SerializeException(\"Method not implemented.\");"); cb .addMethod() .setModifier(Modifiers.PUBLIC) .setReturnType("Iterator<Map.Entry<IFieldName, Object>>") .setName("iterator") .addStringToBody("return null;"); return (Class<T>) classGenerator.generate( cb.buildClass().toString(), targetInterface.getClassLoader() ); } }
45.961905
121
0.562509
b2d6093a67b8738b1f70b7432a46975be691b9a0
6,262
/** * Copyright 2005-2007 Xue Yong Zhi * Distributed under the BSD License */ package com.xruby.compiler.codedom; import java.util.*; import antlr.RecognitionException; class Rescue { private final ExceptionList condition_; private final CompoundStatement body_; Rescue(ExceptionList condition, CompoundStatement body) { condition_ = condition; body_ = body; } public void accept(CodeVisitor visitor, Object end_label, int excepton_var, boolean has_ensure) { Object next_label = condition_.accept(visitor, excepton_var); if (null != body_) { body_.accept(visitor); } if (has_ensure) { visitor.visitEnsure(-1); } //insert "$! = nil;" AssignmentOperatorExpression exp = null; try { exp = new AssignmentOperatorExpression(new GlobalVariableExpression("$!"), new NilExpression()); } catch (RecognitionException e) { throw new Error(e); } exp.accept(visitor); visitor.visitTerminal(); visitor.visitAfterRescueBody(next_label, end_label); } // For debugger int getLastLine() { return body_.getLastLine(); } } public class BodyStatement implements Visitable { private final CompoundStatement compoundStatement_; private ArrayList<Rescue> rescues_ = new ArrayList<Rescue>(); private CompoundStatement else_ = null; private CompoundStatement ensure_ = null; public BodyStatement(CompoundStatement compoundStatement) { compoundStatement_ = compoundStatement; } public int size() { return compoundStatement_.size(); } boolean lastStatementHasReturnValue() { return compoundStatement_.lastStatementHasReturnValue(); } public void addRescue(ExceptionList el, CompoundStatement compoundStatement) { if (null == compoundStatement) { compoundStatement = new CompoundStatement(); compoundStatement.addStatement(new ExpressionStatement(new NilExpression())); } rescues_.add(new Rescue(el, compoundStatement)); } public void addElse(CompoundStatement compoundStatement) { if (null == compoundStatement) { compoundStatement = new CompoundStatement(); compoundStatement.addStatement(new ExpressionStatement(new NilExpression())); } else_ = compoundStatement; } public void addEnsure(CompoundStatement compoundStatement) { if (null == compoundStatement) { compoundStatement = new CompoundStatement(); compoundStatement.addStatement(new ExpressionStatement(new NilExpression())); } ensure_ = compoundStatement; } private boolean needCatch() { return !rescues_.isEmpty() || null != ensure_; } private void acceptNoBody(CodeVisitor visitor) { //Optimazation: because there is no code to throw any exception, we only need to execute 'ensure' if (null != else_) { else_.accept(visitor); } if (null != ensure_) { if (null != else_) { visitor.visitTerminal(); } ensure_.accept(visitor); } if (null == else_ && null == ensure_) { visitor.visitNilExpression(); } } public void accept(CodeVisitor visitor) { if (null == compoundStatement_) { acceptNoBody(visitor); return; } else if (!needCatch()) { compoundStatement_.accept(visitor); return; } compoundStatement_.ensureVariablesAreInitialized(visitor); ArrayList<Block> pulled_blocks = new ArrayList<Block>(); compoundStatement_.pullBlock(pulled_blocks); for (Block block : pulled_blocks) { block.acceptAsPulled(visitor); } final Object begin_label = visitor.visitBodyBegin(null != ensure_); compoundStatement_.accept(visitor); final Object after_label = visitor.visitBodyAfter(); //The body of an else clause is executed only if no //exceptions are raised by the main body of code if (null != else_) { visitor.visitTerminal(); else_.accept(visitor); } if (null != ensure_) { //do this so that ensure is executed in normal situation visitor.visitEnsure(-1); } final Object end_label = visitor.visitPrepareEnsure(); final int exception_var = visitor.visitRescueBegin(begin_label, after_label); for (Rescue rescue : rescues_) { rescue.accept(visitor, end_label, exception_var, null != ensure_); } if (null != ensure_) { visitor.visitEnsure(exception_var); int var = visitor.visitEnsureBodyBegin(); ensure_.accept(visitor); visitor.visitEnsureBodyEnd(var); } if (!rescues_.isEmpty()) { visitor.visitRescueEnd(exception_var, null != ensure_); } visitor.visitBodyEnd(end_label); } // for debugger public int getLastLine() { int lastLine = compoundStatement_.getLastLine(); if(else_ != null && else_.getLastLine() > lastLine) { lastLine = else_.getLastLine(); } if(ensure_ != null && ensure_.getLastLine() > lastLine) { lastLine = ensure_.getLastLine(); } for(Rescue rescue: rescues_) { if(rescue.getLastLine() > lastLine) { lastLine = rescue.getLastLine(); } } return lastLine; } void pullBlock(ArrayList<Block> result) { if (null != compoundStatement_) { compoundStatement_.pullBlock(result); } } void getNewlyAssignedVariables(ISymbolTable symboltable, ArrayList<String> result) { if (null != compoundStatement_) { compoundStatement_.getNewlyAssignedVariables(symboltable, result); } } }
30.696078
109
0.595816
3fdeb474ca1ae89d16f20861bbb7d8ea97f942ae
2,941
/* * Generated from SessionStateData.bond (https://github.com/Microsoft/bond) */ package com.microsoft.applicationinsights.contracts; import java.io.IOException; import java.io.Writer; import java.util.Map; import com.microsoft.telemetry.JsonHelper; /** * Data contract class SessionStateData. */ public class SessionStateData extends TelemetryData { /** * Backing field for property Ver. */ private int ver = 2; /** * Backing field for property State. */ private SessionState state = SessionState.START; /** * Initializes a new instance of the SessionStateData class. */ public SessionStateData() { this.InitializeFields(); this.SetupAttributes(); } /** * Envelope Name for this telemetry. */ public String getEnvelopeName() { return "Microsoft.ApplicationInsights.SessionState"; } /** * Base Type for this telemetry. */ public String getBaseType() { return "Microsoft.ApplicationInsights.SessionStateData"; } /** * Gets the Ver property. */ public int getVer() { return this.ver; } /** * Sets the Ver property. */ public void setVer(int value) { this.ver = value; } /** * Gets the State property. */ public SessionState getState() { return this.state; } /** * Sets the State property. */ public void setState(SessionState value) { this.state = value; } /** * Gets the Properties property. */ public Map<String, String> getProperties() { //Do nothing - does not currently take properties return null; } /** * Sets the Properties property. */ public void setProperties(Map<String, String> value) { //Do nothing - does not currently take properties } /** * Serializes the beginning of this object to the passed in writer. * @param writer The writer to serialize this object to. */ protected String serializeContent(Writer writer) throws IOException { String prefix = super.serializeContent(writer); writer.write(prefix + "\"ver\":"); writer.write(JsonHelper.convert(this.ver)); prefix = ","; writer.write(prefix + "\"state\":"); writer.write(JsonHelper.convert(this.state.getValue())); prefix = ","; return prefix; } /** * Sets up the events attributes */ public void SetupAttributes() { } /** * Optionally initializes fields for the current context. */ protected void InitializeFields() { QualifiedName = "com.microsoft.applicationinsights.contracts.SessionStateData"; } }
23.34127
88
0.571234
c3f5a52f158df0706c2a145131b017d8b19a8a6f
850
package com.springx.bootdubbo.job.autoconfig; import com.dangdang.ddframe.job.event.JobEventConfiguration; import com.dangdang.ddframe.job.event.JobEventListener; import java.io.Serializable; /** * @author <a href="mailto:[email protected]">fuchun.li</a> * @description 事件配置 * @date 2019年01月15日 11:22 AM * @Copyright (c) 2018, lifesense.com */ class ConfigJobEventConfiguration implements JobEventConfiguration, Serializable { public static final String LX_JOB_EVENT_IDENTITY = "lx_log"; /** * 创建作业事件监听器. * * @return 作业事件监听器. */ @Override public JobEventListener createJobEventListener() { return new ConfigJobEventListener(); } /** * 获取作业事件标识. * * @return 作业事件标识 */ @Override public String getIdentity() { return LX_JOB_EVENT_IDENTITY; } }
22.972973
83
0.682353
922ce46c5c1c409580676d85e08586c27735a8e0
8,676
package edu.uga.ei_final; /** * A program to extract semantic relations for job postings using Sparql and ontologies. * @author Gaurav Agarwal */ //package uga.ei.team4; import org.apache.jena.query.*; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.util.FileManager; import java.util.*; public class Main { final static String PREFIX_JOB_OWL = "http://www.semanticweb.org/gaurav/ontologies/2019/4/job-ontology#"; final static String RDF_FILE = "src/main/java/Job_Ontology.owl"; static Model model; public static void main(String[] args) { FileManager.get().addLocatorClassLoader(Main.class.getClassLoader()); model = FileManager.get().loadModel(RDF_FILE); getSemantics("Sr_Software_Engineer", "Cupertino", "Entry_Level", "100000", "Masters"); } public static void codeSupporter(){ FileManager.get().addLocatorClassLoader(Main.class.getClassLoader()); model = FileManager.get().loadModel(RDF_FILE); } /** * This method runs the Sparql queries on the ontology and fetches the results * @param queryString sparql query * @param findParam the list of parameters to get from the result * @return aggregated results. */ public static List<String> execSparql(String queryString, List<String> findParam){ List<String> relationsFound = new ArrayList<>(); Query query = QueryFactory.create(queryString); QueryExecution qexec = QueryExecutionFactory.create(query, model); try{ ResultSet results = qexec.execSelect(); while (results.hasNext()){ QuerySolution soln = results.nextSolution(); for(String param: findParam) { RDFNode className = soln.get(param); relationsFound.add(className.toString().replace(PREFIX_JOB_OWL, "")); } } } catch (Exception e){ e.printStackTrace(); } finally { qexec.close(); return relationsFound; } } // public static String execSparql(String queryString){ // String relationFound = ""; // // Query query = QueryFactory.create(queryString); // QueryExecution qexec = QueryExecutionFactory.create(query, model); // try{ // ResultSet results = qexec.execSelect(); // while (results.hasNext()){ // QuerySolution soln = results.nextSolution(); // RDFNode className = soln.get("s"); // relationFound = className.toString().replace(PREFIX_JOB_OWL, ""); // } // } catch (Exception e){ // e.printStackTrace(); // } finally { // qexec.close(); // return relationFound; // } // } /** * This method removes duplicate elements in the list maintaining the order of elements * @param originalList The List having duplicate elements * @return List of unique Strigns */ public static List<String> removeDuplicates(List<String> originalList){ Set<String> hset = new LinkedHashSet<>(); hset.addAll(originalList); originalList.clear(); originalList.addAll(hset); return originalList; } /** * This method finds in the ontology Locations near to the given location. * @param loc This is the location whose nearby locations you wish to find * @return a List of nearby locations */ public static List<String> getNearLocations( String loc){ List<String> locations = new ArrayList<>(); locations.add(loc); String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + "PREFIX job-ontology: <"+ PREFIX_JOB_OWL +">" + "SELECT * WHERE {" + "job-ontology:"+loc + " job-ontology:isNearTo ?s ." + "?locate job-ontology:isNearTo ?s" + "}"; // loc = execSparql(queryString); // if(!locations.contains(loc)){ // locations.add(loc); // } // queryString = // "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + // "PREFIX job-ontology: <"+ PREFIX_JOB_OWL +">" + // "SELECT DISTINCT * WHERE {" + // "?s job-ontology:isNearTo job-ontology:"+loc + // "}"; List<String> param = new ArrayList<>(); param.add("locate"); param.add("s"); locations.addAll(execSparql(queryString, param)); locations = removeDuplicates(locations); return locations; } /** * This method gets the job similar to the given job name from the ontology * @param pos job position name you want to get matching results for. * @return a List of job positions similar to the given job position. */ public static List<String> getSimilarPositions(String pos){ List<String> jobs = new ArrayList<>(); List<String> param = new ArrayList<>(); jobs.add(pos); param.add("job"); String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + "PREFIX job-ontology: <"+ PREFIX_JOB_OWL +">" + "SELECT * WHERE {"+ "?s job-ontology:similarTo job-ontology:" + pos + " ." + "?s job-ontology:similarTo ?job"+ "}"; param.add("s"); jobs.addAll(execSparql(queryString, param)); jobs = removeDuplicates(jobs); return jobs; } public static List<String> getSimilarExpJob(String exp){ List<String> jobs = new ArrayList<>(); List<String> param = new ArrayList<>(); param.add("job"); String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + "PREFIX job-ontology: <"+ PREFIX_JOB_OWL +">" + "SELECT * WHERE {"+ "?job job-ontology:requiresExperience job-ontology:" + exp + "}"; jobs.addAll(execSparql(queryString, param)); jobs = removeDuplicates(jobs); return jobs; } public static List<String> getSimilarPayJob(String sal){ List<String> jobs = new ArrayList<>(); List<String> param = new ArrayList<>(); param.add("job"); String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + "PREFIX job-ontology: <"+ PREFIX_JOB_OWL +">" + "SELECT * WHERE {"+ "?job job-ontology:hasAveragePay job-ontology:" + sal + "}"; jobs.addAll(execSparql(queryString, param)); jobs = removeDuplicates(jobs); return jobs; } public static List<String> getSimilarDegreeJob(String edu){ List<String> jobs = new ArrayList<>(); List<String> param = new ArrayList<>(); param.add("job"); String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + "PREFIX job-ontology: <"+ PREFIX_JOB_OWL +">" + "SELECT * WHERE {"+ "?job job-ontology:requiresEducation job-ontology:" + edu + "}"; jobs.addAll(execSparql(queryString, param)); jobs = removeDuplicates(jobs); return jobs; } /** * This method gets the semantic matching results from the various methods called in here and loads them into a HashMap. * @param pos job position name. * @param loc job location city. * @param exp experience level. * @param sal Average pay for a given job role. * @param edu Education requirement. */ public static void getSemantics(String pos, String loc, String exp, String sal, String edu){ // model.write(System.out, "RDF/XML"); Map<String, List<String>> resultMap = new LinkedHashMap<String, List<String>>(); resultMap.put("location", getNearLocations(loc)); resultMap.put("jobs-pos", getSimilarPositions(pos)); resultMap.put("jobs-exp", getSimilarExpJob(exp)); resultMap.put("jobs-sal", getSimilarPayJob(sal)); resultMap.put("jobs-edu", getSimilarDegreeJob(edu)); System.out.println(resultMap); } } // "{ ?s job-ontology:isNearTo job-ontology:"+loc + " .}" + // "UNION" +
36.919149
124
0.571
d72fbf28aa7b1c818e14aaf37ba3e02312d218ad
6,815
/* * Copyright (C) 2016 essobedo. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.github.essobedo.appma.task; import com.github.essobedo.appma.exception.TaskInterruptedException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; /** * @author Nicolas Filotto ([email protected]) * @version $Id$ * @since 1.0 */ public class TestTaskProgress { @Test public void updateProgress() throws Exception { Task<?> task = new Task<Object>("foo") { @Override public boolean cancelable() { throw new UnsupportedOperationException("#cancelable()"); } @Override public Void execute() { updateProgress(2, 4); return null; } }; AtomicInteger called = new AtomicInteger(); AtomicInteger done = new AtomicInteger(); AtomicInteger max = new AtomicInteger(); TaskProgress progress = new TaskProgress(task) { @Override public void updateProgress(final int workDone, final int maxWork) { called.incrementAndGet(); done.set(workDone); max.set(maxWork); } @Override public void updateMessage(final String message) { throw new UnsupportedOperationException("#updateMessage()"); } @Override public void cancel() { throw new UnsupportedOperationException("#cancel()"); } }; assertEquals(0, task.getWorkDone()); assertEquals(0, task.getMax()); assertEquals(0, called.get()); assertEquals(task.getWorkDone(), done.get()); assertEquals(task.getMax(), max.get()); task.updateProgress(1, 3); assertEquals(1, task.getWorkDone()); assertEquals(3, task.getMax()); assertEquals(1, called.get()); assertEquals(task.getWorkDone(), done.get()); assertEquals(task.getMax(), max.get()); task.execute(); assertEquals(2, task.getWorkDone()); assertEquals(4, task.getMax()); assertEquals(2, called.get()); assertEquals(task.getWorkDone(), done.get()); assertEquals(task.getMax(), max.get()); } @Test public void updateMessage() throws Exception { Task<?> task = new Task<Object>("foo") { @Override public boolean cancelable() { throw new UnsupportedOperationException("#cancelable()"); } @Override public Void execute() { updateMessage("execute in"); return null; } }; AtomicInteger called = new AtomicInteger(); AtomicReference<String> message = new AtomicReference<>(); TaskProgress progress = new TaskProgress(task) { @Override public void updateProgress(final int done, final int max) { throw new UnsupportedOperationException("#updateProgress()"); } @Override public void updateMessage(final String messageStr) { called.incrementAndGet(); message.set(messageStr); } @Override public void cancel() { throw new UnsupportedOperationException("#cancel()"); } }; assertNull(task.getMessage()); assertEquals(0, called.get()); assertNull(message.get()); task.updateMessage("execute out"); assertEquals("execute out", task.getMessage()); assertEquals(1, called.get()); assertEquals(task.getMessage(), message.get()); task.execute(); assertEquals("execute in", task.getMessage()); assertEquals(2, called.get()); assertEquals(task.getMessage(), message.get()); } @Test public void cancel() throws Exception { Task<?> task = new Task<Object>("foo") { @Override public boolean cancelable() { return true; } @Override public Void execute() throws TaskInterruptedException { if (isCanceled()) { throw new TaskInterruptedException(); } return null; } }; AtomicInteger called = new AtomicInteger(); AtomicBoolean canceled = new AtomicBoolean(); TaskProgress progress = new TaskProgress(task) { @Override public void updateProgress(final int done, final int max) { throw new UnsupportedOperationException("#updateProgress()"); } @Override public void updateMessage(final String message) { throw new UnsupportedOperationException("#updateMessage()"); } @Override public void cancel() { called.incrementAndGet(); canceled.set(true); } }; assertTrue(task.cancelable()); assertFalse(task.isCanceled()); assertEquals(0, called.get()); assertEquals(task.isCanceled(), canceled.get()); task.execute(); assertFalse(task.isCanceled()); assertEquals(0, called.get()); assertEquals(task.isCanceled(), canceled.get()); task.cancel(); assertTrue(task.isCanceled()); assertEquals(1, called.get()); assertEquals(task.isCanceled(), canceled.get()); try { task.execute(); fail("A TaskInterruptedException was expected"); } catch (TaskInterruptedException e) { // expected } } }
34.075
79
0.588114
19c172cca58b7dd3e5d5b742fa4668cb94f27ce4
6,519
package net.kyrptonaught.glassdoor; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.minecraft.block.*; import net.minecraft.client.render.RenderLayer; public class GlassDoorMod implements ModInitializer, ClientModInitializer { static final String MOD_ID = "glassdoor"; public static BlockGlassDoor oak_glassdoor; public static BlockGlassDoor spruce_glassdoor; public static BlockGlassDoor birch_glassdoor; public static BlockGlassDoor acacia_glassdoor; public static BlockGlassDoor jungle_glassdoor; public static BlockGlassDoor dark_oak_glassdoor; public static BlockGlassDoor iron_glassdoor; public static BlockGlassTrapDoor oak_glasstrapdoor; public static BlockGlassTrapDoor spruce_glasstrapdoor; public static BlockGlassTrapDoor birch_glasstrapdoor; public static BlockGlassTrapDoor acacia_glasstrapdoor; public static BlockGlassTrapDoor jungle_glasstrapdoor; public static BlockGlassTrapDoor dark_oak_glasstrapdoor; public static BlockGlassTrapDoor iron_glasstrapdoor; @Override public void onInitialize() { oak_glassdoor = new BlockGlassDoor(Block.Settings.copy(Blocks.OAK_DOOR), "oak_glassdoor"); spruce_glassdoor = new BlockGlassDoor(Block.Settings.copy(Blocks.SPRUCE_DOOR), "spruce_glassdoor"); birch_glassdoor = new BlockGlassDoor(Block.Settings.copy(Blocks.BIRCH_DOOR), "birch_glassdoor"); acacia_glassdoor = new BlockGlassDoor(Block.Settings.copy(Blocks.ACACIA_DOOR), "acacia_glassdoor"); jungle_glassdoor = new BlockGlassDoor(Block.Settings.copy(Blocks.JUNGLE_DOOR), "jungle_glassdoor"); dark_oak_glassdoor = new BlockGlassDoor(Block.Settings.copy(Blocks.DARK_OAK_DOOR), "dark_oak_glassdoor"); iron_glassdoor = new BlockGlassDoor(Block.Settings.copy(Blocks.IRON_DOOR), "iron_glassdoor"); oak_glasstrapdoor = new BlockGlassTrapDoor(Block.Settings.copy(Blocks.OAK_TRAPDOOR), "oak_glasstrapdoor"); spruce_glasstrapdoor = new BlockGlassTrapDoor(Block.Settings.copy(Blocks.SPRUCE_TRAPDOOR), "spruce_glasstrapdoor"); birch_glasstrapdoor = new BlockGlassTrapDoor(Block.Settings.copy(Blocks.BIRCH_TRAPDOOR), "birch_glasstrapdoor"); acacia_glasstrapdoor = new BlockGlassTrapDoor(Block.Settings.copy(Blocks.ACACIA_TRAPDOOR), "acacia_glasstrapdoor"); jungle_glasstrapdoor = new BlockGlassTrapDoor(Block.Settings.copy(Blocks.JUNGLE_TRAPDOOR), "jungle_glasstrapdoor"); dark_oak_glasstrapdoor = new BlockGlassTrapDoor(Block.Settings.copy(Blocks.DARK_OAK_TRAPDOOR), "dark_oak_glasstrapdoor"); iron_glasstrapdoor = new BlockGlassTrapDoor(Block.Settings.copy(Blocks.IRON_TRAPDOOR), "iron_glasstrapdoor"); } @Override public void onInitializeClient() { BlockRenderLayerMap.INSTANCE.putBlock(oak_glassdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(spruce_glassdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(birch_glassdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(acacia_glassdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(jungle_glassdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(dark_oak_glassdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(iron_glassdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(oak_glasstrapdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(spruce_glasstrapdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(birch_glasstrapdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(acacia_glasstrapdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(jungle_glasstrapdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(dark_oak_glasstrapdoor, RenderLayer.getCutout()); BlockRenderLayerMap.INSTANCE.putBlock(iron_glasstrapdoor, RenderLayer.getCutout()); } public static BlockState copyState(BlockState copyState) { if (!(copyState.getBlock() instanceof DoorBlock)) return copyState; BlockState newState = oak_glassdoor.getDefaultState(); if (copyState.getBlock().equals(Blocks.JUNGLE_DOOR)) newState = jungle_glassdoor.getDefaultState(); else if (copyState.getBlock().equals(Blocks.BIRCH_DOOR)) newState = birch_glassdoor.getDefaultState(); else if (copyState.getBlock().equals(Blocks.SPRUCE_DOOR)) newState = spruce_glassdoor.getDefaultState(); else if (copyState.getBlock().equals(Blocks.ACACIA_DOOR)) newState = acacia_glassdoor.getDefaultState(); else if (copyState.getBlock().equals(Blocks.DARK_OAK_DOOR)) newState = dark_oak_glassdoor.getDefaultState(); else if (copyState.getBlock().equals(Blocks.IRON_DOOR)) newState = iron_glassdoor.getDefaultState(); return newState.with(DoorBlock.FACING, copyState.get(DoorBlock.FACING)).with(DoorBlock.HINGE, copyState.get(DoorBlock.HINGE)).with(DoorBlock.OPEN, copyState.get(DoorBlock.OPEN)); } public static BlockState copytrapdoorState(BlockState copyState) { if (!(copyState.getBlock() instanceof TrapdoorBlock)) return copyState; BlockState newState = oak_glasstrapdoor.getDefaultState(); if (copyState.getBlock().equals(Blocks.JUNGLE_TRAPDOOR)) newState = jungle_glasstrapdoor.getDefaultState(); else if (copyState.getBlock().equals(Blocks.BIRCH_TRAPDOOR)) newState = birch_glasstrapdoor.getDefaultState(); else if (copyState.getBlock().equals(Blocks.SPRUCE_TRAPDOOR)) newState = spruce_glasstrapdoor.getDefaultState(); else if (copyState.getBlock().equals(Blocks.ACACIA_TRAPDOOR)) newState = acacia_glasstrapdoor.getDefaultState(); else if (copyState.getBlock().equals(Blocks.DARK_OAK_TRAPDOOR)) newState = dark_oak_glasstrapdoor.getDefaultState(); else if (copyState.getBlock().equals(Blocks.IRON_TRAPDOOR)) newState = iron_glasstrapdoor.getDefaultState(); return newState.with(TrapdoorBlock.FACING, copyState.get(TrapdoorBlock.FACING)).with(TrapdoorBlock.OPEN, copyState.get(TrapdoorBlock.OPEN)).with(TrapdoorBlock.HALF, copyState.get(TrapdoorBlock.HALF)).with(TrapdoorBlock.POWERED, copyState.get(TrapdoorBlock.POWERED)).with(TrapdoorBlock.WATERLOGGED, copyState.get(TrapdoorBlock.WATERLOGGED)); } }
71.637363
348
0.782482
d0b1dab3e863432f7d2337025114bfa169398b6f
1,875
/* * Copyright (c) 2013 Vwazen Nou * All rights reserved. */ package org.vwazennou.mrs.formulary; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "formulary_tuples") public class FormularyTuple { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", nullable = false) private int id; @ManyToOne @JoinColumn(name = "treatment_id", nullable = false) private FormularyEntry treatment; @ManyToOne @JoinColumn(name = "dosage_id", nullable = false) private FormularyEntry dosage; @ManyToOne @JoinColumn(name = "form_id") private FormularyEntry form; public FormularyTuple() { // Default constructor provided for Hibernate } public FormularyTuple(FormularyEntry treatment, FormularyEntry dosage, FormularyEntry form) { if (treatment == null || dosage == null) { System.out.println("huh?"); } this.treatment = treatment; this.dosage = dosage; this.form = form; } public int getId() { return id; } public FormularyEntry getTreatment() { return treatment; } public FormularyEntry getDosage() { return dosage; } public FormularyEntry getForm() { return form; } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof FormularyTuple)) { return false; } FormularyTuple ft = (FormularyTuple) obj; return getTreatment().equals(ft.getTreatment()) && getDosage().equals(ft.getDosage()) && getForm().equals(ft.getForm()); } @Override public int hashCode() { return (getTreatment().hashCode() * 31 + getDosage().hashCode()) * 31 + getForm().hashCode(); } }
27.173913
95
0.705067
557aa2ee068d2a7ef4a5444a250f89fcddb62ced
717
/* * 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 practice; /** * * @author prakash */ public class cmd2 { public static void main(String[] args) { int count=0; for(int i=0;i<args.length;i++) { try { int n=Integer.parseInt(args[i]); } catch(Exception e) { count++; } } System.out.println("Total valid integers: " + (args.length - count)); System.out.println("Total invalid integers: " + count); } }
22.40625
79
0.524407
160c24c1de7d621b2d1f1418405edf6e39622ebe
6,387
/** * a small, limited port of Python's Struct, based on java.nio.ByteBuffer * @author zigliolie - Copyright Sirtrack Ltd. * */ package com.sirtrack.construct; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; /** Functions to convert between Python values and C structs. Python strings are used to hold the data representing the C struct and also as format strings to describe the layout of data in the C struct. The optional first format char indicates byte order, size and alignment: @: native order, size & alignment (default) =: native order, std. size & alignment <: little-endian, std. size & alignment >: big-endian, std. size & alignment !: same as > The remaining chars indicate types of args and must match exactly; these can be preceded by a decimal repeat count: x: pad byte (no data); c:char; b:signed byte; B:unsigned byte; h:short; H:unsigned short; i:int; I:unsigned int; l:long; L:unsigned long; f:float; d:double. Special cases (preceding decimal count indicates length): s:string (array of char); p: pascal string (with count byte). Special case (only available in native format): P:an integer type that is wide enough to hold a pointer. Special case (not in native mode unless 'long long' in platform C): q:long long; Q:unsigned long long Whitespace between formats is ignored. The variable struct.error is an exception raised on errors. * */ public class Packer<T extends Number> { static public class StructError extends RuntimeException{ public StructError( String err ){ super(err); } } char fmt; char endianity; public Packer( char endianity, char fmt ) { this.endianity = endianity; this.fmt = fmt; } public T unpack( ByteBuffer buf ) { ArrayList<Object> result = new ArrayList<Object>(); Object obj; if( endianity == '>' ) buf.order( ByteOrder.BIG_ENDIAN ); // optional, the initial order of a byte buffer is always BIG_ENDIAN. else if( endianity == '<' ) buf.order( ByteOrder.LITTLE_ENDIAN ); else if( endianity == '=' ) buf.order( ByteOrder.nativeOrder() ); switch( fmt ){ case 'b': case 's': case 'p': obj = new Integer(buf.get()); break; case 'B': case 'C': byte b = buf.get(); if( b<0 ) obj = 256 + b; else obj = new Integer(b); break; case 'h': obj = new Integer(buf.getShort()); break; case 'H': short s = buf.getShort(); if( s<0 ) obj = 65536 + s; else obj = new Integer(s); break; case 'i': case 'l': obj = buf.getInt(); break; case 'I': case 'L': int i = buf.getInt(); // not sure here, somewhere we make assumptions that all returned numbers are int if( i<0 ) obj = 4294967296L + i; else obj = new Integer(i); break; case 'q': obj = buf.getLong(); break; case 'Q': throw new RuntimeException("Java doesn't have 64 bit unsigned types (or 128 signed...)"); default: throw new StructError( "unrecognized fmt " + fmt); } return (T)obj; } static public byte getByte( Object obj ){ if( obj instanceof Byte ) return( (Byte)obj ); else if( obj instanceof Short && (Short)obj < 256 ){ return (byte)((Short)obj & 0xFF); } else if( obj instanceof Integer && (Integer)obj < 256 ){ return (byte)((Integer)obj & 0xFF); } throw new RuntimeException( "type not supported " + obj ); } static public short getShort( Object obj ){ if( obj instanceof Short ){ return( (Short)obj ); } else if( obj instanceof Integer && (Integer)obj < 65536 ){ return (short)((Integer)obj & 0xFFFF ); } throw new RuntimeException( "type not supported " + obj ); } static public int getInt( Object obj ){ if( obj instanceof Integer ){ return( (Integer)obj ); } else if( obj instanceof Long && (Long)obj < 4294967296L ){ return (int)((Long)obj - 4294967296L ); } throw new RuntimeException( "type not supported " + obj ); } static public long getLong( Object obj ){ if( obj instanceof Long ){ return( (long)obj ); } if( obj instanceof Integer ){ return( (long)((int)obj) ); } throw new RuntimeException( "type not supported " + obj ); } /* * @return Return byte[] containing value v packed according to fmt. */ public byte[] pack( Object obj ) { ByteBuffer b = ByteBuffer.allocate( length() ); if( endianity == '>' ) b.order( ByteOrder.BIG_ENDIAN ); // optional, the initial order of a byte buffer is always BIG_ENDIAN. else if( endianity == '<' ) b.order( ByteOrder.LITTLE_ENDIAN ); else if( endianity == '=' ) b.order( ByteOrder.nativeOrder() ); switch( fmt ){ case 'b': case 's': case 'p': b.put( getByte(obj) ); break; case 'B': case 'C': b.put( getByte(obj) ); break; case 'h': b.putShort( getShort(obj) ); break; case 'H': b.putShort( getShort(obj) ); break; case 'i': case 'l': // if( obj instanceof Integer ) b.putInt( (Integer)obj ); break; case 'I': case 'L': // if( obj instanceof Integer ) b.putInt( getInt(obj) ); break; case 'q': b.putLong( getLong(obj) ); break; case 'Q': throw new RuntimeException("Java doesn't have 64 bit unsigned types (or 128 signed...)"); default: throw new StructError( "unrecognized fmt " + fmt); } return Arrays.copyOf( b.array(), b.position() ); } public int length(){ int len = 0; switch( fmt ){ case 'b': case 'B': case 'C': case 's': case 'p': len = 1; break; case 'h': case 'H': len = 2; break; case 'i': case 'I': case 'l': case 'L': len = 4; break; case 'q': case 'Q': len = 8; break; default: throw new StructError( "unrecognized fmt " + fmt ); } return len; } }
24.377863
112
0.571786
48cd79e533acf02c0bfa2619dd9e3743a74d985c
2,841
package server; import dh.KeyExchange; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import static utils.CryptChatUtils.*; public class Server implements Runnable { private ServerResponse serverResponse; private ClientHandler clientHandler; private int port; private ServerSocket serverSocket; private Socket socket; private KeyExchange keyExchange; public void openConnection(int port) throws IOException { this.port = port; serverSocket = new ServerSocket(port); serverResponse.notifyConnectionOpen(); } public void setPort(int port) { this.port = port; } public void setServerResponse(ServerResponse serverResponse) { this.serverResponse = serverResponse; } public void handleClient(){ initKeyExchange(); clientHandler = new ClientHandler(socket, serverResponse); clientHandler.setKeyExchange(keyExchange); clientHandler.start(); } public void generateNewKey() { initKeyExchange(); clientHandler.requestNewKey(); } @Override public void run() { try { openConnection(port); acceptConnection(); } catch (IOException e) { e.printStackTrace(); } serverResponse.notifyConnectionEstablished(); handleClient(); } private void acceptConnection() throws IOException { this.socket = serverSocket.accept(); } public void sendMessage(String message){ clientHandler.sendMessage(ENCRYPTED_MESSAGE, PROTOCOL_SEPARATOR, message); } public void initKeyExchange(){ this.keyExchange = new KeyExchange(); keyExchange.init(); } /** * * @param message the message to decrypt */ public void decryptMessage(String message) { String decrypted; try { decrypted = decrypt(message, clientHandler.getKeyExchange().getAESKey()); serverResponse.showDecryptedMessage(decrypted); } catch (Exception e) { e.printStackTrace(); } } public void encryptMessage(String message) { String encrypted; try { encrypted = encrypt(message, clientHandler.getKeyExchange().getAESKey()); serverResponse.showEncryptedMessage(encrypted); } catch (Exception e) { e.printStackTrace(); } } public interface ServerResponse{ void notifyConnectionOpen(); void notifyMessageReceived(); void showEncryptedMessage(String s); void showDecryptedMessage(String s); void showMessageReceived(String s); void showPrivateKey(String s); void showErrorMessage(String s); void notifyConnectionEstablished(); } }
23.675
85
0.63886
0ad4218534cf473e3773ea3a551876cca8598dbe
4,850
/* * Copyright 2016 Michel Vollebregt * * 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.github.mvollebregt.wildmock.test.feedback; import com.github.mvollebregt.wildmock.api.MethodCall; import com.github.mvollebregt.wildmock.exceptions.VerifyClauseNotSatisfiedException; import com.github.mvollebregt.wildmock.test.helpers.ArbitraryWildcardsMockClass; import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import static com.github.mvollebregt.wildmock.Wildmock.mock; import static com.github.mvollebregt.wildmock.Wildmock.verify; import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.*; @SuppressWarnings("ThrowableResultOfMethodCallIgnored") public class VerifyClauseNotSatisfiedExceptionTest { private ArbitraryWildcardsMockClass mock = mock(ArbitraryWildcardsMockClass.class); @Test public void testPartialMatch() throws Exception { // when mock.actionA("first call"); VerifyClauseNotSatisfiedException exception = expectThrows(VerifyClauseNotSatisfiedException.class, () -> verify(() -> { mock.actionA("first call"); mock.actionA("second call"); })); System.out.println(exception.getMessage()); assertEquals(singletonList(actionA("first call")), exception.getClosestMatch().getObservedMethodCalls()); assertNull(exception.getClosestMatch().getMismatchedMethodCall()); assertEquals(singletonList(actionA("second call")), exception.getClosestMatch().getRemainingMethodCalls()); } @Test public void testWrongArgument() throws Exception { // when mock.actionA("unexpected argument"); VerifyClauseNotSatisfiedException exception = expectThrows(VerifyClauseNotSatisfiedException.class, () -> verify(() -> mock.actionA("expected argument"))); System.out.println(exception.getMessage()); assertEquals(actionA("unexpected argument"), exception.getClosestMatch().getMismatchedMethodCall()); assertEquals(singletonList(actionA("expected argument")), exception.getClosestMatch().getRemainingMethodCalls()); } @Test public void testWrongMethod() throws Exception { // when mock.actionAB(null, null); VerifyClauseNotSatisfiedException exception = expectThrows(VerifyClauseNotSatisfiedException.class, () -> verify(() -> mock.actionA("expected argument"))); System.out.println(exception.getMessage()); assertEquals(actionAB(null, null), exception.getClosestMatch().getMismatchedMethodCall()); } @Test public void testWrongArgumentTwice() throws Exception { // when: action is called with wrong argument twice mock.actionA("unexpected 1"); mock.actionA("unexpected 2"); VerifyClauseNotSatisfiedException exception = expectThrows(VerifyClauseNotSatisfiedException.class, () -> verify(() -> mock.actionA("expected argument"))); // then: the first argument is registered as closest match assertEquals(actionA("unexpected 1"), exception.getClosestMatch().getMismatchedMethodCall()); } @Test public void testWrongMethodThenWrongArgument() throws Exception { // when: action is called with wrong method and then with wrong argument mock.actionAB(null, null); mock.actionA("unexpected argument"); VerifyClauseNotSatisfiedException exception = expectThrows(VerifyClauseNotSatisfiedException.class, () -> verify(() -> mock.actionA("expected argument"))); // then: the closest call is registered as closest match assertEquals(actionA("unexpected argument"), exception.getClosestMatch().getMismatchedMethodCall()); } private MethodCall actionA(String argument) throws Exception { Method actionA = ArbitraryWildcardsMockClass.class.getMethod("actionA", Object.class); return new MethodCall(mock, actionA, new Object[]{argument}, null); } private MethodCall actionAB(String arg1, String arg2) throws Exception { Method actionAB = ArbitraryWildcardsMockClass.class.getMethod("actionAB", Object.class, Object.class); return new MethodCall(mock, actionAB, new Object[]{arg1, arg2}, null); } }
46.190476
121
0.717113
6fa3bb72dae81ae19626ff325f8c0d7934f63002
828
package io.smsc.jwt.service; import io.smsc.jwt.service.impl.JWTTokenGenerationServiceImpl; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.Map; /** * This interface is describing methods to provide JWT authentication service. * Methods implementation is in {@link JWTTokenGenerationServiceImpl} * * @author Nazar Lipkovskyy * @since 0.0.1-SNAPSHOT */ public interface JWTTokenGenerationService extends Serializable { String getUsernameFromToken(String token); String generateAccessToken(UserDetails userDetails); String generateRefreshToken(UserDetails userDetails); String generateAccessToken(Map<String, Object> claims); String generateRefreshToken(Map<String, Object> claims); }
28.551724
78
0.799517
3a4c4b753b717dae6d2f888eecefffc7a63f6d55
1,992
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.modules.grade.model; import java.math.BigDecimal; import org.olat.modules.grade.GradeScale; import org.olat.modules.grade.GradeSystem; import org.olat.repository.RepositoryEntry; /** * * Initial date: 10 Mar 2022<br> * @author uhensler, [email protected], http://www.frentix.com * */ public class GradeScaleWrapper implements GradeScale { private BigDecimal minScore; private BigDecimal maxScore; private GradeSystem gradeSystem; @Override public Long getKey() { return null; } @Override public BigDecimal getMinScore() { return minScore; } @Override public void setMinScore(BigDecimal minScore) { this.minScore = minScore; } @Override public BigDecimal getMaxScore() { return maxScore; } @Override public void setMaxScore(BigDecimal maxScore) { this.maxScore = maxScore; } @Override public GradeSystem getGradeSystem() { return gradeSystem; } @Override public void setGradeSystem(GradeSystem gradeSystem) { this.gradeSystem = gradeSystem; } @Override public RepositoryEntry getRepositoryEntry() { return null; } @Override public String getSubIdent() { return null; } }
23.162791
82
0.725904
62bbfa64e77eae935e5a1eb3e9c68c5bed24e0e4
647
package im.silen.vueboot.util; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static im.silen.vueboot.util.StringUtil.stripWhitespace; class StringUtilTest { @Test void stripWhitespace1() { Assertions.assertEquals(stripWhitespace(" \u202a \nhello \n world \n "), "hello \n world"); Assertions.assertEquals(stripWhitespace("hello world\t"), "hello world"); Assertions.assertEquals(stripWhitespace(" \u202e\nhello\u202bworld"), "hello\u202bworld"); Assertions.assertEquals(stripWhitespace("\n \t \nhello world ! \u202e\n "), "hello world !"); } }
40.4375
111
0.692427
5a47db7dc113e446ee041e8c5c2f5e300133eaa0
1,185
package it.secretbasium.bns.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import it.secretbasium.bns.dal.GiftDAO; import it.secretbasium.bns.entities.Gift; @Service public class GiftServiceImpl implements GiftService { @Autowired private GiftDAO repo; @Override public List<Gift> getAllGifts() { return repo.findAll(); } @Override public Gift getGiftById(String id) { return repo.findById(id).get(); } @Override public Gift addGift(Gift gift) { return repo.save(gift); } @Override public Gift updateGift(Gift gift) { return repo.save(gift); } @Override public void deleteGift(String id) { repo.deleteById(id); } @Override public List<Gift> findByGroupId(String groupId) { return repo.findByGroupId(groupId); } @Override public List<Gift> findByBasium(String basium) { return repo.findByBasiumId(basium); } @Override public List<Gift> findByBabbo(String babbo) { return repo.findByBabboId(babbo); } }
19.42623
62
0.664135
452c33c693783e86ee2dcfee72bf09e80307b9ce
294
package com.common.jdk.desginpattern.bridge; /** * <p> * </p> * * @author zhoucg * @date 2019-11-05 9:41 */ public class ConcreteImplementorA implements Implementor{ @Override public void OperationImpl() { System.out.println("具体实现化(Concrete Implementor)角色被访问" ); } }
18.375
64
0.663265
c0ea4d588641224fe337039be0aedbf99c30afcf
218
package game; public interface GameField { void markPosition(int i, int j, char signOfMark); char getPosition(int i, int j); boolean getIsMarked(int i, int j); boolean isFilled(); int getSize(); }
21.8
53
0.674312
7f53cde533fbd0558a477f5815bc090909ac988b
20,473
package hu.juhdanad.neonjumper; import java.util.Arrays; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.Screen; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; /** * Created by danika on 2015.09.18.. */ public class GameScreen implements Screen { /** * Impossible mode on/off */ public boolean impossible; /** * counts the time until respawn */ private float deathCooldown; /** * parent Game object */ private Launcher parent; /** * the game's texture */ private Texture sprites; /** * the ball's position on the texture */ private TextureRegion ball; /** * the wall's position on the texture */ private TextureRegion wall; /** * the spike's position on the texture */ private TextureRegion spike; /** * the checkpoint's position on the texture */ private TextureRegion checkpoint; /** * the slower's position on the texture */ private TextureRegion slower; /** * the jumper's position on the texture */ private TextureRegion jumper; /** * the finish's position on the texture */ private TextureRegion finish; /** * the sprite batch to draw */ private SpriteBatch batch; enum Tile { EMPTY, WALL, SPIKE, CHECKPOINT, CHECKPOINT_ACTIVE, SLOW, UP, FINISH } /** * the array storing the level. */ private Tile[][] level; /** * ball's x coordinate */ private float bobX; /** * ball's y coordinate */ private float bobY; /** * ball's y velocity */ private float bobYVel; /** * is the game over? */ private boolean gameOver; /** * Does the player jumping? */ private boolean jumpIntent; /** * can the player jump? */ private boolean canJump; /** * the ball's current direction */ private boolean leftDirection; /** * leftDirection after death */ private boolean startLeftDirection; /** * the respawn x coordinate */ private float startX; /** * the respawn y coordinate */ private float startY; /** * the level start x coordinate */ private float originalStartX = 5; /** * the level start y coordinate */ private float originalStartY = 5; /** * the ball's x velocity */ private float bobXVel; /** * the death counter */ private int deathCount; /** * the x coordinate of the camera's bottom left corner */ private float cameraX; /** * the y coordinate of the camera's bottom left corner */ private float cameraY; /** * is respawn counter running? */ private boolean dying; /** * slower effect countdown */ private float slowTime; /** * time multiplier, used by slowdown effect */ private float timeMulti; /** * is the player winning? */ private boolean win; public float light; public GameScreen(Launcher parent) { this.parent = parent;// set parent FileHandle leveltext = Gdx.files.internal("level.txt"); String levelstr = leveltext.readString(); batch = new SpriteBatch();// create batch sprites = new Texture(Gdx.files.internal("GameSprites.png"));// load texture TextureRegion[][] textures = TextureRegion.split(sprites, 128, 128);// create texture regions ball = textures[0][0]; wall = textures[1][0]; spike = textures[0][1]; checkpoint = textures[1][1]; slower = textures[0][2]; jumper = textures[1][2]; finish = textures[0][3]; level = new Tile[300][30];// create level array for(int x=0;x<level.length;x++){ for(int y=0;y<level[x].length;y++){ level[x][y]=Tile.EMPTY; } } int x = 0; int y = 29; for (int i = 0; i < levelstr.length(); i++) { switch (levelstr.charAt(i)) { case '*': level[x][y] = Tile.SPIKE; break; case 'O': level[x][y] = Tile.WALL; break; case 'C': level[x][y] = Tile.CHECKPOINT; break; case '8': level[x][y] = Tile.SLOW; break; case 'S': // start originalStartX = x + 0.5f; originalStartY = y + 0.5f; break; case '^': level[x][y] = Tile.UP; break; case 'F': level[x][y] = Tile.FINISH; break; case '\n': x = -1; y--; break; } x++; } } /** * reset original values */ public void reset() { light = 0; startX = originalStartX; startY = originalStartY; bobX = startX; bobY = startY; bobXVel = 0f; bobYVel = 0f; startLeftDirection = false; leftDirection = false; jumpIntent = false; cameraX = 0; cameraY = 0; deathCooldown = 1; deathCount = 0; timeMulti = 1; win = false; dying = false; } /** * set input when active */ @Override public void show() { Gdx.input.setInputProcessor(new InputMultiplexer(new InputAdapter() { @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { jumpIntent = true; return false;// pass event to parent's touchDown } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { jumpIntent = false; return false;// pass event to input's touchUp } @Override public boolean keyDown(int keycode) { jumpIntent = true; return false; } @Override public boolean keyUp(int keycode) { jumpIntent = false; return false; } }, parent.inAd)); } /** * render to screen * * @param delta time in seconds since last render */ @Override public void render(float delta) { if (slowTime > 0) {// if should slow down timeMulti += (0.25f - timeMulti) * delta * 4;// let time flow a bit slower if it is too fast slowTime -= delta;// decease the slowdown duration if (slowTime < 0) { slowTime = 0; } } else { timeMulti += (1 - timeMulti) * delta;// let the time flow faster if it is slow } delta *= timeMulti;// modify delta time gameStep(Math.min(delta, 0.1f));// game stuff Gdx.gl.glClearColor(0, 0, 0, 1);// clear screen Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); parent.camera.update();// update cameras parent.textCamera.update(); batch.setProjectionMatrix(parent.camera.combined);// activate normal camera batch.begin();// activate batch float goalCameraX = bobX + bobXVel * 0.6f - 6.5f;// where should the camera look at float goalCameraY = bobY + bobYVel * 0.1f - 4; cameraX += (goalCameraX - cameraX) * delta * 6;// follow camera's goal cameraY += (goalCameraY - cameraY) * delta * 6; if (cameraY < 0) {// don't let the camera go under the level's border cameraY = 0; } int minDrawX = Math.max((int) (cameraX), 0);// which tiles to draw int maxDrawX = Math.min((int) (cameraX + 13), level.length - 1); int minDrawY = Math.max((int) (cameraY), 0); int maxDrawY = Math.min((int) (cameraY + 8), level[0].length - 1); for (int tilex = minDrawX; tilex <= maxDrawX; tilex++) {// for every drawn tile for (int tiley = minDrawY; tiley <= maxDrawY; tiley++) { if (level[tilex][tiley] != Tile.EMPTY) {// if not air, draw float alpha = 1;// calculate alpha if (tilex - cameraX > 11) { alpha *= Math.max(1 - (tilex - cameraX - 11) / 2f, 0); } else if (tilex - cameraX < 1) { alpha *= Math.max(1 - (1 - tilex + cameraX) / 2f, 0); } if (tiley - cameraY > 7) { alpha *= Math.max(8 - tiley + cameraY, 0); } else if (tiley - cameraY < 0) { alpha *= Math.max(1 + tiley - cameraY, 0); } batch.setColor(1, 1, 1, alpha); switch (level[tilex][tiley]) {// draw tile case WALL: batch.draw(wall, tilex - cameraX, tiley - cameraY, 1, 1); break; case SPIKE: batch.draw(spike, tilex - cameraX, tiley - cameraY, 1, 1); break; case CHECKPOINT: batch.setColor(1, 1, 1, alpha / 2f); batch.draw(checkpoint, tilex - cameraX, tiley - cameraY, 1, 1); batch.setColor(1, 1, 1, alpha); break; case CHECKPOINT_ACTIVE: batch.draw(checkpoint, tilex - cameraX, tiley - cameraY, 1, 1); break; case SLOW: if (!impossible) {// if impossible, there are nop slowers batch.draw(slower, tilex - cameraX, tiley - cameraY, 1, 1); } break; case UP: batch.draw(jumper, tilex - cameraX, tiley - cameraY, 1, 1); break; case FINISH: batch.draw(finish, tilex - cameraX, tiley - cameraY, 1, 1); break; default: break; } } } } if (dying) { if (deathCooldown < 0.5f) {// draw popping ball batch.setColor(1, 1, 1, 1 - 2 * deathCooldown); float size = deathCooldown; batch.draw(ball, bobX - 0.5f - cameraX - size, bobY - 0.5f - cameraY - size, 1 + 2 * size, 1 + 2 * size); batch.setColor(1, 1, 1, 1); } } else {// draw normal ball batch.setColor(1, 1, 1, 1); batch.draw(ball, bobX - 0.5f - cameraX, bobY - 0.5f - cameraY, 1, 1); } batch.setProjectionMatrix(parent.textCamera.combined);// change to text rendering parent.font.draw(batch, "Deaths: " + deathCount, 10, 150);// draw death count batch.end();// draw everything } /** * te game step * * @param delta elapsed time since last call in seconds */ private void gameStep(float delta) { if (win) {// if player won, show the win screen and tell it if the game impossible was parent.showWin(impossible); return; } if (gameOver) {// if game is over gameOver = false; dying = true;// set death cooldown deathCooldown = 0; deathCount++; bobYVel = 0; bobXVel = 0; slowTime = 0; } if (dying) { if (deathCooldown < 1) { deathCooldown += delta; } else {// if end of dying dying = false; deathCooldown = 1; bobY = startY;// reset position bobX = startX; leftDirection = startLeftDirection; if (impossible) {// if impossible, reset checkpoints for (int x = 0; x < 300; x++) { for (int y = 0; y < 30; y++) { if (level[x][y] == Tile.CHECKPOINT_ACTIVE) { level[x][y] = Tile.CHECKPOINT; } } } } } return;// do not run game step } canJump = false; bobYVel -= 100f * delta;// gravity if (leftDirection) {// horizontal acceleration to 8 tile/sec if (bobXVel > -8) { bobXVel -= 10f * delta; if (bobXVel < -8) { bobXVel = -8; } } } else { if (bobXVel < 8) { bobXVel += 10f * delta; if (bobXVel > 8) { bobXVel = 8; } } } float bobNewX = bobX + bobXVel * delta;// calculate new position float bobNewY = bobY + bobYVel * delta; int minInteractX = Math.max((int) (bobNewX - 1), 0);// calculate tiles which the ball interact with int maxInteractX = Math.min((int) (bobNewX + 1), level.length - 1); int minInteractY = Math.max((int) (bobNewY - 1), 0); int maxInteractY = Math.min((int) (bobNewY + 1), level[0].length - 1); for (int interactX = minInteractX; interactX <= maxInteractX; interactX++) {// for every tile for (int interactY = minInteractY; interactY <= maxInteractY; interactY++) { float deltaX = bobNewX - interactX - 0.5f; float deltaY = bobNewY - interactY - 0.5f; switch (level[interactX][interactY]) { case WALL: if (bobY - interactY >= 1.3f) {// if the ball was above if (deltaX <= 0.5f && deltaX >= -0.5f) { if (deltaY < 1) {// keep the ball above the tile bobNewY = interactY + 1.5f; bobYVel = Math.max(0, bobYVel); canJump = true;// can jump from this } } else if (deltaX < -0.5f) {// let the ball roll onto the tile float dx2 = deltaX + 0.5f; float minY = 0.5f + (float) Math.sqrt(Math.max(0, 0.25f - dx2 * dx2)); if (deltaY < minY) { bobNewY = interactY + 0.5f + minY; bobYVel = Math.max(1.5f, bobYVel); canJump = true; } } else if (deltaX > 0.5f) {// let the ball roll down from the tile float dx2 = deltaX - 0.5f; float minY = 0.5f + (float) Math.sqrt(Math.max(0, 0.25f - dx2 * dx2)); if (deltaY < minY) { bobNewY = interactY + 0.5f + minY; bobYVel = Math.max(0, bobYVel); canJump = true; } } } else if (bobY - interactY <= -0.2f) {// if the ball was under the tile if (deltaX <= 0.5f && deltaX >= -0.5f) {// keep it under the tile if (deltaY > -1) { bobNewY = interactY - 0.5f; bobYVel = Math.min(0, bobYVel); } } else if (deltaX < -0.5f) {// roll stuff float dx2 = deltaX - 0.5f; float minY = -0.5f - (float) Math.sqrt(Math.max(0, 0.25f - dx2 * dx2)); if (deltaY > minY) { bobNewY = interactY + 0.5f + minY; bobYVel = Math.min(-1.5f, bobYVel); } } else if (deltaX > 0.5f) {// roll stuff float dx2 = deltaX - 0.5f; float minY = -0.5f - (float) Math.sqrt(Math.max(0, 0.25f - dx2 * dx2)); if (deltaY > minY) { bobNewY = interactY + 0.5f + minY; } } } else {// frontal collision if (deltaX < 0.5f && deltaX > -0.5f) {// if the ball collides gameOver = true;// die } } break; case SPIKE: if (deltaX * deltaX + deltaY * deltaY < 0.8f) {// if ball is in radius gameOver = true;// die } break; case CHECKPOINT: if (deltaX * deltaX + deltaY * deltaY < 0.8f) {// if ball is in radius leftDirection = !leftDirection;// change direction level[interactX][interactY] = Tile.CHECKPOINT_ACTIVE;// activate if (!impossible) {// if checkpoints work startLeftDirection = leftDirection;// set respawn startX = interactX + 0.5f; startY = interactY + 0.5f; } } break; case SLOW: if (!impossible) { if (deltaX * deltaX + deltaY * deltaY < 0.8f) { slowTime = 20;// set slowdown effect to 20 sec } } break; case UP: if (deltaX * deltaX + deltaY * deltaY < 0.8f) {// if in radius canJump = true;// can jump } break; case FINISH: if (deltaX * deltaX + deltaY * deltaY < 0.8f) { win = true; } break; default: break; } } } if (jumpIntent && canJump) {// if jump is successful bobYVel = 22; } bobX = bobNewX;// finalize movement bobY = bobNewY; if (bobY < -5) {// if the ball fell out of the level, the game ends gameOver = true; } } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { batch.dispose();// delete resources sprites.dispose(); } }
36.235398
108
0.430274
8ba501d438589cb1c23139038a74453a659dbe28
171
package com.github.serezhka.jap2lib.rtsp; public interface MediaStreamInfo { StreamType getStreamType(); enum StreamType { AUDIO, VIDEO } }
14.25
41
0.654971
f56d1d00ce21993866121843e60336a1d52e4040
1,790
package by.it.academy.elearning.model; import java.util.Objects; public class User { private Long id; private String userName; private String password; private String role; public User(Long id, String userName, String password, String role) { this.id = id; this.userName = userName; this.password = password; this.role = role; } public User(Long id, String userName, String password) { this.id = id; this.userName = userName; this.password = password; this.role = "user"; } public User() { } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return Objects.equals(id, user.id) && Objects.equals(userName, user.userName) && Objects.equals(role, user.role); } @Override public int hashCode() { return Objects.hash(id, userName, role); } @Override public String toString() { return "User{" + "userName='" + userName + '\'' + ", role='" + role + '\'' + '}'; } }
21.309524
73
0.544134
947c70223dd3f4b9d64a91d1740e3762a1c78d36
1,011
//,temp,MQTTMaxFrameSizeTest.java,94,121,temp,MQTTMaxFrameSizeTest.java,65,92 //,2 public class xxx { @Test(timeout = 30000) public void testFrameSizeNotExceededWorks() throws Exception { LOG.debug("Starting test on connector {} for frame size: {}", getProtocolScheme(), maxFrameSize); MQTT mqtt = createMQTTConnection(); mqtt.setClientId(getTestName()); mqtt.setKeepAlive((short) 10); mqtt.setVersion("3.1.1"); BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); final int payloadSize = maxFrameSize / 2; byte[] payload = new byte[payloadSize]; for (int i = 0; i < payloadSize; ++i) { payload[i] = 42; } try { connection.publish(getTopicName(), payload, QoS.AT_LEAST_ONCE, false); } catch (Exception ex) { fail("should not have thrown an exception"); } finally { connection.disconnect(); } } };
30.636364
105
0.605341
b69fe886c8faaeb7f05afcf7afcf10a7c07d6c51
641
package com.surroundrervouscat.astar; import java.awt.Point; public class Node implements Comparable<Node> { public Point point; // 坐标 public Node parent; // 父结点 public int G; // G:是个准确的值,是起点到当前结点的代价 public int H; // H:是个估值,当前结点到目的结点的估计代价 public Node(int x, int y) { this.point = new Point(x, y); } public Node(Point point, Node parent, int g, int h) { this.point = point; this.parent = parent; G = g; H = h; } @Override public int compareTo(Node o) { if (o == null) return -1; if (G + H > o.G + o.H) return 1; else if (G + H < o.G + o.H) return -1; return 0; } }
18.852941
55
0.591264
3bc473690219de60e5a163b628e3e61465a5ca2f
1,221
/** * Copyright 2012-2019 Wicked Charts (http://github.com/adessoAG/wicked-charts) * * 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 de.adesso.wickedcharts.highcharts.options; import java.io.Serializable; /** * This class is used to mark Highcharts feature which are not (yet) supported * by wicked-charts. If you need this feature, please post a feature request at * http://code.google.com/p/wicked-charts/issues/list. * * Do not use this class, since it's uses in the API are subject to change! * * @author Tom Hombergs ([email protected]) * */ @Deprecated public class DummyOption implements Serializable { private static final long serialVersionUID = 1L; }
34.885714
81
0.731368
bba6e51ec2ba88ebd01c658b9cbf1df1eb7cc28c
3,913
package com.github.tadukoo.util.map; import com.github.tadukoo.util.tuple.Pair; import java.util.Map; /** * A ManyToManyMap class that uses {@link HashMultiMap} as the backing {@link MultiMap} class. * * @author Logan Ferree (Tadukoo) * @version Alpha v.0.2 * @since Pre-Alpha */ public class HashManyToManyMap<K, V> extends ManyToManyMap<K, V>{ /** * Creates a new HashManyToManyMap where the backing HashMultiMap is constructed with * the default initial capacity (16) and the default load factor (0.75). */ public HashManyToManyMap(){ super(new HashMultiMap<>(), new HashMultiMap<>()); } /** * Creates a new HashManyToManyMap where the backing HashMultiMaps are constructed with * the specified initial capacity and the default load factor (0.75). * * @param initialCapacity The initial capacity of the backing HashMultiMaps */ public HashManyToManyMap(int initialCapacity){ super(new HashMultiMap<>(initialCapacity), new HashMultiMap<>(initialCapacity)); } /** * Creates a new HashManyToManyMap where the backing HashMultiMaps are constructed with * the specified initial capacity and load factor. * * @param initialCapacity The initial capacity of the backing HashMultiMaps * @param loadFactor The load factor of the backing HashMultiMaps */ public HashManyToManyMap(int initialCapacity, float loadFactor){ super(new HashMultiMap<>(initialCapacity, loadFactor), new HashMultiMap<>(initialCapacity, loadFactor)); } /** * Creates a new HashManyToManyMap where the given Pairs are loaded into the * map right away. * * @param entries A collection of key-value Pairs to be put in this ManyToManyMap */ @SafeVarargs public HashManyToManyMap(Pair<K, V>... entries){ super(new HashMultiMap<>(), new HashMultiMap<>(), entries); } /** * Creates a new HashManyToManyMap where the backing HashMultiMaps are constructed with * the same mappings as the specified Map. The HashMultiMap is created with * default load factor (0.75) and an initial capacity sufficient to hold * the mappings in the specified Map. * * @param map The Map whose mappings are to be placed in the backing HashMultiMaps */ public HashManyToManyMap(Map<K, V> map){ super(new HashMultiMap<>(), new HashMultiMap<>(), map); } /** * Creates a new HashManyToManyMap where the backing HashMultiMap is constructed with * the default initial capacity (16) and the default load factor (0.75). * <br> * The ManyToManyMap is then populated with the values present in the specified * MultiMap. * * @param multiMap The MultiMap whose mappings are to be placed in this ManyToManyMap */ public HashManyToManyMap(MultiMap<K, V> multiMap){ super(new HashMultiMap<>(), new HashMultiMap<>(), multiMap); } /** * Creates a new HashManyToManyMap where the backing HashMultiMap is constructed with * the default initial capacity (16) and the default load factor (0.75). * <br> * The ManyToManyMap is then populated with the values present in the specified * ManyToManyMap. * * @param manyToManyMap The ManyToManyMap whose mappings are to be placed in this ManyToManyMap */ public HashManyToManyMap(ManyToManyMap<K, V> manyToManyMap){ super(new HashMultiMap<>(), new HashMultiMap<>(), manyToManyMap); } /** * Compares the given object with this HashManyToManyMap for equality. * Returns true if the given object is also a HashManyToManyMap and the two * HashManyToManyMaps represent the same mappings. * If they're both HashManyToManyMaps, it will run {@link ManyToManyMap#equals} to compare them. * * @param o The object to be compared for equality with this HashManyToManyMap * @return true if the given object is equivalent to this HashManyToManyMap */ public boolean equals(Object o){ if(o instanceof HashManyToManyMap){ return super.equals(o); } return false; } }
34.628319
97
0.732686
62710891e18a25df1bba15bee8fc20deb732440c
631
package com.google.cloud.functions.invoker.testfunctions; import com.google.cloud.functions.HttpFunction; import com.google.cloud.functions.HttpRequest; import com.google.cloud.functions.HttpResponse; import java.util.stream.Collectors; public class Nested { public static class Echo implements HttpFunction { @Override public void service(HttpRequest request, HttpResponse response) throws Exception { String body = request.getReader().lines().collect(Collectors.joining("\n")); response.setContentType("text/plain"); response.getWriter().write(body); response.getWriter().flush(); } } }
33.210526
86
0.752773
f2967a2c34b5909a588d03de91b93f12f500381b
904
package roth.lib.java.jdbc.sql; @SuppressWarnings("serial") public abstract class Order extends Sql { protected String sql; protected String table; protected String name; protected String orderType = ASC; protected Order() { } public Order setSql(String sql) { this.sql = sql; return this; } public Order setTable(String table) { this.table = table; return this; } public Order setName(String name) { this.name = name; return this; } public Order setOrderType(String orderType) { this.orderType = orderType; return this; } @Override public String toString() { if(sql != null) { return sql; } else { StringBuilder builder = new StringBuilder(); if(table != null) { builder.append(tick(table)); builder.append(DOT); } builder.append(tick(name)); builder.append(orderType); return builder.toString(); } } }
14.580645
47
0.661504
556c7ca75d26d4d1d42c4aff03be11fe9581c034
172
import java.util.List; public class CombinedResult { private List<SalesInfoDTO> values; public List<SalesInfoDTO> getValues() { return values; } }
13.230769
43
0.668605
ff86014c3cc3ac6eee0c88220376533bf404e627
10,874
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|pdfbox operator|. name|pdmodel operator|. name|graphics operator|. name|shading package|; end_package begin_import import|import name|java operator|. name|awt operator|. name|Point import|; end_import begin_import import|import name|java operator|. name|awt operator|. name|Rectangle import|; end_import begin_import import|import name|java operator|. name|awt operator|. name|geom operator|. name|AffineTransform import|; end_import begin_import import|import name|java operator|. name|awt operator|. name|geom operator|. name|Point2D import|; end_import begin_import import|import name|java operator|. name|awt operator|. name|image operator|. name|ColorModel import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|javax operator|. name|imageio operator|. name|stream operator|. name|ImageInputStream import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|commons operator|. name|logging operator|. name|Log import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|commons operator|. name|logging operator|. name|LogFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|pdmodel operator|. name|common operator|. name|PDRange import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|util operator|. name|Matrix import|; end_import begin_comment comment|/** * Shades Gouraud triangles for Type4ShadingContext and Type5ShadingContext. * * @author Tilman Hausherr * @author Shaola Ren */ end_comment begin_class specifier|abstract class|class name|GouraudShadingContext extends|extends name|TriangleBasedShadingContext block|{ specifier|private specifier|static specifier|final name|Log name|LOG init|= name|LogFactory operator|. name|getLog argument_list|( name|GouraudShadingContext operator|. name|class argument_list|) decl_stmt|; comment|/** * triangle list. */ specifier|private name|List argument_list|< name|ShadedTriangle argument_list|> name|triangleList init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; comment|/** * Constructor creates an instance to be used for fill operations. * * @param shading the shading type to be used * @param colorModel the color model to be used * @param xform transformation for user to device space * @param matrix the pattern matrix concatenated with that of the parent content stream * @throws IOException if something went wrong */ specifier|protected name|GouraudShadingContext parameter_list|( name|PDShading name|shading parameter_list|, name|ColorModel name|colorModel parameter_list|, name|AffineTransform name|xform parameter_list|, name|Matrix name|matrix parameter_list|) throws|throws name|IOException block|{ name|super argument_list|( name|shading argument_list|, name|colorModel argument_list|, name|xform argument_list|, name|matrix argument_list|) expr_stmt|; block|} comment|/** * Read a vertex from the bit input stream performs interpolations. * * @param input bit input stream * @param maxSrcCoord max value for source coordinate (2^bits-1) * @param maxSrcColor max value for source color (2^bits-1) * @param rangeX dest range for X * @param rangeY dest range for Y * @param colRangeTab dest range array for colors * @param matrix the pattern matrix concatenated with that of the parent content stream * @return a new vertex with the flag and the interpolated values * @throws IOException if something went wrong */ specifier|protected name|Vertex name|readVertex parameter_list|( name|ImageInputStream name|input parameter_list|, name|long name|maxSrcCoord parameter_list|, name|long name|maxSrcColor parameter_list|, name|PDRange name|rangeX parameter_list|, name|PDRange name|rangeY parameter_list|, name|PDRange index|[] name|colRangeTab parameter_list|, name|Matrix name|matrix parameter_list|, name|AffineTransform name|xform parameter_list|) throws|throws name|IOException block|{ name|float index|[] name|colorComponentTab init|= operator|new name|float index|[ name|numberOfColorComponents index|] decl_stmt|; name|long name|x init|= name|input operator|. name|readBits argument_list|( name|bitsPerCoordinate argument_list|) decl_stmt|; name|long name|y init|= name|input operator|. name|readBits argument_list|( name|bitsPerCoordinate argument_list|) decl_stmt|; name|float name|dstX init|= name|interpolate argument_list|( name|x argument_list|, name|maxSrcCoord argument_list|, name|rangeX operator|. name|getMin argument_list|() argument_list|, name|rangeX operator|. name|getMax argument_list|() argument_list|) decl_stmt|; name|float name|dstY init|= name|interpolate argument_list|( name|y argument_list|, name|maxSrcCoord argument_list|, name|rangeY operator|. name|getMin argument_list|() argument_list|, name|rangeY operator|. name|getMax argument_list|() argument_list|) decl_stmt|; name|LOG operator|. name|debug argument_list|( literal|"coord: " operator|+ name|String operator|. name|format argument_list|( literal|"[%06X,%06X] -> [%f,%f]" argument_list|, name|x argument_list|, name|y argument_list|, name|dstX argument_list|, name|dstY argument_list|) argument_list|) expr_stmt|; name|Point2D name|p init|= name|matrix operator|. name|transformPoint argument_list|( name|dstX argument_list|, name|dstY argument_list|) decl_stmt|; name|xform operator|. name|transform argument_list|( name|p argument_list|, name|p argument_list|) expr_stmt|; for|for control|( name|int name|n init|= literal|0 init|; name|n operator|< name|numberOfColorComponents condition|; operator|++ name|n control|) block|{ name|int name|color init|= operator|( name|int operator|) name|input operator|. name|readBits argument_list|( name|bitsPerColorComponent argument_list|) decl_stmt|; name|colorComponentTab index|[ name|n index|] operator|= name|interpolate argument_list|( name|color argument_list|, name|maxSrcColor argument_list|, name|colRangeTab index|[ name|n index|] operator|. name|getMin argument_list|() argument_list|, name|colRangeTab index|[ name|n index|] operator|. name|getMax argument_list|() argument_list|) expr_stmt|; name|LOG operator|. name|debug argument_list|( literal|"color[" operator|+ name|n operator|+ literal|"]: " operator|+ name|color operator|+ literal|"/" operator|+ name|String operator|. name|format argument_list|( literal|"%02x" argument_list|, name|color argument_list|) operator|+ literal|"-> color[" operator|+ name|n operator|+ literal|"]: " operator|+ name|colorComponentTab index|[ name|n index|] argument_list|) expr_stmt|; block|} comment|// "Each set of vertex data shall occupy a whole number of bytes. comment|// If the total number of bits required is not divisible by 8, the last data byte comment|// for each vertex is padded at the end with extra bits, which shall be ignored." name|int name|bitOffset init|= name|input operator|. name|getBitOffset argument_list|() decl_stmt|; if|if condition|( name|bitOffset operator|!= literal|0 condition|) block|{ name|input operator|. name|readBits argument_list|( literal|8 operator|- name|bitOffset argument_list|) expr_stmt|; block|} return|return operator|new name|Vertex argument_list|( name|p argument_list|, name|colorComponentTab argument_list|) return|; block|} specifier|final name|void name|setTriangleList parameter_list|( name|List argument_list|< name|ShadedTriangle argument_list|> name|triangleList parameter_list|) block|{ name|this operator|. name|triangleList operator|= name|triangleList expr_stmt|; block|} annotation|@ name|Override specifier|protected name|Map argument_list|< name|Point argument_list|, name|Integer argument_list|> name|calcPixelTable parameter_list|( name|Rectangle name|deviceBounds parameter_list|) throws|throws name|IOException block|{ name|Map argument_list|< name|Point argument_list|, name|Integer argument_list|> name|map init|= operator|new name|HashMap argument_list|<> argument_list|() decl_stmt|; name|super operator|. name|calcPixelTable argument_list|( name|triangleList argument_list|, name|map argument_list|, name|deviceBounds argument_list|) expr_stmt|; return|return name|map return|; block|} annotation|@ name|Override specifier|public name|void name|dispose parameter_list|() block|{ name|triangleList operator|= literal|null expr_stmt|; name|super operator|. name|dispose argument_list|() expr_stmt|; block|} comment|/** * Calculate the interpolation, see p.345 pdf spec 1.7. * * @param src src value * @param srcMax max src value (2^bits-1) * @param dstMin min dst value * @param dstMax max dst value * @return interpolated value */ specifier|private name|float name|interpolate parameter_list|( name|float name|src parameter_list|, name|long name|srcMax parameter_list|, name|float name|dstMin parameter_list|, name|float name|dstMax parameter_list|) block|{ return|return name|dstMin operator|+ operator|( name|src operator|* operator|( name|dstMax operator|- name|dstMin operator|) operator|/ name|srcMax operator|) return|; block|} annotation|@ name|Override specifier|protected name|boolean name|isDataEmpty parameter_list|() block|{ return|return name|triangleList operator|. name|isEmpty argument_list|() return|; block|} block|} end_class end_unit
16.062038
810
0.781313
b916f3e52339df8d88316425a638c1d06a7ca22e
198
package com.ververica.common.resp; import com.ververica.common.model.catalog.Catalog; import java.util.List; import lombok.Data; @Data public class ListCatalogsResp { List<Catalog> catalogs; }
16.5
50
0.787879
51cfc5dfc2c0488f8ed044df548af08039bee661
7,331
package de.redsix.dmncheck.feel; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; class SubsumptionTest { @ParameterizedTest @CsvSource({"1", "\"a\"", "[1..2]", "<3", "not(3)"}) void emptySubsumesEverything(final String input) { final FeelExpression expression = FeelParser.PARSER.parse(input); final FeelExpression emptyExpression = FeelExpressions.Empty(); assertEquals(Optional.of(true), Subsumption.subsumes(emptyExpression, expression, Subsumption.eq)); } @ParameterizedTest @CsvSource({"1", "\"a\"", "[1..2]", "<3", "not(3)"}) void nothingSubsumesEmptyExceptEmpty(final String input) { final FeelExpression expression = FeelParser.PARSER.parse(input); final FeelExpression emptyExpression = FeelExpressions.Empty(); assertEquals(Optional.of(false), Subsumption.subsumes(expression, emptyExpression, Subsumption.eq)); } @Test void emptySubsumesEmpty() { final FeelExpression emptyExpression = FeelExpressions.Empty(); assertEquals(Optional.of(true), Subsumption.subsumes(emptyExpression, emptyExpression, Subsumption.eq)); } @Test void nullSubsumesNull() { final FeelExpression nullExpression = FeelExpressions.Null(); assertEquals(Optional.of(true), Subsumption.subsumes(nullExpression, nullExpression, Subsumption.eq)); } @Test void identicalStringsSubsumeEachOther() { final FeelExpression stringExpression = FeelParser.PARSER.parse("\"somestring\""); assertEquals(Optional.of(true), Subsumption.subsumes(stringExpression, stringExpression, Subsumption.eq)); } @Test void differentStringsDoNotSubsumeEachOther() { final FeelExpression stringExpression = FeelParser.PARSER.parse("\"somestring\""); final FeelExpression otherStringExpression = FeelParser.PARSER.parse("\"otherstring\""); assertEquals(Optional.of(false), Subsumption.subsumes(stringExpression, otherStringExpression, Subsumption.eq)); } @ParameterizedTest @CsvSource({"[1..2], [1..2]", "[1..9], [4..5]", "[1..5], (1..5)", "[1..5], [4..5]", "[1..5], [1..2]"}) void rangeExpressionsThatSubsumeEachOther(final String subsumingInput, final String subsumedInput) { assertLeftIsSubsumedByRight(subsumingInput, subsumedInput); } @ParameterizedTest @CsvSource({"[5..5], [1..9]", "(1..5), [1..5]", "[4..5], [1..5]", "[1..2], [1..5]"}) void rangeExpressionsThatDoNotSubsumeEachOther(final String subsumingInput, final String subsumedInput) { assertLeftIsNotSubsumedByRight(subsumingInput, subsumedInput); } @ParameterizedTest @CsvSource({"<5, [1..5)", "<5, [1..4]", "<=5, [1..5]", ">5, (5..9]", ">5, [6..9]", ">=5, [5..9]"}) void comparisonExpressionsThatSubsumesRangeExpression(final String subsumingInput, final String subsumedInput) { assertLeftIsSubsumedByRight(subsumingInput, subsumedInput); } @ParameterizedTest @CsvSource({"<=5, <5", "<=5, <=5", ">=5, >5", ">=5, >=5", ">1, >5", "<5, <1", "<=5.0, <5.0", "<=5.0, <=5.0", ">=5.0, >5.0", ">=5.0, >=5.0", ">1.0, >5.0", "<5.0, <1.0", "<=date and time(\"2015-11-30T12:00:00\"), <date and time(\"2015-11-30T12:00:00\")", "<=date and time(\"2015-11-30T12:00:00\"), <=date and time(\"2015-11-30T12:00:00\")", ">=date and time(\"2015-11-30T12:00:00\"), >date and time(\"2015-11-30T12:00:00\")", ">=date and time(\"2015-11-30T12:00:00\"), >=date and time(\"2015-11-30T12:00:00\")", ">date and time(\"2014-11-30T12:00:00\"), >date and time(\"2015-11-30T12:00:00\")", "<date and time(\"2015-11-30T12:00:00\"), <date and time(\"2014-11-30T12:00:00\")"}) void comparisonExpressionsThatSubsumesComparisonExpression(final String subsumingInput, final String subsumedInput) { assertLeftIsSubsumedByRight(subsumingInput, subsumedInput); } @ParameterizedTest @CsvSource({"<5, <=5", ">5, >=5", ">5, >1", "<1, <5", "<5.0, <=5.0", ">5.0, >=5.0", ">5.0, >1.0", "<1.0, <5.0", "<date and time(\"2015-11-30T12:00:00\"), <=date and time(\"2015-11-30T12:00:00\")", ">date and time(\"2015-11-30T12:00:00\"), >=date and time(\"2015-11-30T12:00:00\")", ">date and time(\"2015-11-30T12:00:00\"), >date and time(\"2014-11-30T12:00:00\")", "<date and time(\"2014-11-30T12:00:00\"), <date and time(\"2015-11-30T12:00:00\")"}) void comparisonExpressionsThatDoNotSubsumesComparisonExpression(final String subsumingInput, final String subsumedInput) { assertLeftIsNotSubsumedByRight(subsumingInput, subsumedInput); } @ParameterizedTest @CsvSource({"true, true", "false, false"}) void subsumptionForBooleanIsEqualityPositiveCases(final String subsumingInput, final String subsumedInput) { assertLeftIsSubsumedByRight(subsumingInput, subsumedInput); } @ParameterizedTest @CsvSource({"x, not(3)", "not(3), not(3)", "not(3), 4"}) void subsumptionForNotPositveCases(final String subsumingInput, final String subsumedInput) { assertLeftIsSubsumedByRight(subsumingInput, subsumedInput); } @ParameterizedTest @CsvSource({"true, false", "false, true"}) void subsumptionForBooleanIsEqualityNegativeCases(final String subsumingInput, final String subsumedInput) { assertLeftIsNotSubsumedByRight(subsumingInput, subsumedInput); } @ParameterizedTest @CsvSource({"x, not(x)", "not(x), not(y)", "not(3), x", "3, not(3)", "null, not(null)" , "not(3), 3", "[1..5], not([1..5])", "[1..5], not([1..5])", "not(3), not(4)", "not(\"3\"),\"3\""}) void subsumptionForNotNegativeCases(final String subsumingInput, final String subsumedInput) { assertLeftIsNotSubsumedByRight(subsumingInput, subsumedInput); } @ParameterizedTest @CsvSource({"[1..3], 2", "[1..3], 1", "[1..3], 3"}) void subsumptionRangeExpressionsAndLiteralsPositiveCases(final String subsumingInput, final String subsumedInput) { assertLeftIsSubsumedByRight(subsumingInput, subsumedInput); } @ParameterizedTest @CsvSource({"(1..3], 1", "[1..3), 3", "[1..3], 4", "[1..3], 0"}) void subsumptionRangeExpressionsAndLiteralsNegativeCases(final String subsumingInput, final String subsumedInput) { assertLeftIsNotSubsumedByRight(subsumingInput, subsumedInput); } private static void assertLeftIsSubsumedByRight(String subsumingInput, String subsumedInput) { final FeelExpression subsumingExpression = FeelParser.PARSER.parse(subsumingInput); final FeelExpression subsumedExpression = FeelParser.PARSER.parse(subsumedInput); assertEquals(Optional.of(true), Subsumption.subsumes(subsumingExpression, subsumedExpression, Subsumption.eq)); } private static void assertLeftIsNotSubsumedByRight(String subsumingInput, String subsumedInput) { final FeelExpression subsumingExpression = FeelParser.PARSER.parse(subsumingInput); final FeelExpression subsumedExpression = FeelParser.PARSER.parse(subsumedInput); assertEquals(Optional.of(false), Subsumption.subsumes(subsumingExpression, subsumedExpression, Subsumption.eq)); } }
52.364286
526
0.678898
a7328f0d35c9efa2c093739cf10f1adcde6d92ec
2,880
package com.milelu.service.service.category.impl; import java.util.List; import com.milelu.service.service.category.CategoryAttributeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.milelu.service.mapper.CategoryAttributeMapper; import com.milelu.service.domain.CategoryAttribute; /** * 分类扩展Service业务层处理 * * @author MILELU * @date 2021-01-20 */ @Service public class CategoryAttributeServiceImpl implements CategoryAttributeService { @Autowired private CategoryAttributeMapper categoryAttributeMapper; /** * 查询分类扩展 * * @param categoryId 分类扩展ID * @return 分类扩展 */ @Override public CategoryAttribute selectCategoryAttributeById(Long categoryId) { return categoryAttributeMapper.selectCategoryAttributeById(categoryId); } /** * 查询分类扩展列表 * * @param categoryAttribute 分类扩展 * @return 分类扩展 */ @Override public List<CategoryAttribute> selectCategoryAttributeList(CategoryAttribute categoryAttribute) { return categoryAttributeMapper.selectCategoryAttributeList(categoryAttribute); } /** * 新增分类扩展 * * @param categoryAttribute 分类扩展 * @return 结果 */ @Override public int insertCategoryAttribute(CategoryAttribute categoryAttribute) { return categoryAttributeMapper.insertCategoryAttribute(categoryAttribute); } /** * 修改分类扩展 * * @param categoryAttribute 分类扩展 * @return 结果 */ @Override public int updateCategoryAttribute(CategoryAttribute categoryAttribute) { return categoryAttributeMapper.updateCategoryAttribute(categoryAttribute); } /** * 批量删除分类扩展 * * @param categoryIds 需要删除的分类扩展ID * @return 结果 */ @Override public int deleteCategoryAttributeByIds(Long[] categoryIds) { return categoryAttributeMapper.deleteCategoryAttributeByIds(categoryIds); } /** * 删除分类扩展信息 * * @param categoryId 分类扩展ID * @return 结果 */ @Override public int deleteCategoryAttributeById(Long categoryId) { return categoryAttributeMapper.deleteCategoryAttributeById(categoryId); } /** * 根据分类ID获取SEO信息 * @param categoryId */ @Override public CategoryAttribute getSeo(String categoryId) { CategoryAttribute categoryAttribute = categoryAttributeMapper.getSeo(categoryId); return categoryAttribute; } /** * 根据分类ID修改Attribute * @param categoryAttribute */ @Override public void updateAttributeSeo(CategoryAttribute categoryAttribute) { updateCategoryAttribute(categoryAttribute); } @Override public void deleteByFiled(String field, String id) { categoryAttributeMapper.deleteByFiled(field,id); } }
24.201681
99
0.694444
a9b8ee190b280fe3dff71a0f19bbc1ff25fddd82
2,144
package br.com.exemplo.vendas.negocio.dao; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import br.com.exemplo.vendas.negocio.entity.Reserva; import br.com.exemplo.vendas.util.log.LoggerGenerator; public class ReservaDAO extends GenericDAO<Reserva> { public ReservaDAO( EntityManager em ) { super( em ) ; } public boolean inserir( Reserva reserva ) { boolean result = Boolean.FALSE; try { em.persist( reserva ); result = Boolean.TRUE; if (debugInfo) { LoggerGenerator.write("Reserva inserido: ", reserva.getAtendente()); } } catch ( Exception e ) { if ( debugInfo ) { e.printStackTrace( ); } } return result; } public boolean alterar( Reserva reserva ) { boolean result = false; Reserva existenteReserva = null; try { existenteReserva = em.find( Reserva.class, reserva.getId() ); if ( existenteReserva != null ) { em.merge( reserva ); result = true; if (debugInfo) { LoggerGenerator.write("Reserva alterada: ", reserva.getAtendente()); } } else { result = false; } } catch ( Exception e ) { if ( debugInfo ) { e.printStackTrace( ); } result = false; } return result; } public boolean excluir( Reserva reserva ) { boolean result = false; try { Reserva reservaEncontrada = em.find( Reserva.class, reserva.getId() ); em.remove( reservaEncontrada ); result = true; if (debugInfo) { LoggerGenerator.write("Reserva excluida: ", reserva.getAtendente()); } } catch ( Exception e ) { if ( debugInfo ) { e.printStackTrace( ); } } return result; } public List<Reserva> localizarPorCodigo( Reserva reserva ) { List<Reserva> result = new ArrayList<Reserva>( ); try { TypedQuery<Reserva> q = em.createQuery( "from Reserva where codigo = :codigo", Reserva.class ); q.setParameter( "codigo", reserva.getCodigo()); result = q.getResultList( ); } catch ( Exception e ) { if ( debugInfo ) { e.printStackTrace( ); } } return result; } }
18.807018
98
0.643657
e998bea02b943f4534956b2a300315c743587632
896
package domain.cache.impl; import domain.cache.Item; public class Clothe implements Item { private int id; private String code; private String name; private String price; private String provider; private String country; public void setCode(String code) { this.code = code; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCode() { return code; } }
14.688525
43
0.688616
f7a75112dd74660e3ff40e8982cfcf47b0ebe86b
9,304
/* * MIT License * * Copyright (c) 2018 Andreas Guther * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.aguther.dds.routing.util; import static com.google.common.base.Preconditions.checkNotNull; import com.github.aguther.dds.util.DurationFactory; import com.rti.connext.infrastructure.Sample; import com.rti.connext.requestreply.Requester; import com.rti.connext.requestreply.RequesterParams; import com.rti.dds.domain.DomainParticipant; import com.rti.dds.domain.DomainParticipantQos; import com.rti.dds.domain.builtin.ParticipantBuiltinTopicData; import com.rti.dds.infrastructure.InstanceHandleSeq; import com.rti.dds.infrastructure.InstanceHandle_t; import com.rti.dds.infrastructure.ServiceQosPolicyKind; import idl.RTI.RoutingService.Administration.COMMAND_REQUEST_TOPIC_NAME; import idl.RTI.RoutingService.Administration.COMMAND_RESPONSE_TOPIC_NAME; import idl.RTI.RoutingService.Administration.CommandRequest; import idl.RTI.RoutingService.Administration.CommandRequestTypeSupport; import idl.RTI.RoutingService.Administration.CommandResponse; import idl.RTI.RoutingService.Administration.CommandResponseTypeSupport; import java.io.Closeable; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class provides helpers to easily interact with a routing service using the topics defined by RTI. */ public class RoutingServiceCommandInterface implements Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(RoutingServiceCommandInterface.class); private final Requester<CommandRequest, CommandResponse> requester; private final int hostId; private final int applicationId; private int invocationCounter; /** * Instantiates a new routing service command helper. * * @param domainParticipant domain participant to send and receive commands */ public RoutingServiceCommandInterface( final DomainParticipant domainParticipant ) { // check input parameters checkNotNull(domainParticipant, "DomainParticipant must not be null"); // get host and app id from wire protocol of domain participant DomainParticipantQos domainParticipantQos = new DomainParticipantQos(); domainParticipant.get_qos(domainParticipantQos); hostId = domainParticipantQos.wire_protocol.rtps_host_id; applicationId = domainParticipantQos.wire_protocol.rtps_app_id; // set invocation counter invocationCounter = 0; // create parameters for requester RequesterParams requesterParams = new RequesterParams( domainParticipant, CommandRequestTypeSupport.get_instance(), CommandResponseTypeSupport.get_instance() ); requesterParams.setRequestTopicName(COMMAND_REQUEST_TOPIC_NAME.VALUE); requesterParams.setReplyTopicName(COMMAND_RESPONSE_TOPIC_NAME.VALUE); // create requester for routing service administration requester = new Requester<>(requesterParams); } @Override public void close() { if (requester != null) { requester.close(); } } /** * Waits for a specific routing service instance to be discovered. * * @param targetRouter target routing service * @param timeOut timeout * @param timeOutUnit time unit of timeout * @return true if target routing service was discovered, false if not within timeout */ public boolean waitForDiscovery( final String targetRouter, final long timeOut, final TimeUnit timeOutUnit ) { return waitForDiscovery( targetRouter, timeOut, timeOutUnit, 250L, TimeUnit.MILLISECONDS ); } /** * Waits for a specific routing service instance to be discovered. * * @param targetRouter target routing service * @param timeOut timeout * @param timeOutUnit time unit of timeout * @param sleepTime time to sleep between checks * @param sleepTimeUnit time unit of time to sleep * @return true if target routing service was discovered, false if not within timeout */ public boolean waitForDiscovery( final String targetRouter, final long timeOut, final TimeUnit timeOutUnit, final long sleepTime, final TimeUnit sleepTimeUnit ) { // create participant name for target router according RTI conventions String participantNameTargetRouter = String.format("RTI Routing Service: %s", targetRouter); try { // variables to store the data InstanceHandleSeq instanceHandles = new InstanceHandleSeq(); ParticipantBuiltinTopicData participantData = new ParticipantBuiltinTopicData(); // store start time long startTime = System.currentTimeMillis(); // determine end time long endTime = startTime + timeOutUnit.toMillis(timeOut); while (System.currentTimeMillis() < endTime) { // get matched subscriptions requester.getRequestDataWriter().get_matched_subscriptions(instanceHandles); // iterate over instance handles for (Object participantHandle : instanceHandles) { // get participant data of subscription requester.getRequestDataWriter().get_matched_subscription_participant_data( participantData, (InstanceHandle_t) participantHandle ); // check if related participant is from routing service if (participantData.service.kind == ServiceQosPolicyKind.ROUTING_SERVICE_QOS && participantData.participant_name.name.equals(participantNameTargetRouter)) { // we discovered the target routing service return true; } } // sleep for some time sleepTimeUnit.sleep(sleepTime); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // we did not discover the target routing service return false; } /** * Creates a new instance of the command request. * * @return new instance */ public CommandRequest createCommandRequest() { return new CommandRequest(); } /** * Sends a request to a target routing service and returns the response when received within timeout. * * @param commandRequest request to send * @param timeOut timeout * @param timeUnit time unit of timeout * @return response if received within timeout, otherwise null */ public CommandResponse sendRequest( final CommandRequest commandRequest, final long timeOut, final TimeUnit timeUnit ) { // set identification commandRequest.id.host = hostId; commandRequest.id.app = applicationId; commandRequest.id.invocation = ++invocationCounter; // logging logCommandRequest(commandRequest); // send request requester.sendRequest(commandRequest); // create reply Sample<CommandResponse> reply = requester.createReplySample(); // wait for reply boolean replyReceived = requester.receiveReply( reply, DurationFactory.from(timeOut, timeUnit) ); // logging logCommandResponse(reply, replyReceived); // return result return replyReceived ? reply.getData() : null; } /** * Logs some important things of a command request. * * @param commandRequest request that should be logged */ private void logCommandRequest( final CommandRequest commandRequest ) { // trace logs if (LOGGER.isTraceEnabled()) { LOGGER.trace( "CommandRequest.command.entity_desc.xml_url.content.length()='{}'", commandRequest.command.entity_desc.xml_url.content.length() ); LOGGER.trace( "CommandRequest {}", commandRequest.toString().replace("\n", "").replaceAll("[ ]{2,}", " ") ); } } /** * Logs some important things of a command response. * * @param reply response that should be logged * @param replyReceived true if response is valid, otherwise false */ private void logCommandResponse( final Sample<CommandResponse> reply, final boolean replyReceived ) { // trace logs if (LOGGER.isTraceEnabled()) { LOGGER.trace( "CommandResponse {}", replyReceived ? reply.getData().toString().replace( "\n", "").replaceAll("[ ]{2,}", " ") : "<no response received>" ); } } }
33.11032
105
0.7227
3b25c0f02f10a9d407679a62ebe16c0bfde5fd1e
136
package medo.algorithm; /** * Binary Search. * * @author bryce * */ public interface ArraySort { int[] run(int[] datas); }
9.714286
28
0.595588
36e3e6f6c62ff3044cabcbec0f13fb62addb930b
629
package de.pnp.manager.model.character.state; public abstract class MemberStateIcon { public static final int UNKNOWN = 0; public static final int DAMAGE = 1; public static final int HEAL = 2; public static final int MANA_DRAIN = 3; public static final int MANA_REGENERATION = 4; public static final int SLOW = 5; public static final int SPEED = 6; public static final int SNARE = 7; public static final int STUN = 8; public static final int FEAR = 9; public static final int ARMOR_BONUS = 10; public static final int ARMOR_MALUS = 11; public static final int SHIELD = 12; }
33.105263
50
0.702703
2e663ebe070507d03376b48e754a133e864db77e
995
package com.seizedays.ideasharingprovider.impl; import com.alibaba.dubbo.config.annotation.Service; import com.seizedays.beans.Memo; import com.seizedays.ideasharingprovider.mappers.MemoMapper; import com.seizedays.services.MemoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component //将当前Services变成spring的bean @Service public class MemoServiceImpl implements MemoService { @Autowired private MemoMapper memoMapper; @Override public List<Memo> getMemo(String date, Long uid) { return memoMapper.selectMemo(date,uid); } @Override public Integer addMemo(Memo memo) { return memoMapper.insertMemo(memo); } @Override public Integer updateMemo(Memo memo) { return memoMapper.updateMemo(memo); } @Override public Integer deleteMemoById(Long mid, Long uid) { return memoMapper.deleteMemoById(mid, uid); } }
25.512821
62
0.745729
fa8bea319d2ace13211fb92f6a3d5dd0e3fb5364
4,972
/** * Copyright (c) 2001-2017 Mathew A. Nelson and Robocode contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://robocode.sourceforge.net/license/epl-v10.html */ package robocode; import net.sf.robocode.security.IHiddenBulletHelper; import net.sf.robocode.serialization.ISerializableHelper; import net.sf.robocode.serialization.RbSerializer; import java.nio.ByteBuffer; /** * Represents a bullet. This is returned from {@link Robot#fireBullet(double)} * and {@link AdvancedRobot#setFireBullet(double)}, and all the bullet-related * events. * * @see Robot#fireBullet(double) * @see AdvancedRobot#setFireBullet(double) * @see BulletHitEvent * @see BulletMissedEvent * @see BulletHitBulletEvent * * @author Mathew A. Nelson (original) * @author Flemming N. Larsen (contributor) */ public class Bullet extends Projectile { private final int bulletId; /** * Called by the game to create a new {@code Bullet} object * * @param heading the heading of the bullet, in radians. * @param x the starting X position of the bullet. * @param y the starting Y position of the bullet. * @param power the power of the bullet. * @param ownerName the name of the owner robot that owns the bullet. * @param victimName the name of the robot hit by the bullet. * @param isActive {@code true} if the bullet still moves; {@code false} otherwise. * @param bulletId unique id of bullet for owner robot. */ public Bullet(double heading, double x, double y, double power, double velocity, String ownerName, String victimName, boolean isActive, int bulletId) { this.headingRadians = heading; this.x = x; this.y = y; this.power = power; this.velocity = velocity; this.ownerName = ownerName; this.victimName = victimName; this.isActive = isActive; this.bulletId = bulletId; } public Bullet(double heading, double x, double y, double power, String ownerName, String victimName, boolean isActive, int bulletId) { this.headingRadians = heading; this.x = x; this.y = y; this.power = power; this.ownerName = ownerName; this.victimName = victimName; this.isActive = isActive; this.bulletId = bulletId; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return bulletId == ((Bullet) obj).bulletId; } @Override public int hashCode() { return bulletId; } /** * @return unique id of bullet for owner robot */ int getBulletId() { return bulletId; } /** * Creates a hidden bullet helper for accessing hidden methods on this object. * * @return a hidden bullet helper. */ // this method is invisible on RobotAPI static IHiddenBulletHelper createHiddenHelper() { return new HiddenBulletHelper(); } /** * Creates a hidden bullet helper for accessing hidden methods on this object. * * @return a hidden bullet helper. */ // this class is invisible on RobotAPI static ISerializableHelper createHiddenSerializer() { return new HiddenBulletHelper(); } // this class is invisible on RobotAPI private static class HiddenBulletHelper implements IHiddenBulletHelper, ISerializableHelper { public void update(Bullet bullet, double x, double y, String victimName, boolean isActive) { bullet.update(x, y, victimName, isActive); } public int sizeOf(RbSerializer serializer, Object object) { Bullet obj = (Bullet) object; return RbSerializer.SIZEOF_TYPEINFO + 5 * RbSerializer.SIZEOF_DOUBLE + serializer.sizeOf(obj.ownerName) + serializer.sizeOf(obj.victimName) + RbSerializer.SIZEOF_BOOL + RbSerializer.SIZEOF_INT; } public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object) { Bullet obj = (Bullet) object; serializer.serialize(buffer, obj.headingRadians); serializer.serialize(buffer, obj.x); serializer.serialize(buffer, obj.y); serializer.serialize(buffer, obj.power); serializer.serialize(buffer, obj.velocity); serializer.serialize(buffer, obj.ownerName); serializer.serialize(buffer, obj.victimName); serializer.serialize(buffer, obj.isActive); serializer.serialize(buffer, obj.bulletId); } public Object deserialize(RbSerializer serializer, ByteBuffer buffer) { double headingRadians = buffer.getDouble(); double x = buffer.getDouble(); double y = buffer.getDouble(); double power = buffer.getDouble(); double velocity = buffer.getDouble(); String ownerName = serializer.deserializeString(buffer); String victimName = serializer.deserializeString(buffer); boolean isActive = serializer.deserializeBoolean(buffer); int bulletId = serializer.deserializeInt(buffer); return new Bullet(headingRadians, x, y, power, velocity, ownerName, victimName, isActive, bulletId); } } }
31.66879
152
0.730893
7bb9819a5562af203b705687a0b2c4a44d609590
144
package mcjty.lector.books.parser; public enum Token { TITLE, TOC, SECTION, TEXT, PARAGRAPH, PAGE, ITEM, IMG }
11.076923
34
0.576389
22a116fd7b1fa7556eccb513325cbd7910722985
57,117
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.api.servicemanagement.v1.stub; import static com.google.cloud.api.servicemanagement.v1.ServiceManagerClient.ListServiceConfigsPagedResponse; import static com.google.cloud.api.servicemanagement.v1.ServiceManagerClient.ListServiceRolloutsPagedResponse; import static com.google.cloud.api.servicemanagement.v1.ServiceManagerClient.ListServicesPagedResponse; import com.google.api.Service; import com.google.api.core.ApiFunction; import com.google.api.core.ApiFuture; import com.google.api.core.BetaApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.GrpcTransportChannel; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.grpc.ProtoOperationTransformers; import com.google.api.gax.longrunning.OperationSnapshot; import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallSettings; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.PagedCallSettings; import com.google.api.gax.rpc.PagedListDescriptor; import com.google.api.gax.rpc.PagedListResponseFactory; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.api.gax.rpc.UnaryCallable; import com.google.api.servicemanagement.v1.CreateServiceConfigRequest; import com.google.api.servicemanagement.v1.CreateServiceRequest; import com.google.api.servicemanagement.v1.CreateServiceRolloutRequest; import com.google.api.servicemanagement.v1.DeleteServiceRequest; import com.google.api.servicemanagement.v1.DisableServiceRequest; import com.google.api.servicemanagement.v1.DisableServiceResponse; import com.google.api.servicemanagement.v1.EnableServiceRequest; import com.google.api.servicemanagement.v1.EnableServiceResponse; import com.google.api.servicemanagement.v1.GenerateConfigReportRequest; import com.google.api.servicemanagement.v1.GenerateConfigReportResponse; import com.google.api.servicemanagement.v1.GetServiceConfigRequest; import com.google.api.servicemanagement.v1.GetServiceRequest; import com.google.api.servicemanagement.v1.GetServiceRolloutRequest; import com.google.api.servicemanagement.v1.ListServiceConfigsRequest; import com.google.api.servicemanagement.v1.ListServiceConfigsResponse; import com.google.api.servicemanagement.v1.ListServiceRolloutsRequest; import com.google.api.servicemanagement.v1.ListServiceRolloutsResponse; import com.google.api.servicemanagement.v1.ListServicesRequest; import com.google.api.servicemanagement.v1.ListServicesResponse; import com.google.api.servicemanagement.v1.ManagedService; import com.google.api.servicemanagement.v1.OperationMetadata; import com.google.api.servicemanagement.v1.Rollout; import com.google.api.servicemanagement.v1.SubmitConfigSourceRequest; import com.google.api.servicemanagement.v1.SubmitConfigSourceResponse; import com.google.api.servicemanagement.v1.UndeleteServiceRequest; import com.google.api.servicemanagement.v1.UndeleteServiceResponse; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.longrunning.Operation; import com.google.protobuf.Empty; import java.io.IOException; import java.util.List; import javax.annotation.Generated; import org.threeten.bp.Duration; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link ServiceManagerStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (servicemanagement.googleapis.com) and default port (443) are * used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the total timeout of getService to 30 seconds: * * <pre>{@code * ServiceManagerStubSettings.Builder serviceManagerSettingsBuilder = * ServiceManagerStubSettings.newBuilder(); * serviceManagerSettingsBuilder * .getServiceSettings() * .setRetrySettings( * serviceManagerSettingsBuilder * .getServiceSettings() * .getRetrySettings() * .toBuilder() * .setTotalTimeout(Duration.ofSeconds(30)) * .build()); * ServiceManagerStubSettings serviceManagerSettings = serviceManagerSettingsBuilder.build(); * }</pre> */ @Generated("by gapic-generator-java") public class ServiceManagerStubSettings extends StubSettings<ServiceManagerStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder() .add("https://www.googleapis.com/auth/cloud-platform") .add("https://www.googleapis.com/auth/cloud-platform.read-only") .add("https://www.googleapis.com/auth/service.management") .add("https://www.googleapis.com/auth/service.management.readonly") .build(); private final PagedCallSettings< ListServicesRequest, ListServicesResponse, ListServicesPagedResponse> listServicesSettings; private final UnaryCallSettings<GetServiceRequest, ManagedService> getServiceSettings; private final UnaryCallSettings<CreateServiceRequest, Operation> createServiceSettings; private final OperationCallSettings<CreateServiceRequest, ManagedService, OperationMetadata> createServiceOperationSettings; private final UnaryCallSettings<DeleteServiceRequest, Operation> deleteServiceSettings; private final OperationCallSettings<DeleteServiceRequest, Empty, OperationMetadata> deleteServiceOperationSettings; private final UnaryCallSettings<UndeleteServiceRequest, Operation> undeleteServiceSettings; private final OperationCallSettings< UndeleteServiceRequest, UndeleteServiceResponse, OperationMetadata> undeleteServiceOperationSettings; private final PagedCallSettings< ListServiceConfigsRequest, ListServiceConfigsResponse, ListServiceConfigsPagedResponse> listServiceConfigsSettings; private final UnaryCallSettings<GetServiceConfigRequest, Service> getServiceConfigSettings; private final UnaryCallSettings<CreateServiceConfigRequest, Service> createServiceConfigSettings; private final UnaryCallSettings<SubmitConfigSourceRequest, Operation> submitConfigSourceSettings; private final OperationCallSettings< SubmitConfigSourceRequest, SubmitConfigSourceResponse, OperationMetadata> submitConfigSourceOperationSettings; private final PagedCallSettings< ListServiceRolloutsRequest, ListServiceRolloutsResponse, ListServiceRolloutsPagedResponse> listServiceRolloutsSettings; private final UnaryCallSettings<GetServiceRolloutRequest, Rollout> getServiceRolloutSettings; private final UnaryCallSettings<CreateServiceRolloutRequest, Operation> createServiceRolloutSettings; private final OperationCallSettings<CreateServiceRolloutRequest, Rollout, OperationMetadata> createServiceRolloutOperationSettings; private final UnaryCallSettings<GenerateConfigReportRequest, GenerateConfigReportResponse> generateConfigReportSettings; private final UnaryCallSettings<EnableServiceRequest, Operation> enableServiceSettings; private final OperationCallSettings< EnableServiceRequest, EnableServiceResponse, OperationMetadata> enableServiceOperationSettings; private final UnaryCallSettings<DisableServiceRequest, Operation> disableServiceSettings; private final OperationCallSettings< DisableServiceRequest, DisableServiceResponse, OperationMetadata> disableServiceOperationSettings; private static final PagedListDescriptor< ListServicesRequest, ListServicesResponse, ManagedService> LIST_SERVICES_PAGE_STR_DESC = new PagedListDescriptor<ListServicesRequest, ListServicesResponse, ManagedService>() { @Override public String emptyToken() { return ""; } @Override public ListServicesRequest injectToken(ListServicesRequest payload, String token) { return ListServicesRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListServicesRequest injectPageSize(ListServicesRequest payload, int pageSize) { return ListServicesRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListServicesRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListServicesResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<ManagedService> extractResources(ListServicesResponse payload) { return payload.getServicesList() == null ? ImmutableList.<ManagedService>of() : payload.getServicesList(); } }; private static final PagedListDescriptor< ListServiceConfigsRequest, ListServiceConfigsResponse, Service> LIST_SERVICE_CONFIGS_PAGE_STR_DESC = new PagedListDescriptor< ListServiceConfigsRequest, ListServiceConfigsResponse, Service>() { @Override public String emptyToken() { return ""; } @Override public ListServiceConfigsRequest injectToken( ListServiceConfigsRequest payload, String token) { return ListServiceConfigsRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListServiceConfigsRequest injectPageSize( ListServiceConfigsRequest payload, int pageSize) { return ListServiceConfigsRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListServiceConfigsRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListServiceConfigsResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<Service> extractResources(ListServiceConfigsResponse payload) { return payload.getServiceConfigsList() == null ? ImmutableList.<Service>of() : payload.getServiceConfigsList(); } }; private static final PagedListDescriptor< ListServiceRolloutsRequest, ListServiceRolloutsResponse, Rollout> LIST_SERVICE_ROLLOUTS_PAGE_STR_DESC = new PagedListDescriptor< ListServiceRolloutsRequest, ListServiceRolloutsResponse, Rollout>() { @Override public String emptyToken() { return ""; } @Override public ListServiceRolloutsRequest injectToken( ListServiceRolloutsRequest payload, String token) { return ListServiceRolloutsRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListServiceRolloutsRequest injectPageSize( ListServiceRolloutsRequest payload, int pageSize) { return ListServiceRolloutsRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListServiceRolloutsRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListServiceRolloutsResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<Rollout> extractResources(ListServiceRolloutsResponse payload) { return payload.getRolloutsList() == null ? ImmutableList.<Rollout>of() : payload.getRolloutsList(); } }; private static final PagedListResponseFactory< ListServicesRequest, ListServicesResponse, ListServicesPagedResponse> LIST_SERVICES_PAGE_STR_FACT = new PagedListResponseFactory< ListServicesRequest, ListServicesResponse, ListServicesPagedResponse>() { @Override public ApiFuture<ListServicesPagedResponse> getFuturePagedResponse( UnaryCallable<ListServicesRequest, ListServicesResponse> callable, ListServicesRequest request, ApiCallContext context, ApiFuture<ListServicesResponse> futureResponse) { PageContext<ListServicesRequest, ListServicesResponse, ManagedService> pageContext = PageContext.create(callable, LIST_SERVICES_PAGE_STR_DESC, request, context); return ListServicesPagedResponse.createAsync(pageContext, futureResponse); } }; private static final PagedListResponseFactory< ListServiceConfigsRequest, ListServiceConfigsResponse, ListServiceConfigsPagedResponse> LIST_SERVICE_CONFIGS_PAGE_STR_FACT = new PagedListResponseFactory< ListServiceConfigsRequest, ListServiceConfigsResponse, ListServiceConfigsPagedResponse>() { @Override public ApiFuture<ListServiceConfigsPagedResponse> getFuturePagedResponse( UnaryCallable<ListServiceConfigsRequest, ListServiceConfigsResponse> callable, ListServiceConfigsRequest request, ApiCallContext context, ApiFuture<ListServiceConfigsResponse> futureResponse) { PageContext<ListServiceConfigsRequest, ListServiceConfigsResponse, Service> pageContext = PageContext.create( callable, LIST_SERVICE_CONFIGS_PAGE_STR_DESC, request, context); return ListServiceConfigsPagedResponse.createAsync(pageContext, futureResponse); } }; private static final PagedListResponseFactory< ListServiceRolloutsRequest, ListServiceRolloutsResponse, ListServiceRolloutsPagedResponse> LIST_SERVICE_ROLLOUTS_PAGE_STR_FACT = new PagedListResponseFactory< ListServiceRolloutsRequest, ListServiceRolloutsResponse, ListServiceRolloutsPagedResponse>() { @Override public ApiFuture<ListServiceRolloutsPagedResponse> getFuturePagedResponse( UnaryCallable<ListServiceRolloutsRequest, ListServiceRolloutsResponse> callable, ListServiceRolloutsRequest request, ApiCallContext context, ApiFuture<ListServiceRolloutsResponse> futureResponse) { PageContext<ListServiceRolloutsRequest, ListServiceRolloutsResponse, Rollout> pageContext = PageContext.create( callable, LIST_SERVICE_ROLLOUTS_PAGE_STR_DESC, request, context); return ListServiceRolloutsPagedResponse.createAsync(pageContext, futureResponse); } }; /** Returns the object with the settings used for calls to listServices. */ public PagedCallSettings<ListServicesRequest, ListServicesResponse, ListServicesPagedResponse> listServicesSettings() { return listServicesSettings; } /** Returns the object with the settings used for calls to getService. */ public UnaryCallSettings<GetServiceRequest, ManagedService> getServiceSettings() { return getServiceSettings; } /** Returns the object with the settings used for calls to createService. */ public UnaryCallSettings<CreateServiceRequest, Operation> createServiceSettings() { return createServiceSettings; } /** Returns the object with the settings used for calls to createService. */ public OperationCallSettings<CreateServiceRequest, ManagedService, OperationMetadata> createServiceOperationSettings() { return createServiceOperationSettings; } /** Returns the object with the settings used for calls to deleteService. */ public UnaryCallSettings<DeleteServiceRequest, Operation> deleteServiceSettings() { return deleteServiceSettings; } /** Returns the object with the settings used for calls to deleteService. */ public OperationCallSettings<DeleteServiceRequest, Empty, OperationMetadata> deleteServiceOperationSettings() { return deleteServiceOperationSettings; } /** Returns the object with the settings used for calls to undeleteService. */ public UnaryCallSettings<UndeleteServiceRequest, Operation> undeleteServiceSettings() { return undeleteServiceSettings; } /** Returns the object with the settings used for calls to undeleteService. */ public OperationCallSettings<UndeleteServiceRequest, UndeleteServiceResponse, OperationMetadata> undeleteServiceOperationSettings() { return undeleteServiceOperationSettings; } /** Returns the object with the settings used for calls to listServiceConfigs. */ public PagedCallSettings< ListServiceConfigsRequest, ListServiceConfigsResponse, ListServiceConfigsPagedResponse> listServiceConfigsSettings() { return listServiceConfigsSettings; } /** Returns the object with the settings used for calls to getServiceConfig. */ public UnaryCallSettings<GetServiceConfigRequest, Service> getServiceConfigSettings() { return getServiceConfigSettings; } /** Returns the object with the settings used for calls to createServiceConfig. */ public UnaryCallSettings<CreateServiceConfigRequest, Service> createServiceConfigSettings() { return createServiceConfigSettings; } /** Returns the object with the settings used for calls to submitConfigSource. */ public UnaryCallSettings<SubmitConfigSourceRequest, Operation> submitConfigSourceSettings() { return submitConfigSourceSettings; } /** Returns the object with the settings used for calls to submitConfigSource. */ public OperationCallSettings< SubmitConfigSourceRequest, SubmitConfigSourceResponse, OperationMetadata> submitConfigSourceOperationSettings() { return submitConfigSourceOperationSettings; } /** Returns the object with the settings used for calls to listServiceRollouts. */ public PagedCallSettings< ListServiceRolloutsRequest, ListServiceRolloutsResponse, ListServiceRolloutsPagedResponse> listServiceRolloutsSettings() { return listServiceRolloutsSettings; } /** Returns the object with the settings used for calls to getServiceRollout. */ public UnaryCallSettings<GetServiceRolloutRequest, Rollout> getServiceRolloutSettings() { return getServiceRolloutSettings; } /** Returns the object with the settings used for calls to createServiceRollout. */ public UnaryCallSettings<CreateServiceRolloutRequest, Operation> createServiceRolloutSettings() { return createServiceRolloutSettings; } /** Returns the object with the settings used for calls to createServiceRollout. */ public OperationCallSettings<CreateServiceRolloutRequest, Rollout, OperationMetadata> createServiceRolloutOperationSettings() { return createServiceRolloutOperationSettings; } /** Returns the object with the settings used for calls to generateConfigReport. */ public UnaryCallSettings<GenerateConfigReportRequest, GenerateConfigReportResponse> generateConfigReportSettings() { return generateConfigReportSettings; } /** * Returns the object with the settings used for calls to enableService. * * @deprecated This method is deprecated and will be removed in the next major version update. */ @Deprecated public UnaryCallSettings<EnableServiceRequest, Operation> enableServiceSettings() { return enableServiceSettings; } /** Returns the object with the settings used for calls to enableService. */ public OperationCallSettings<EnableServiceRequest, EnableServiceResponse, OperationMetadata> enableServiceOperationSettings() { return enableServiceOperationSettings; } /** * Returns the object with the settings used for calls to disableService. * * @deprecated This method is deprecated and will be removed in the next major version update. */ @Deprecated public UnaryCallSettings<DisableServiceRequest, Operation> disableServiceSettings() { return disableServiceSettings; } /** Returns the object with the settings used for calls to disableService. */ public OperationCallSettings<DisableServiceRequest, DisableServiceResponse, OperationMetadata> disableServiceOperationSettings() { return disableServiceOperationSettings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public ServiceManagerStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(GrpcTransportChannel.getGrpcTransportName())) { return GrpcServiceManagerStub.create(this); } throw new UnsupportedOperationException( String.format( "Transport not supported: %s", getTransportChannelProvider().getTransportName())); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return "servicemanagement.googleapis.com:443"; } /** Returns the default mTLS service endpoint. */ public static String getDefaultMtlsEndpoint() { return "servicemanagement.mtls.googleapis.com:443"; } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return DEFAULT_SERVICE_SCOPES; } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return InstantiatingGrpcChannelProvider.newBuilder() .setMaxInboundMessageSize(Integer.MAX_VALUE); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultGrpcTransportProviderBuilder().build(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(ServiceManagerStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected ServiceManagerStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); listServicesSettings = settingsBuilder.listServicesSettings().build(); getServiceSettings = settingsBuilder.getServiceSettings().build(); createServiceSettings = settingsBuilder.createServiceSettings().build(); createServiceOperationSettings = settingsBuilder.createServiceOperationSettings().build(); deleteServiceSettings = settingsBuilder.deleteServiceSettings().build(); deleteServiceOperationSettings = settingsBuilder.deleteServiceOperationSettings().build(); undeleteServiceSettings = settingsBuilder.undeleteServiceSettings().build(); undeleteServiceOperationSettings = settingsBuilder.undeleteServiceOperationSettings().build(); listServiceConfigsSettings = settingsBuilder.listServiceConfigsSettings().build(); getServiceConfigSettings = settingsBuilder.getServiceConfigSettings().build(); createServiceConfigSettings = settingsBuilder.createServiceConfigSettings().build(); submitConfigSourceSettings = settingsBuilder.submitConfigSourceSettings().build(); submitConfigSourceOperationSettings = settingsBuilder.submitConfigSourceOperationSettings().build(); listServiceRolloutsSettings = settingsBuilder.listServiceRolloutsSettings().build(); getServiceRolloutSettings = settingsBuilder.getServiceRolloutSettings().build(); createServiceRolloutSettings = settingsBuilder.createServiceRolloutSettings().build(); createServiceRolloutOperationSettings = settingsBuilder.createServiceRolloutOperationSettings().build(); generateConfigReportSettings = settingsBuilder.generateConfigReportSettings().build(); enableServiceSettings = settingsBuilder.enableServiceSettings().build(); enableServiceOperationSettings = settingsBuilder.enableServiceOperationSettings().build(); disableServiceSettings = settingsBuilder.disableServiceSettings().build(); disableServiceOperationSettings = settingsBuilder.disableServiceOperationSettings().build(); } /** Builder for ServiceManagerStubSettings. */ public static class Builder extends StubSettings.Builder<ServiceManagerStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final PagedCallSettings.Builder< ListServicesRequest, ListServicesResponse, ListServicesPagedResponse> listServicesSettings; private final UnaryCallSettings.Builder<GetServiceRequest, ManagedService> getServiceSettings; private final UnaryCallSettings.Builder<CreateServiceRequest, Operation> createServiceSettings; private final OperationCallSettings.Builder< CreateServiceRequest, ManagedService, OperationMetadata> createServiceOperationSettings; private final UnaryCallSettings.Builder<DeleteServiceRequest, Operation> deleteServiceSettings; private final OperationCallSettings.Builder<DeleteServiceRequest, Empty, OperationMetadata> deleteServiceOperationSettings; private final UnaryCallSettings.Builder<UndeleteServiceRequest, Operation> undeleteServiceSettings; private final OperationCallSettings.Builder< UndeleteServiceRequest, UndeleteServiceResponse, OperationMetadata> undeleteServiceOperationSettings; private final PagedCallSettings.Builder< ListServiceConfigsRequest, ListServiceConfigsResponse, ListServiceConfigsPagedResponse> listServiceConfigsSettings; private final UnaryCallSettings.Builder<GetServiceConfigRequest, Service> getServiceConfigSettings; private final UnaryCallSettings.Builder<CreateServiceConfigRequest, Service> createServiceConfigSettings; private final UnaryCallSettings.Builder<SubmitConfigSourceRequest, Operation> submitConfigSourceSettings; private final OperationCallSettings.Builder< SubmitConfigSourceRequest, SubmitConfigSourceResponse, OperationMetadata> submitConfigSourceOperationSettings; private final PagedCallSettings.Builder< ListServiceRolloutsRequest, ListServiceRolloutsResponse, ListServiceRolloutsPagedResponse> listServiceRolloutsSettings; private final UnaryCallSettings.Builder<GetServiceRolloutRequest, Rollout> getServiceRolloutSettings; private final UnaryCallSettings.Builder<CreateServiceRolloutRequest, Operation> createServiceRolloutSettings; private final OperationCallSettings.Builder< CreateServiceRolloutRequest, Rollout, OperationMetadata> createServiceRolloutOperationSettings; private final UnaryCallSettings.Builder< GenerateConfigReportRequest, GenerateConfigReportResponse> generateConfigReportSettings; private final UnaryCallSettings.Builder<EnableServiceRequest, Operation> enableServiceSettings; private final OperationCallSettings.Builder< EnableServiceRequest, EnableServiceResponse, OperationMetadata> enableServiceOperationSettings; private final UnaryCallSettings.Builder<DisableServiceRequest, Operation> disableServiceSettings; private final OperationCallSettings.Builder< DisableServiceRequest, DisableServiceResponse, OperationMetadata> disableServiceOperationSettings; private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>> RETRYABLE_CODE_DEFINITIONS; static { ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions = ImmutableMap.builder(); definitions.put( "no_retry_0_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList())); RETRYABLE_CODE_DEFINITIONS = definitions.build(); } private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS; static { ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder(); RetrySettings settings = null; settings = RetrySettings.newBuilder() .setInitialRpcTimeout(Duration.ofMillis(10000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(10000L)) .setTotalTimeout(Duration.ofMillis(10000L)) .build(); definitions.put("no_retry_0_params", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(clientContext); listServicesSettings = PagedCallSettings.newBuilder(LIST_SERVICES_PAGE_STR_FACT); getServiceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); createServiceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); createServiceOperationSettings = OperationCallSettings.newBuilder(); deleteServiceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); deleteServiceOperationSettings = OperationCallSettings.newBuilder(); undeleteServiceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); undeleteServiceOperationSettings = OperationCallSettings.newBuilder(); listServiceConfigsSettings = PagedCallSettings.newBuilder(LIST_SERVICE_CONFIGS_PAGE_STR_FACT); getServiceConfigSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); createServiceConfigSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); submitConfigSourceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); submitConfigSourceOperationSettings = OperationCallSettings.newBuilder(); listServiceRolloutsSettings = PagedCallSettings.newBuilder(LIST_SERVICE_ROLLOUTS_PAGE_STR_FACT); getServiceRolloutSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); createServiceRolloutSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); createServiceRolloutOperationSettings = OperationCallSettings.newBuilder(); generateConfigReportSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); enableServiceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); enableServiceOperationSettings = OperationCallSettings.newBuilder(); disableServiceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); disableServiceOperationSettings = OperationCallSettings.newBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( listServicesSettings, getServiceSettings, createServiceSettings, deleteServiceSettings, undeleteServiceSettings, listServiceConfigsSettings, getServiceConfigSettings, createServiceConfigSettings, submitConfigSourceSettings, listServiceRolloutsSettings, getServiceRolloutSettings, createServiceRolloutSettings, generateConfigReportSettings, enableServiceSettings, disableServiceSettings); initDefaults(this); } protected Builder(ServiceManagerStubSettings settings) { super(settings); listServicesSettings = settings.listServicesSettings.toBuilder(); getServiceSettings = settings.getServiceSettings.toBuilder(); createServiceSettings = settings.createServiceSettings.toBuilder(); createServiceOperationSettings = settings.createServiceOperationSettings.toBuilder(); deleteServiceSettings = settings.deleteServiceSettings.toBuilder(); deleteServiceOperationSettings = settings.deleteServiceOperationSettings.toBuilder(); undeleteServiceSettings = settings.undeleteServiceSettings.toBuilder(); undeleteServiceOperationSettings = settings.undeleteServiceOperationSettings.toBuilder(); listServiceConfigsSettings = settings.listServiceConfigsSettings.toBuilder(); getServiceConfigSettings = settings.getServiceConfigSettings.toBuilder(); createServiceConfigSettings = settings.createServiceConfigSettings.toBuilder(); submitConfigSourceSettings = settings.submitConfigSourceSettings.toBuilder(); submitConfigSourceOperationSettings = settings.submitConfigSourceOperationSettings.toBuilder(); listServiceRolloutsSettings = settings.listServiceRolloutsSettings.toBuilder(); getServiceRolloutSettings = settings.getServiceRolloutSettings.toBuilder(); createServiceRolloutSettings = settings.createServiceRolloutSettings.toBuilder(); createServiceRolloutOperationSettings = settings.createServiceRolloutOperationSettings.toBuilder(); generateConfigReportSettings = settings.generateConfigReportSettings.toBuilder(); enableServiceSettings = settings.enableServiceSettings.toBuilder(); enableServiceOperationSettings = settings.enableServiceOperationSettings.toBuilder(); disableServiceSettings = settings.disableServiceSettings.toBuilder(); disableServiceOperationSettings = settings.disableServiceOperationSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( listServicesSettings, getServiceSettings, createServiceSettings, deleteServiceSettings, undeleteServiceSettings, listServiceConfigsSettings, getServiceConfigSettings, createServiceConfigSettings, submitConfigSourceSettings, listServiceRolloutsSettings, getServiceRolloutSettings, createServiceRolloutSettings, generateConfigReportSettings, enableServiceSettings, disableServiceSettings); } private static Builder createDefault() { Builder builder = new Builder(((ClientContext) null)); builder.setTransportChannelProvider(defaultTransportChannelProvider()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); builder.setEndpoint(getDefaultEndpoint()); builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); builder.setSwitchToMtlsEndpointAllowed(true); return initDefaults(builder); } private static Builder initDefaults(Builder builder) { builder .listServicesSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .getServiceSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .createServiceSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .deleteServiceSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .undeleteServiceSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .listServiceConfigsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .getServiceConfigSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .createServiceConfigSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .submitConfigSourceSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .listServiceRolloutsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .getServiceRolloutSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .createServiceRolloutSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .generateConfigReportSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .enableServiceSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .disableServiceSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")); builder .createServiceOperationSettings() .setInitialCallSettings( UnaryCallSettings .<CreateServiceRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(ManagedService.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelay(Duration.ofMillis(45000L)) .setInitialRpcTimeout(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ZERO) .setTotalTimeout(Duration.ofMillis(300000L)) .build())); builder .deleteServiceOperationSettings() .setInitialCallSettings( UnaryCallSettings .<DeleteServiceRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Empty.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelay(Duration.ofMillis(45000L)) .setInitialRpcTimeout(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ZERO) .setTotalTimeout(Duration.ofMillis(300000L)) .build())); builder .undeleteServiceOperationSettings() .setInitialCallSettings( UnaryCallSettings .<UndeleteServiceRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(UndeleteServiceResponse.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelay(Duration.ofMillis(45000L)) .setInitialRpcTimeout(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ZERO) .setTotalTimeout(Duration.ofMillis(300000L)) .build())); builder .submitConfigSourceOperationSettings() .setInitialCallSettings( UnaryCallSettings .<SubmitConfigSourceRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create( SubmitConfigSourceResponse.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelay(Duration.ofMillis(45000L)) .setInitialRpcTimeout(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ZERO) .setTotalTimeout(Duration.ofMillis(300000L)) .build())); builder .createServiceRolloutOperationSettings() .setInitialCallSettings( UnaryCallSettings .<CreateServiceRolloutRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Rollout.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelay(Duration.ofMillis(45000L)) .setInitialRpcTimeout(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ZERO) .setTotalTimeout(Duration.ofMillis(300000L)) .build())); builder .enableServiceOperationSettings() .setInitialCallSettings( UnaryCallSettings .<EnableServiceRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(EnableServiceResponse.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelay(Duration.ofMillis(45000L)) .setInitialRpcTimeout(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ZERO) .setTotalTimeout(Duration.ofMillis(300000L)) .build())); builder .disableServiceOperationSettings() .setInitialCallSettings( UnaryCallSettings .<DisableServiceRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(DisableServiceResponse.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelay(Duration.ofMillis(45000L)) .setInitialRpcTimeout(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ZERO) .setTotalTimeout(Duration.ofMillis(300000L)) .build())); return builder; } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); return this; } public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() { return unaryMethodSettingsBuilders; } /** Returns the builder for the settings used for calls to listServices. */ public PagedCallSettings.Builder< ListServicesRequest, ListServicesResponse, ListServicesPagedResponse> listServicesSettings() { return listServicesSettings; } /** Returns the builder for the settings used for calls to getService. */ public UnaryCallSettings.Builder<GetServiceRequest, ManagedService> getServiceSettings() { return getServiceSettings; } /** Returns the builder for the settings used for calls to createService. */ public UnaryCallSettings.Builder<CreateServiceRequest, Operation> createServiceSettings() { return createServiceSettings; } /** Returns the builder for the settings used for calls to createService. */ @BetaApi( "The surface for use by generated code is not stable yet and may change in the future.") public OperationCallSettings.Builder<CreateServiceRequest, ManagedService, OperationMetadata> createServiceOperationSettings() { return createServiceOperationSettings; } /** Returns the builder for the settings used for calls to deleteService. */ public UnaryCallSettings.Builder<DeleteServiceRequest, Operation> deleteServiceSettings() { return deleteServiceSettings; } /** Returns the builder for the settings used for calls to deleteService. */ @BetaApi( "The surface for use by generated code is not stable yet and may change in the future.") public OperationCallSettings.Builder<DeleteServiceRequest, Empty, OperationMetadata> deleteServiceOperationSettings() { return deleteServiceOperationSettings; } /** Returns the builder for the settings used for calls to undeleteService. */ public UnaryCallSettings.Builder<UndeleteServiceRequest, Operation> undeleteServiceSettings() { return undeleteServiceSettings; } /** Returns the builder for the settings used for calls to undeleteService. */ @BetaApi( "The surface for use by generated code is not stable yet and may change in the future.") public OperationCallSettings.Builder< UndeleteServiceRequest, UndeleteServiceResponse, OperationMetadata> undeleteServiceOperationSettings() { return undeleteServiceOperationSettings; } /** Returns the builder for the settings used for calls to listServiceConfigs. */ public PagedCallSettings.Builder< ListServiceConfigsRequest, ListServiceConfigsResponse, ListServiceConfigsPagedResponse> listServiceConfigsSettings() { return listServiceConfigsSettings; } /** Returns the builder for the settings used for calls to getServiceConfig. */ public UnaryCallSettings.Builder<GetServiceConfigRequest, Service> getServiceConfigSettings() { return getServiceConfigSettings; } /** Returns the builder for the settings used for calls to createServiceConfig. */ public UnaryCallSettings.Builder<CreateServiceConfigRequest, Service> createServiceConfigSettings() { return createServiceConfigSettings; } /** Returns the builder for the settings used for calls to submitConfigSource. */ public UnaryCallSettings.Builder<SubmitConfigSourceRequest, Operation> submitConfigSourceSettings() { return submitConfigSourceSettings; } /** Returns the builder for the settings used for calls to submitConfigSource. */ @BetaApi( "The surface for use by generated code is not stable yet and may change in the future.") public OperationCallSettings.Builder< SubmitConfigSourceRequest, SubmitConfigSourceResponse, OperationMetadata> submitConfigSourceOperationSettings() { return submitConfigSourceOperationSettings; } /** Returns the builder for the settings used for calls to listServiceRollouts. */ public PagedCallSettings.Builder< ListServiceRolloutsRequest, ListServiceRolloutsResponse, ListServiceRolloutsPagedResponse> listServiceRolloutsSettings() { return listServiceRolloutsSettings; } /** Returns the builder for the settings used for calls to getServiceRollout. */ public UnaryCallSettings.Builder<GetServiceRolloutRequest, Rollout> getServiceRolloutSettings() { return getServiceRolloutSettings; } /** Returns the builder for the settings used for calls to createServiceRollout. */ public UnaryCallSettings.Builder<CreateServiceRolloutRequest, Operation> createServiceRolloutSettings() { return createServiceRolloutSettings; } /** Returns the builder for the settings used for calls to createServiceRollout. */ @BetaApi( "The surface for use by generated code is not stable yet and may change in the future.") public OperationCallSettings.Builder<CreateServiceRolloutRequest, Rollout, OperationMetadata> createServiceRolloutOperationSettings() { return createServiceRolloutOperationSettings; } /** Returns the builder for the settings used for calls to generateConfigReport. */ public UnaryCallSettings.Builder<GenerateConfigReportRequest, GenerateConfigReportResponse> generateConfigReportSettings() { return generateConfigReportSettings; } /** * Returns the builder for the settings used for calls to enableService. * * @deprecated This method is deprecated and will be removed in the next major version update. */ @Deprecated public UnaryCallSettings.Builder<EnableServiceRequest, Operation> enableServiceSettings() { return enableServiceSettings; } /** Returns the builder for the settings used for calls to enableService. */ @BetaApi( "The surface for use by generated code is not stable yet and may change in the future.") public OperationCallSettings.Builder< EnableServiceRequest, EnableServiceResponse, OperationMetadata> enableServiceOperationSettings() { return enableServiceOperationSettings; } /** * Returns the builder for the settings used for calls to disableService. * * @deprecated This method is deprecated and will be removed in the next major version update. */ @Deprecated public UnaryCallSettings.Builder<DisableServiceRequest, Operation> disableServiceSettings() { return disableServiceSettings; } /** Returns the builder for the settings used for calls to disableService. */ @BetaApi( "The surface for use by generated code is not stable yet and may change in the future.") public OperationCallSettings.Builder< DisableServiceRequest, DisableServiceResponse, OperationMetadata> disableServiceOperationSettings() { return disableServiceOperationSettings; } @Override public ServiceManagerStubSettings build() throws IOException { return new ServiceManagerStubSettings(this); } } }
47.478803
110
0.726316