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
bce907be547d1a3001d0bed5153b200901b34a43
5,244
package eu.dnetlib.iis.wf.affmatching.match; import static eu.dnetlib.iis.wf.affmatching.match.voter.AffOrgMatchVotersFactory.createNameCountryStrictMatchVoter; import static eu.dnetlib.iis.wf.affmatching.match.voter.AffOrgMatchVotersFactory.createNameStrictCountryLooseMatchVoter; import static eu.dnetlib.iis.wf.affmatching.match.voter.AffOrgMatchVotersFactory.createSectionedNameLevenshteinCountryLooseMatchVoter; import static eu.dnetlib.iis.wf.affmatching.match.voter.AffOrgMatchVotersFactory.createSectionedNameStrictCountryLooseMatchVoter; import static eu.dnetlib.iis.wf.affmatching.match.voter.CommonWordsVoter.RatioRelation.WITH_REGARD_TO_AFF_WORDS; import static eu.dnetlib.iis.wf.affmatching.match.voter.CommonWordsVoter.RatioRelation.WITH_REGARD_TO_ORG_WORDS; import java.util.List; import java.util.function.Function; import com.google.common.collect.ImmutableList; import eu.dnetlib.iis.wf.affmatching.bucket.AffOrgHashBucketJoiner; import eu.dnetlib.iis.wf.affmatching.bucket.OrganizationNameBucketHasher; import eu.dnetlib.iis.wf.affmatching.match.voter.AffOrgMatchVoter; import eu.dnetlib.iis.wf.affmatching.match.voter.CommonSimilarWordCalculator; import eu.dnetlib.iis.wf.affmatching.match.voter.CommonWordsVoter; import eu.dnetlib.iis.wf.affmatching.match.voter.CompositeMatchVoter; import eu.dnetlib.iis.wf.affmatching.match.voter.CountryCodeLooseMatchVoter; import eu.dnetlib.iis.wf.affmatching.match.voter.GetOrgNameFunction; import eu.dnetlib.iis.wf.affmatching.match.voter.GetOrgShortNameFunction; import eu.dnetlib.iis.wf.affmatching.model.AffMatchAffiliation; import eu.dnetlib.iis.wf.affmatching.model.AffMatchOrganization; /** * A factory of {@link AffOrgMatcher}s that join organizations and affiliations into buckets based on hashes produced from * first words of organization names. * @author Łukasz Dumiszewski */ public final class FirstWordsHashBucketMatcherFactory { // ---------------------- CONSTRUCTORS ---------------------- private FirstWordsHashBucketMatcherFactory() {} // ---------------------- LOGIC ----------------------------- /** * Returns {@link AffOrgMatcher} that uses hashing of affiliations and organizations to create buckets.<br/> * Hashes are computed based on first letters of first words of {@link AffMatchAffiliation#getOrganizationName()} * and {@link AffMatchOrganization#getName()}. */ public static AffOrgMatcher createNameFirstWordsHashBucketMatcher() { // joiner AffOrgHashBucketJoiner firstWordsHashBucketJoiner = createFirstWordsAffOrgHashBucketJoiner(new GetOrgNameFunction()); // computer AffOrgMatchComputer firstWordsHashMatchComputer = new AffOrgMatchComputer(); firstWordsHashMatchComputer.setAffOrgMatchVoters(createNameFirstWordsHashBucketMatcherVoters()); // matcher return new AffOrgMatcher(firstWordsHashBucketJoiner, firstWordsHashMatchComputer); } /** * Creates {@link AffOrgMatchVoter}s for {@link #createNameFirstWordsHashBucketMatcher()} */ public static ImmutableList<AffOrgMatchVoter> createNameFirstWordsHashBucketMatcherVoters() { CommonWordsVoter commonOrgNameWordsVoter = new CommonWordsVoter(ImmutableList.of(',', ';'), 2, 0.71, WITH_REGARD_TO_ORG_WORDS); commonOrgNameWordsVoter.setCommonSimilarWordCalculator(new CommonSimilarWordCalculator(0.9)); CommonWordsVoter commonAffNameWordsVoter = new CommonWordsVoter(ImmutableList.of(',', ';'), 2, 0.81, WITH_REGARD_TO_AFF_WORDS); commonAffNameWordsVoter.setCommonSimilarWordCalculator(new CommonSimilarWordCalculator(0.9)); CompositeMatchVoter commonAffOrgNameWordsVoter = new CompositeMatchVoter(ImmutableList.of(new CountryCodeLooseMatchVoter(), commonOrgNameWordsVoter, commonAffNameWordsVoter)); commonAffOrgNameWordsVoter.setMatchStrength(0.859f); return ImmutableList.of( createNameCountryStrictMatchVoter(0.981f, new GetOrgNameFunction()), createNameStrictCountryLooseMatchVoter(0.966f, new GetOrgNameFunction()), createSectionedNameStrictCountryLooseMatchVoter(0.943f, new GetOrgNameFunction()), createSectionedNameLevenshteinCountryLooseMatchVoter(0.934f, new GetOrgNameFunction()), createSectionedNameStrictCountryLooseMatchVoter(0.882f, new GetOrgShortNameFunction()), commonAffOrgNameWordsVoter); } //------------------------ PRIVATE -------------------------- private static AffOrgHashBucketJoiner createFirstWordsAffOrgHashBucketJoiner(Function<AffMatchOrganization, List<String>> getOrgNamesFunction) { AffOrgHashBucketJoiner firstWordsHashBucketJoiner = new AffOrgHashBucketJoiner(); OrganizationNameBucketHasher orgNameBucketHasher = new OrganizationNameBucketHasher(); orgNameBucketHasher.setGetOrgNamesFunction(getOrgNamesFunction); firstWordsHashBucketJoiner.setOrganizationBucketHasher(orgNameBucketHasher); return firstWordsHashBucketJoiner; } }
48.555556
183
0.748474
40f912adf9d4830ed8c46abe6f5e6bfd3a79478c
828
package com.learn_weather.sun.tryweather.mode; /** * Created by Sun on 2016/11/8. */ public class HeWeathCodition { String codeDaily; String codeNight; String txtDaily; String txtNight; public String getCodeDaily() { return codeDaily; } public void setCodeDaily(String codeDaily) { this.codeDaily=codeDaily; } public String getCodeNight() { return codeNight; } public void setCodeNight(String codeNight) { this.codeNight=codeNight; } public String getTxtDaily() { return txtDaily; } public void setTxtDaily(String txtDaily) { this.txtDaily=txtDaily; } public String getTxtNight() { return txtNight; } public void setTxtNight(String txtNight) { this.txtNight=txtNight; } }
18.4
48
0.634058
adb9d6a1509d191d2c898a3390b71c50fa489f0b
760
package org.iot.iotuser.service; import com.baomidou.mybatisplus.core.metadata.IPage; import org.iot.iotcommon.model.Permission; import org.iot.iotcommon.model.PageCondition; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; public interface PermissionService { List<Permission> selectList(); Permission selectById(@RequestParam("id") String id); Permission insert(@RequestBody Permission permission); Permission updateById(@RequestBody Permission permission); boolean deleteById(@RequestParam("id") String id); boolean deleteBatchIds(List<String> list); IPage<Permission> selectPage(@RequestBody PageCondition pageCondition); }
29.230769
75
0.792105
480c6e3fabd6a8fe34d1035ccec89da6e40a16e1
2,073
/** * Copyright 2009 - 2011 Sergio Bossa ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package terrastore.client; import terrastore.client.connection.Connection; /** * @author Sven Johansson * @author Sergio Bossa * */ public class PredicateOperation extends AbstractOperation { private final String bucket; private final String predicate; PredicateOperation(Connection connection, String bucket, String predicate) { super(connection); if (null == bucket) { throw new IllegalArgumentException("Bucket name cannot be null."); } if (null == predicate) { throw new IllegalArgumentException("Predicate cannot be null."); } this.bucket = bucket; this.predicate = predicate; } /** * Retrieves a Map of all keys/values matching the specified predicate. * * @param <T> The Java type to deserialize the values to. * @param type The Java class to deserialize the values to. * @return A Map of matching keys and values. * @throws TerrastoreClientException if the request is invalid, ie due to an incorrect predicate syntax. */ public <T> Values<T> get(Class<T> type) throws TerrastoreClientException { return connection.queryByPredicate(new Context(), type); } public class Context { public String getBucket() { return bucket; } public String getPredicate() { return predicate; } } }
31.409091
108
0.66329
a68c75212c1e99bde0625c1ef46fdccad58caa80
104
package cgeo.geocaching.maps.interfaces; public interface MapReadyCallback { void mapReady(); }
11.555556
40
0.75
59fc039e6bee1600ccda0a2fb2b40b6eac85f086
676
package io.volkan; import java.util.Collections; import java.util.List; public class Student { private List<TestScore> testScores; private String name; public Student(List<TestScore> scores, String name) { this.testScores = Collections.unmodifiableList(scores); this.name = name; } public String getName() { return this.name; } public List<TestScore> getTestScores() { return testScores; } public int getAverage() { int total = 0; for (TestScore testScore : testScores) { total += testScore.getPercentCorrect(); } return total / testScores.size(); } }
20.484848
63
0.621302
fcb5093e94115303336a0dd216c325c432b83dfd
1,739
/* * Copyright 2018-2022 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 * * 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 io.lettuce.test.resource; import io.lettuce.core.RedisURI; import io.lettuce.core.cluster.ClusterClientOptions; import io.lettuce.core.cluster.RedisClusterClient; import io.lettuce.test.settings.TestSettings; /** * @author Mark Paluch */ public class DefaultRedisClusterClient { private static final DefaultRedisClusterClient instance = new DefaultRedisClusterClient(); private RedisClusterClient redisClient; private DefaultRedisClusterClient() { redisClient = RedisClusterClient.create(RedisURI.Builder.redis(TestSettings.host(), TestSettings.port(900)) .withClientName("my-client").build()); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { FastShutdown.shutdown(redisClient); } }); } /** * Do not close the client. * * @return the default redis client for the tests. */ public static RedisClusterClient get() { instance.redisClient.setOptions(ClusterClientOptions.create()); return instance.redisClient; } }
32.811321
115
0.703278
52f98d8aeb6bdf967e566a95938cc62df65dd1f6
1,307
package com.Karim.Art.core; import com.android.volley.Request; import com.google.gson.reflect.TypeToken; import com.Karim.Art.ArtistoApplication; import com.Karim.Art.utils.NetworkUtils; import java.util.Map; /** * Created by HP-HP on 01-10-2016. */ public class BaseService { //Opens connection port via GET Method protected void executeGetRequest(String url, Map<String, String> headers, Map<String, String> params, TypeToken typeToken, ResponseListener listener) { url = NetworkUtils.getUrl(url, params); executeRequest(Request.Method.GET, url, headers, params, typeToken, listener); } //Opens connection port via POST Method protected void executePostRequest(String url, Map<String, String> headers, Map<String, String> params, TypeToken typeToken, ResponseListener listener) { url = NetworkUtils.getUrl(url, params); executeRequest(Request.Method.POST, url, headers, params, typeToken, listener); } protected void executeRequest(int method, String url, Map<String, String> headers, Map<String, String> params, TypeToken typeToken, ResponseListener listener) { BaseRequest request = new BaseRequest(method, url, headers, params,typeToken, listener); ArtistoApplication.getInstance().addToRequestQueue(request); } }
40.84375
164
0.742158
d6455302200f1cdc94afd0419a09d4ff5d597872
1,431
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.processors.query.h2.opt.join; /** * Multiplier for different collocation types. */ public enum CollocationModelMultiplier { /** Tables are collocated, cheap. */ COLLOCATED(1), /** */ UNICAST(50), /** */ BROADCAST(200), /** Force REPLICATED tables to be at the end of join sequence. */ REPLICATED_NOT_LAST(10_000); /** Multiplier value. */ private final int multiplier; /** * Constructor. * * @param multiplier Multiplier value. */ CollocationModelMultiplier(int multiplier) { this.multiplier = multiplier; } /** * @return Multiplier value. */ public int multiplier() { return multiplier; } }
26.5
102
0.682041
3a8324749c34e2d9b73a45fbd6acf8b2b9c979c1
1,867
/* * 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 cap_datos; import cap_logica.Docente; import cap_logica.Persona; import java.util.ArrayList; import java.util.Iterator; /** * * @author Sh */ public class ListaPersonas { private static ArrayList<Persona> misdatos = new ArrayList(); public static void agregar(Persona objP){ misdatos.add(objP); } public static ArrayList obtener(){ return misdatos; } public static ArrayList devolverDocentes(){ ArrayList temporal = new ArrayList(); Iterator elemento; elemento = misdatos.iterator(); while(elemento.hasNext()){ Persona objP = (Persona)elemento.next(); if(objP instanceof Docente){ temporal.add(objP); } } return temporal; } public static int[] cantidadDocentesPorGrado(){ int[] contador = new int[3]; Iterator elemento; elemento = misdatos.iterator(); while(elemento.hasNext()){ Persona objP = (Persona)elemento.next(); if(objP instanceof Docente){ if(((Docente) objP).getGrado().equalsIgnoreCase("BACHILLER")){ contador[0]++; } if(((Docente) objP).getGrado().equalsIgnoreCase("MAGISTER")){ contador[1]++; } if(((Docente) objP).getGrado().equalsIgnoreCase("DOCTOR")){ contador[2]++; } } } return contador; } }
27.057971
80
0.519014
ecf7c31cf921c2f3074a22ed0e0bd47943f78966
1,291
package de.fau.cs.mad.smile.android.encryption.remote; import android.os.AsyncTask; import android.os.Environment; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import de.fau.cs.mad.smile.android.encryption.App; public abstract class ContentLoaderTask<T> extends AsyncTask<Void, Void, T> { private final InputStream inputStream; protected ContentLoaderTask(InputStream inputStream) { this.inputStream = inputStream; } protected InputStream getInputStream() { return inputStream; } protected File copyToFile(InputStream inputStream) throws IOException { final File externalStorage = Environment.getExternalStorageDirectory(); final String targetDirName = FilenameUtils.concat(externalStorage.getAbsolutePath(), App.getContext().getPackageName()); final File targetDir = new File(targetDirName); File targetFile = null; int fileNumber = 0; do { targetFile = new File(targetDir, String.format("source-%05d.eml", fileNumber++)); } while (targetFile.exists()); FileUtils.copyInputStreamToFile(inputStream, targetFile); return targetFile; } }
30.738095
128
0.722696
d3b3243d31148ba1b846dbf85b44953107f58135
2,516
package org.flowant.stats.dao; import static org.flowant.stats.dao.Doc.EXP_DLR; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import org.flowant.stats.BaseTest; import org.flowant.util.DateTimeUtil; import org.junit.Assert; import org.junit.Test; public class TradeDaoTest extends BaseTest { int TEST_CNT = 100; @Test public void makeSpacerDocumentList() { String startYearMonth = DateTimeUtil.makeYearMonthString(2000, 1); String endYearMonth = DateTimeUtil.plusMonths(startYearMonth, TEST_CNT - 1); String yearMonth = startYearMonth; List<Doc> docList = new ArrayList<>(); for (int i = 0; i < TEST_CNT; i++) { Doc doc = TradeDAO.makeSpacerDoc(Optional.empty(), yearMonth); docList.add(doc); yearMonth = DateTimeUtil.plusOneMonth(yearMonth); } // make hole for (int i = 0; i < docList.size(); i++) { if (i % 3 == 0) docList.remove(i); } docList.remove(docList.size() - 1); docList = TradeDAO.makeSpacerDocList(docList.iterator(), startYearMonth, endYearMonth); logger.log(l, () -> "startYearMonth:" + startYearMonth); if (logger.isLoggable(l)) { for (int i = 0; i < docList.size(); i++) { logger.log(l, docList.get(i).toString()); } } logger.log(l, () -> "endYearMonth:" + endYearMonth); yearMonth = startYearMonth; Iterator<Doc> iter = docList.iterator(); while(iter.hasNext()) { Assert.assertEquals(yearMonth, iter.next().getYm()); yearMonth = DateTimeUtil.plusOneMonth(yearMonth); } Assert.assertEquals(endYearMonth, docList.get(docList.size() - 1).getYm()); } @Test public void findAllNationCode() throws IOException { List<String> sortedList = TradeDAO.findNationCode(DateTimeUtil.makeMonthsBefore(0), EXP_DLR, true); sortedList.forEach(s -> logger.log(l, () -> s.toString())); sortedList = TradeDAO.findNationCode(DateTimeUtil.makeMonthsBefore(1), EXP_DLR, false); sortedList.forEach(s -> logger.log(l, () -> s.toString())); } @Test public void findLatestYearMonth() throws IOException { Optional<String> yearMonth = TradeDAO.findLatestYm(true); logger.log(l, () -> "latestYearMonth:" + yearMonth.orElse("collection is empty")); } }
34.465753
107
0.628776
f73ee51fbf9933fcc2b36eb2b4e5a3f3a872906d
7,281
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alipay.sofa.rpc.transport; import com.alipay.sofa.rpc.client.ProviderInfo; import com.alipay.sofa.rpc.common.annotation.VisibleForTesting; import com.alipay.sofa.rpc.common.utils.NetUtils; import com.alipay.sofa.rpc.context.RpcRuntimeContext; import com.alipay.sofa.rpc.ext.ExtensionLoaderFactory; import com.alipay.sofa.rpc.log.Logger; import com.alipay.sofa.rpc.log.LoggerFactory; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Factory of ClientTransport * * @author <a href=mailto:[email protected]>GengZhang</a> */ public class ClientTransportFactory { /** * slf4j Logger for this class */ private final static Logger LOGGER = LoggerFactory .getLogger(ClientTransportFactory.class); /** * 不可复用长连接管理器 */ private final static ClientTransportHolder CLIENT_TRANSPORT_HOLDER = new NotReusableClientTransportHolder(); /** * 销毁长连接 * * @param clientTransport ClientTransport * @param disconnectTimeout disconnect timeout */ public static void releaseTransport(ClientTransport clientTransport, int disconnectTimeout) { if (clientTransport == null) { return; } boolean needDestroy = CLIENT_TRANSPORT_HOLDER.removeClientTransport(clientTransport); // 执行销毁动作 if (needDestroy) { if (disconnectTimeout > 0) { // 需要等待结束时间 int count = clientTransport.currentRequests(); if (count > 0) { // 有正在调用的请求 long start = RpcRuntimeContext.now(); if (LOGGER.isInfoEnabled()) { LOGGER.info("There are {} outstanding call in transport, wait {}ms to end", count, disconnectTimeout); } while (clientTransport.currentRequests() > 0 && RpcRuntimeContext.now() - start < disconnectTimeout) { // 等待返回结果 try { Thread.sleep(10); } catch (InterruptedException ignore) { } } } // 关闭前检查已有请求? } // disconnectTimeout已过 int count = clientTransport.currentRequests(); if (count > 0) { // 还有正在调用的请求 if (LOGGER.isWarnEnabled()) { LOGGER.warn("There are {} outstanding call in client transport, but shutdown now.", count); } } // 反向的也删一下 if (REVERSE_CLIENT_TRANSPORT_MAP != null) { String key = NetUtils.channelToString(clientTransport.remoteAddress(), clientTransport.localAddress()); REVERSE_CLIENT_TRANSPORT_MAP.remove(key); } clientTransport.destroy(); } } /** * 通过配置获取长连接 * * @param config 传输层配置 * @return 传输层 */ public static ClientTransport getClientTransport(ClientTransportConfig config) { return CLIENT_TRANSPORT_HOLDER.getClientTransport(config); } /** * 关闭全部客户端连接 */ public static void closeAll() { if (LOGGER.isInfoEnabled()) { LOGGER.info("Shutdown all client transport now!"); } try { CLIENT_TRANSPORT_HOLDER.destroy(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } @VisibleForTesting static ClientTransportHolder getClientTransportHolder() { return CLIENT_TRANSPORT_HOLDER; } /** * 反向虚拟的长连接对象, 缓存一个长连接一个<br> * {"127.0.0.1:22000<->127.0.0.1:54321": ClientTransport} */ private volatile static ConcurrentMap<String, ClientTransport> REVERSE_CLIENT_TRANSPORT_MAP = null; /** * 构建反向的(服务端到客户端)虚拟长连接 * * @param container Container of client transport * @param channel Exists channel from client * @return reverse client transport of exists channel */ public static ClientTransport getReverseClientTransport(String container, AbstractChannel channel) { if (REVERSE_CLIENT_TRANSPORT_MAP == null) { // 初始化 synchronized (ClientTransportFactory.class) { if (REVERSE_CLIENT_TRANSPORT_MAP == null) { REVERSE_CLIENT_TRANSPORT_MAP = new ConcurrentHashMap<String, ClientTransport>(); } } } String key = NetUtils.channelToString(channel.remoteAddress(), channel.localAddress()); ClientTransport transport = REVERSE_CLIENT_TRANSPORT_MAP.get(key); if (transport == null) { synchronized (ClientTransportFactory.class) { transport = REVERSE_CLIENT_TRANSPORT_MAP.get(key); if (transport == null) { ClientTransportConfig config = new ClientTransportConfig() .setProviderInfo(new ProviderInfo().setHost(channel.remoteAddress().getHostName()) .setPort(channel.remoteAddress().getPort())) .setContainer(container); transport = ExtensionLoaderFactory.getExtensionLoader(ClientTransport.class) .getExtension(config.getContainer(), new Class[] { ClientTransportConfig.class }, new Object[] { config }); transport.setChannel(channel); REVERSE_CLIENT_TRANSPORT_MAP.put(key, transport); // 保存唯一长连接 } } } return transport; } /** * Find reverse client transport by channel key * * @param channelKey channel key * @return client transport * @see ClientTransportFactory#getReverseClientTransport * @see NetUtils#channelToString */ public static ClientTransport getReverseClientTransport(String channelKey) { return REVERSE_CLIENT_TRANSPORT_MAP != null ? REVERSE_CLIENT_TRANSPORT_MAP.get(channelKey) : null; } /** * Remove client transport from reverse map by channel key * * @param channelKey channel key */ public static void removeReverseClientTransport(String channelKey) { if (REVERSE_CLIENT_TRANSPORT_MAP != null) { REVERSE_CLIENT_TRANSPORT_MAP.remove(channelKey); } } }
38.52381
119
0.611867
1f58fe0a9786309e4d35e59e3381bf3273f1e7ea
308
package com.ashish.comparator; import com.ashish.Employee; import java.util.Comparator; /** * Created by shaashis on 10/23/2015. */ public class SalaryComparator implements Comparator<Employee> { public int compare(Employee o1, Employee o2) { return o1.getSalary() - o2.getSalary(); } }
20.533333
63
0.711039
05fa104040b7546b5c80f9cb5924ef269f17180b
2,169
package de.koudingspawn.vault; import static com.github.tomakehurst.wiremock.client.WireMock.*; public class TestHelper { public static void generateLookupSelfStub() { stubFor(get(urlEqualTo("/v1/auth/token/lookup-self")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"request_id\": \"200ef4ee-7ca7-9d38-2e63-6002454e00d7\",\n" + " \"lease_id\": \"\",\n" + " \"renewable\": false,\n" + " \"lease_duration\": 0,\n" + " \"data\": {\n" + " \"accessor\": \"c69c3bd7-c142-c655-2757-77bfdc86b04a\",\n" + " \"creation_time\": 1536033750,\n" + " \"creation_ttl\": 0,\n" + " \"display_name\": \"root\",\n" + " \"entity_id\": \"\",\n" + " \"expire_time\": null,\n" + " \"explicit_max_ttl\": 0,\n" + " \"id\": \"c73ab0cb-41e6-b89c-7af6-96b36f1ac87b\",\n" + " \"meta\": null,\n" + " \"num_uses\": 0,\n" + " \"orphan\": true,\n" + " \"path\": \"auth/token/root\",\n" + " \"policies\": [\n" + " \"root\"\n" + " ],\n" + " \"ttl\": 0\n" + " },\n" + " \"wrap_info\": null,\n" + " \"warnings\": null,\n" + " \"auth\": null\n" + "}"))); } }
51.642857
101
0.288151
c1b36719d8f5cf29eb5e4343cc813b731e03aa89
3,927
package pl.polsl.orderadoctor.services; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pl.polsl.orderadoctor.dto.MedicalProductDto; import pl.polsl.orderadoctor.mappers.MedicalProductMapper; import pl.polsl.orderadoctor.model.Doctor; import pl.polsl.orderadoctor.model.MedicalProduct; import pl.polsl.orderadoctor.repositories.DoctorRepository; import pl.polsl.orderadoctor.repositories.MedicalProductRepository; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Log4j2 @Service @RequiredArgsConstructor public class MedicalProductServiceImpl implements MedicalProductService { private final MedicalProductRepository medicalProductRepository; private final DoctorRepository doctorRepository; private final MedicalProductMapper medicalProductMapper; @Override public void save(MedicalProduct medicalProduct) { medicalProductRepository.save(medicalProduct); } @Override public void saveAll(List<MedicalProduct> medicalProducts) { medicalProductRepository.saveAll(medicalProducts); } @Override public MedicalProduct findById(Long id) { MedicalProduct medicalProduct = medicalProductRepository.findById(id).get(); return medicalProduct; } @Override public List<MedicalProductDto> findAllSMedicalProductsDto() { List<MedicalProduct> products = medicalProductRepository .findAll(Sort.by(Sort.Direction.ASC, "name")); return products.stream().map(medicalProductMapper::medicalProductToMedicalProductDto).collect(Collectors.toList()); } @Override public MedicalProductDto findDtoById(Long id) { return medicalProductMapper.medicalProductToMedicalProductDto(medicalProductRepository.findById(id).get()); } @Override @Transactional public MedicalProductDto saveDto(MedicalProductDto dto, Long doctorId) { Optional<Doctor> doctorOptional = doctorRepository.findById(doctorId); if (!doctorOptional.isPresent()) { log.error("Doctor not found for id: " + doctorId); return new MedicalProductDto(); } else { Doctor doctor = doctorOptional.get(); //checks if medical product exists in database (same id) Optional<MedicalProduct> medicalProductOptional = doctor .getMedicalProducts() .stream() .filter(product -> product.getId().equals(dto.getId())) .findFirst(); //checks if medical product with the same name exists in database Optional<MedicalProduct> medicalProductOptional2 = doctor .getMedicalProducts() .stream() .filter(product -> product.getName().equals(dto.getName())) .findFirst(); if (medicalProductOptional.isPresent() || medicalProductOptional2.isPresent()) { if (medicalProductOptional.isPresent() && medicalProductOptional2.isPresent()) { doctor.getMedicalProducts().remove(medicalProductOptional.get()); doctor.getMedicalProducts().remove(medicalProductOptional2.get()); } else if (medicalProductOptional.isPresent()) doctor.getMedicalProducts().remove(medicalProductOptional.get()); else doctor.getMedicalProducts().remove(medicalProductOptional2.get()); } MedicalProduct medicalProduct = medicalProductMapper.medicalProductDtoToMedicalProduct(dto); doctor.addMedicalProduct(medicalProduct); doctorRepository.save(doctor); return dto; } } }
38.126214
123
0.69315
8c5c6fedacd3d9b469324ae57228d5011b194ae2
1,339
package com.csci.parser; import com.csci.grammar.*; public interface ParserInterface { /** * Parse program * * @return program * @throws Exception syntax exception */ Program parseProgram() throws Exception; /** * Parse definition list * * @return ListDef * @throws Exception syntax exception */ ListDef parseListDef() throws Exception; /** * Parse single definition * * @return Def * @throws Exception syntax exception */ Def parseDef() throws Exception; /** * Parse argument list * * @return ListArg * @throws Exception syntax exception */ ListArg parseListArg() throws Exception; /** * Parse single argument * * @return Arg * @throws Exception syntax exception */ Arg parseArg() throws Exception; /** * Parse expression * * @return Exp * @throws Exception syntax exception */ Exp parseExp() throws Exception; /** * Parse statement list * * @return ListStm * @throws Exception syntax exception */ ListStm parseListStm() throws Exception; /** * Parse single statement * * @return ListStm * @throws Exception syntax exception */ Stm parseStm() throws Exception; }
18.597222
44
0.584765
620e4cf21df4d47fd05983d657c15093545c449b
373
package conqueror.castle.exceptions; public class CastleNameAlreadyExistsEcpetion extends RuntimeException { public CastleNameAlreadyExistsEcpetion(String message, Throwable cause) { super(message, cause); } public CastleNameAlreadyExistsEcpetion(String message) { super(message); } public CastleNameAlreadyExistsEcpetion() { } }
24.866667
77
0.742627
4f3d827403bdd9fabb251485afe5b201157bff6c
678
package com.baeldung.junit5; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assumptions.*; public class AssumptionUnitTest { @Test public void trueAssumption() { assumeTrue(5 > 1, () -> "5 is greater the 1"); assertEquals(5 + 2, 7); } @Test public void falseAssumption() { assumeFalse(5 < 1, () -> "5 is less then 1"); assertEquals(5 + 2, 7); } @Test public void assumptionThat() { String someString = "Just a string"; assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4)); } }
24.214286
87
0.620944
3071d213282d054e100f5efb58d182b393960809
662
package com.github.tonydeng.desgin.command.fs.command; import com.github.tonydeng.desgin.command.fs.FileSystemReceiver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by tonydeng on 15/9/27. */ public class OpenFileCommand implements Command { private static final Logger log = LoggerFactory.getLogger(OpenFileCommand.class); private FileSystemReceiver fileSystem; public OpenFileCommand(FileSystemReceiver fs) { this.fileSystem = fs; } @Override public void execute() { if(log.isDebugEnabled()) log.debug("open file command......."); this.fileSystem.openFile(); } }
25.461538
85
0.703927
edf2b767b7fe095da2d2faeb6847d9ff4d93281b
790
package com.unascribed.fabrication.mixin.g_weird_tweaks.disable_lightning_fire; import com.unascribed.fabrication.support.EligibleIf; import com.unascribed.fabrication.support.MixinConfigPlugin; import net.minecraft.entity.LightningEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(LightningEntity.class) @EligibleIf(configAvailable="*.disable_lightning_fire") public class MixinLightningEntity { @Inject(at=@At("HEAD"), method="spawnFire(I)V", cancellable=true) public void preventFire(int spreadAttempts, CallbackInfo ci) { if (MixinConfigPlugin.isEnabled("*.disable_lightning_fire")) ci.cancel(); } }
37.619048
79
0.824051
3169a23b849a118bebad9e6afbc43d083e96eb45
19,078
/* * 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.geode.cache.query.internal; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.sql.Timestamp; import java.util.Date; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.cache.query.internal.index.DummyQRegion; import org.apache.geode.internal.cache.EntrySnapshot; import org.apache.geode.internal.cache.LocalRegion; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.test.junit.categories.SecurityTest; import org.apache.geode.test.junit.categories.UnitTest; @Category({UnitTest.class, SecurityTest.class}) public class RestrictedMethodInvocationAuthorizerTest { RestrictedMethodInvocationAuthorizer methodInvocationAuthorizer = new RestrictedMethodInvocationAuthorizer(null); @Test public void getClassShouldFail() throws Exception { Method method = Integer.class.getMethod("getClass"); assertFalse(methodInvocationAuthorizer.isWhitelisted(method)); } @Test public void toStringOnAnyObject() throws Exception { Method stringMethod = Integer.class.getMethod("toString"); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void equalsOnAnyObject() throws Exception { Method equalsMethod = Integer.class.getMethod("equals", Object.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(equalsMethod)); } @Test public void booleanMethodsAreWhiteListed() throws Exception { Method booleanValue = Boolean.class.getMethod("booleanValue"); assertTrue(methodInvocationAuthorizer.isWhitelisted(booleanValue)); } @Test public void toCharAtOnStringObject() throws Exception { Method stringMethod = String.class.getMethod("charAt", int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void codePointAtStringObject() throws Exception { Method stringMethod = String.class.getMethod("codePointAt", int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void codePointBeforeStringObject() throws Exception { Method stringMethod = String.class.getMethod("codePointBefore", int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void codePointCountStringObject() throws Exception { Method stringMethod = String.class.getMethod("codePointCount", int.class, int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void compareToStringObject() throws Exception { Method stringMethod = String.class.getMethod("compareTo", String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void compareToIgnoreCaseStringObject() throws Exception { Method stringMethod = String.class.getMethod("compareToIgnoreCase", String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void concatStringObject() throws Exception { Method stringMethod = String.class.getMethod("compareTo", String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void containsStringObject() throws Exception { Method stringMethod = String.class.getMethod("contains", CharSequence.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void contentEqualsStringObject() throws Exception { Method stringMethod = String.class.getMethod("contentEquals", CharSequence.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void contentEqualsWithStringBufferStringObject() throws Exception { Method stringMethod = String.class.getMethod("contentEquals", StringBuffer.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void endsWithOnStringObject() throws Exception { Method stringMethod = String.class.getMethod("endsWith", String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void equalsIgnoreCase() throws Exception { Method stringMethod = String.class.getMethod("equalsIgnoreCase", String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void getBytesOnString() throws Exception { Method stringMethod = String.class.getMethod("getBytes"); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void getBytesWithCharsetOnString() throws Exception { Method stringMethod = String.class.getMethod("getBytes", Charset.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void hashCodeOnStringObject() throws Exception { Method stringMethod = String.class.getMethod("hashCode"); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void indexOfOnStringObject() throws Exception { Method stringMethod = String.class.getMethod("indexOf", int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void indexOfWithStringOnStringObject() throws Exception { Method stringMethod = String.class.getMethod("indexOf", String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void indexOfWithStringAndIntOnStringObject() throws Exception { Method stringMethod = String.class.getMethod("indexOf", String.class, int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void internOnStringObject() throws Exception { Method stringMethod = String.class.getMethod("intern"); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void isEmpty() throws Exception { Method stringMethod = String.class.getMethod("isEmpty"); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void lastIndexOfWithIntOnString() throws Exception { Method stringMethod = String.class.getMethod("lastIndexOf", int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void lastIndexOfWithIntAndFronIndexOnString() throws Exception { Method stringMethod = String.class.getMethod("lastIndexOf", int.class, int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void lastIndexOfWithStringOnString() throws Exception { Method stringMethod = String.class.getMethod("lastIndexOf", String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void lastIndexOfWithStringAndFromIndexOnString() throws Exception { Method stringMethod = String.class.getMethod("lastIndexOf", String.class, int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void lengthOnString() throws Exception { Method stringMethod = String.class.getMethod("length"); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void matchesOnString() throws Exception { Method stringMethod = String.class.getMethod("matches", String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void offsetByCodePointsOnString() throws Exception { Method stringMethod = String.class.getMethod("offsetByCodePoints", int.class, int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void regionMatchesWith5ParamsOnString() throws Exception { Method stringMethod = String.class.getMethod("regionMatches", boolean.class, int.class, String.class, int.class, int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void regionMatchesWith4ParamsOnString() throws Exception { Method stringMethod = String.class.getMethod("regionMatches", int.class, String.class, int.class, int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void replaceOnString() throws Exception { Method stringMethod = String.class.getMethod("replace", char.class, char.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void replaceWithCharSequenceOnString() throws Exception { Method stringMethod = String.class.getMethod("replace", CharSequence.class, CharSequence.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void replaceAllOnString() throws Exception { Method stringMethod = String.class.getMethod("replaceAll", String.class, String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void replaceFirstOnString() throws Exception { Method stringMethod = String.class.getMethod("replaceFirst", String.class, String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void splitOnString() throws Exception { Method stringMethod = String.class.getMethod("split", String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void splitWithLimitOnString() throws Exception { Method stringMethod = String.class.getMethod("split", String.class, int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void startsOnString() throws Exception { Method stringMethod = String.class.getMethod("startsWith", String.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void startsWithOffsetOnString() throws Exception { Method stringMethod = String.class.getMethod("startsWith", String.class, int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void substringOnString() throws Exception { Method stringMethod = String.class.getMethod("substring", int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void substringWithEndIndexOnString() throws Exception { Method stringMethod = String.class.getMethod("substring", int.class, int.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void toCharArrayOnString() throws Exception { Method stringMethod = String.class.getMethod("toCharArray"); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void toLowerCaseOnStringObject() throws Exception { Method stringMethod = String.class.getMethod("toLowerCase"); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void toUpperCaseOnStringObject() throws Exception { Method stringMethod = String.class.getMethod("toUpperCase"); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void trimOnString() throws Exception { Method stringMethod = String.class.getMethod("trim"); assertTrue(methodInvocationAuthorizer.isWhitelisted(stringMethod)); } @Test public void utilDateAfterMethodIsWhiteListed() throws Exception { Method method = Date.class.getMethod("after", Date.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(method)); } @Test public void sqlDateAfterMethodIsWhiteListed() throws Exception { Method method = java.sql.Date.class.getMethod("after", Date.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(method)); } @Test public void utilDateBeforeMethodIsWhiteListed() throws Exception { Method method = Date.class.getMethod("before", Date.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(method)); } @Test public void sqlDateBeforeMethodIsWhiteListed() throws Exception { Method method = java.sql.Date.class.getMethod("before", Date.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(method)); } @Test public void timestampAfterMethodIsWhiteListed() throws Exception { Method method = Timestamp.class.getMethod("after", Timestamp.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(method)); } @Test public void sqlTimestampBeforeMethodIsWhiteListed() throws Exception { Method method = Timestamp.class.getMethod("before", Timestamp.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(method)); } @Test public void sqlTimestampGetNanosIsWhiteListed() throws Exception { Method method = Timestamp.class.getMethod("getNanos"); assertTrue(methodInvocationAuthorizer.isWhitelisted(method)); } @Test public void sqlTimestampGetTimeIsWhiteListed() throws Exception { Method method = Timestamp.class.getMethod("getTime"); assertTrue(methodInvocationAuthorizer.isWhitelisted(method)); } @Test public void getKeyForMapEntryIsWhiteListed() throws Exception { Method getKeyMethod = Map.Entry.class.getMethod("getKey"); assertTrue(methodInvocationAuthorizer.isWhitelisted(getKeyMethod)); } @Test public void getValueForMapEntryIsWhiteListed() throws Exception { Method getValueMethod = Map.Entry.class.getMethod("getValue"); assertTrue(methodInvocationAuthorizer.isWhitelisted(getValueMethod)); } @Test public void getKeyForMapEntrySnapShotIsWhiteListed() throws Exception { Method getKeyMethod = EntrySnapshot.class.getMethod("getKey"); assertTrue(methodInvocationAuthorizer.isWhitelisted(getKeyMethod)); } @Test public void getValueForMapEntrySnapShotIsWhiteListed() throws Exception { Method getValueMethod = EntrySnapshot.class.getMethod("getValue"); assertTrue(methodInvocationAuthorizer.isWhitelisted(getValueMethod)); } @Test public void getKeyForNonTXEntryIsWhiteListed() throws Exception { Method getKeyMethod = LocalRegion.NonTXEntry.class.getMethod("getKey"); assertTrue(methodInvocationAuthorizer.isWhitelisted(getKeyMethod)); } @Test public void getValueForNonTXEntryIsWhiteListed() throws Exception { Method getValueMethod = LocalRegion.NonTXEntry.class.getMethod("getValue"); assertTrue(methodInvocationAuthorizer.isWhitelisted(getValueMethod)); } @Test public void mapMethodsForQRegionAreWhiteListed() throws Exception { testMapMethods(QRegion.class); } @Test public void mapMethodsForDummyQRegionAreWhiteListed() throws Exception { testMapMethods(DummyQRegion.class); } @Test public void mapMethodsForPartitionedRegionAreWhiteListed() throws Exception { Class clazz = PartitionedRegion.class; Method entrySet = clazz.getMethod("entrySet"); Method keySet = clazz.getMethod("keySet"); Method values = clazz.getMethod("values"); Method containsKey = clazz.getMethod("containsKey", Object.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(entrySet)); assertTrue(methodInvocationAuthorizer.isWhitelisted(keySet)); assertTrue(methodInvocationAuthorizer.isWhitelisted(values)); assertTrue(methodInvocationAuthorizer.isWhitelisted(containsKey)); } @Test public void numberMethodsForByteAreWhiteListed() throws Exception { testNumberMethods(Byte.class); } @Test public void numberMethodsForDoubleAreWhiteListed() throws Exception { testNumberMethods(Double.class); } @Test public void numberMethodsForFloatAreWhiteListed() throws Exception { testNumberMethods(Float.class); } @Test public void numberMethodsForIntegerAreWhiteListed() throws Exception { testNumberMethods(Integer.class); } @Test public void numberMethodsForShortAreWhiteListed() throws Exception { testNumberMethods(Short.class); } @Test public void numberMethodsForBigDecimalAreWhiteListed() throws Exception { testNumberMethods(BigDecimal.class); } @Test public void numberMethodsForNumberAreWhiteListed() throws Exception { testNumberMethods(BigInteger.class); } @Test public void numberMethodsForAtomicIntegerAreWhiteListed() throws Exception { testNumberMethods(AtomicInteger.class); } @Test public void numberMethodsForAtomicLongAreWhiteListed() throws Exception { testNumberMethods(AtomicLong.class); } private void testNumberMethods(Class clazz) throws NoSuchMethodException { Method byteValue = clazz.getMethod("byteValue"); Method doubleValue = clazz.getMethod("doubleValue"); Method intValue = clazz.getMethod("intValue"); Method floatValue = clazz.getMethod("longValue"); Method longValue = clazz.getMethod("floatValue"); Method shortValue = clazz.getMethod("shortValue"); assertTrue(methodInvocationAuthorizer.isWhitelisted(byteValue)); assertTrue(methodInvocationAuthorizer.isWhitelisted(doubleValue)); assertTrue(methodInvocationAuthorizer.isWhitelisted(intValue)); assertTrue(methodInvocationAuthorizer.isWhitelisted(floatValue)); assertTrue(methodInvocationAuthorizer.isWhitelisted(longValue)); assertTrue(methodInvocationAuthorizer.isWhitelisted(shortValue)); } private void testMapMethods(Class clazz) throws NoSuchMethodException { Method entrySet = clazz.getMethod("entrySet"); Method keySet = clazz.getMethod("keySet"); Method values = clazz.getMethod("values"); Method getEntries = clazz.getMethod("getEntries"); Method getValues = clazz.getMethod("getValues"); Method containsKey = clazz.getMethod("containsKey", Object.class); assertTrue(methodInvocationAuthorizer.isWhitelisted(entrySet)); assertTrue(methodInvocationAuthorizer.isWhitelisted(keySet)); assertTrue(methodInvocationAuthorizer.isWhitelisted(values)); assertTrue(methodInvocationAuthorizer.isWhitelisted(getEntries)); assertTrue(methodInvocationAuthorizer.isWhitelisted(getValues)); assertTrue(methodInvocationAuthorizer.isWhitelisted(containsKey)); } }
37.04466
100
0.777754
6a180ba8aff67903707121b9aef2b59726c0d951
775
package com.apprisingsoftware.util; import java.util.function.BiFunction; /** * Represents a function that accepts two int-valued arguments and produces a * result. This is the {@code int}-consuming primitive specialization for * {@link BiFunction}. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #apply(int, int)}. * * @param <R> the type of the result of the function * * @see BiFunction */ @FunctionalInterface public interface BiIntFunction<R> { /** * Applies this function to the given argument. * * @param value1 the first function argument * @param value2 the second function argument * @return the function result */ R apply(int value1, int value2); }
26.724138
77
0.695484
dcff76cef839085c75a4bc8a1f375ac7c6eb6642
736
import java.sql.*; class JDBCPrep4 { public static void main(String[] args) { try { Connection con = DriverManager.getConnection("jdbc:odbc:NGP","",""); PreparedStatement pst = con.prepareStatement("delete from emp where empno=?"); pst.setString(1,args[0]); int a = pst.executeUpdate(); System.out.println(a+" Row Deleted"); PreparedStatement pst2 = con.prepareStatement("Select * from emp"); ResultSet rs = pst2.executeQuery(); System.out.println("Empno\tEmpName\tCity\tSalary"); while(rs.next()) { System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4)); } } catch(Exception ex) { System.out.println("Error Occured: " + ex); } } }
25.37931
103
0.654891
4870b104fe4d019c1d8f32d621a9d25023304ab9
1,575
package com.jc.es.service.impl; import com.jc.es.service.BookService; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.Arrays; @Service public class BookServiceImpl implements BookService{ @Autowired RestHighLevelClient restHighLevelClient; @Override public boolean testEsRestClient(){ SearchRequest searchRequest = new SearchRequest("gdp_tops*"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.termQuery("city","北京")); searchRequest.source(sourceBuilder); SearchResponse response = null; try { response = restHighLevelClient.search(searchRequest); } catch (IOException e) { e.printStackTrace(); return false; } Arrays.stream(response.getHits().getHits()) .forEach(i->{ System.out.println(i.getIndex()); System.out.println(i.getType()); System.out.println(i.getSourceAsString()); }); System.out.println(response.getHits().totalHits); return true; } }
34.23913
70
0.694603
50c2baad35fdea60c492305eabf1cc41724bc85f
8,898
package com.coralogix.jenkins.pipeline; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.cloudbees.plugins.credentials.domains.DomainRequirement; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import com.cloudbees.workflow.rest.external.RunExt; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import hudson.Extension; import hudson.model.Item; import hudson.model.Run; import hudson.model.TaskListener; import hudson.security.ACL; import hudson.util.ListBoxModel; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.HashSet; import java.util.Set; import java.util.List; import java.util.ArrayList; import com.coralogix.jenkins.model.Log; import com.coralogix.jenkins.utils.CoralogixAPI; import com.coralogix.jenkins.credentials.CoralogixCredential; /** * Allows to send metrics to Coralogix * * @author Eldar Aliiev * @version 1.0.0 * @since 2020-10-27 */ public class CoralogixMetricsSend extends Step { /** * Coralogix Private Key */ private final String privateKeyCredentialId; /** * Application name */ private final String application; /** * Subsystem name */ private final String subsystem; /** * Stages metrics splitting */ private final Boolean splitStages; /** * Initialize pipeline step * * @param application application name */ @DataBoundConstructor public CoralogixMetricsSend(String privateKeyCredentialId, String application, String subsystem, Boolean splitStages) { this.privateKeyCredentialId = privateKeyCredentialId; this.application = application; this.subsystem = subsystem; this.splitStages = splitStages; } /** * Coralogix Private Key getter * * @return the currently configured private key */ public String getPrivateKeyCredentialId() { return this.privateKeyCredentialId; } /** * Application name getter * * @return application name */ public String getApplication() { return this.application; } /** * Subsystem name getter * * @return subsystem name */ public String getSubsystem() { return this.subsystem; } /** * Stages metrics splitting status getter * * @return stages metrics splitting status */ public Boolean getSplitStages() { return this.splitStages; } /** * Start step execution * * @param context execution context * @return execution step * @throws Exception */ @Override public StepExecution start(StepContext context) throws Exception { return new Execution(context, this.privateKeyCredentialId, this.application, this.subsystem, this.splitStages); } /** * Pipeline step executor */ @SuppressFBWarnings(value = "SE_TRANSIENT_FIELD_NOT_RESTORED", justification = "Only used when starting.") private static class Execution extends SynchronousNonBlockingStepExecution<Void> { /** * Serial UID */ private static final long serialVersionUID = 1L; /** * Coralogix Private Key */ private transient final String privateKeyCredentialId; /** * Application name */ private transient final String application; /** * Subsystem name */ private transient final String subsystem; /** * Stages metrics splitting */ private transient final Boolean splitStages; /** * Pipeline step executor initialization * * @param context execution context * @param application application name */ Execution(StepContext context, String privateKeyCredentialId, String application, String subsystem, Boolean splitStages) { super(context); this.privateKeyCredentialId = privateKeyCredentialId; this.application = application; this.subsystem = subsystem; this.splitStages = splitStages; } /** * Executor step action * * @return action result * @throws Exception */ @Override protected Void run() throws Exception { WorkflowRun run = getContext().get(WorkflowRun.class); Run<?, ?> build = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); GsonBuilder builder = new GsonBuilder(); JsonObject metrics = (JsonObject) builder.create().toJsonTree(RunExt.create(run)); JsonArray stages = metrics.getAsJsonArray("stages"); metrics.remove("_links"); metrics.addProperty("job", build.getParent().getFullName()); for(int i = 0; i < stages.size(); i++) { JsonObject stage = stages.get(i).getAsJsonObject(); stage.remove("_links"); stage.remove("stageFlowNodes"); stages.set(i, stage); } try { List<Log> logEntries = new ArrayList<>(); if(splitStages) { for(JsonElement stage : stages) { JsonObject record = metrics.deepCopy(); record.remove("stages"); record.add("stage", stage); logEntries.add(new Log( 1, record.toString(), "job", "", "", build.getDisplayName() )); } } else { logEntries.add(new Log( 1, metrics.toString(), "job", "", "", build.getDisplayName() )); } CoralogixAPI.sendLogs( CoralogixAPI.retrieveCoralogixCredential(build, privateKeyCredentialId), application, subsystem, logEntries ); } catch (Exception e) { listener.getLogger().println("Cannot send pipeline metrics to Coralogix!"); } return null; } } /** * Jenkins pipeline step definition */ @Extension public static class DescriptorImpl extends StepDescriptor { /** * Pipeline step description display value * * @return pipeline step description */ @Override public String getDisplayName() { return "Send metrics to Coralogix"; } /** * Pipeline step name display value * * @return pipeline step name */ @Override public String getFunctionName() { return "coralogixMetricsSend"; } /** * Context builder * * @return execution context */ @Override public Set<? extends Class<?>> getRequiredContext() { Set<Class<?>> contexts = new HashSet<>(); contexts.add(WorkflowRun.class); contexts.add(TaskListener.class); contexts.add(Run.class); return contexts; } /** * Coralogix Private Keys list builder * * @param owner Credentials owner * @param uri Current URL * @return allowed credentials list */ @SuppressWarnings("unused") public ListBoxModel doFillPrivateKeyCredentialIdItems(@AncestorInPath Item owner, @QueryParameter String uri) { List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(uri).build(); return new StandardListBoxModel().includeEmptyValue().includeAs(ACL.SYSTEM, owner, CoralogixCredential.class, domainRequirements); } } }
30.57732
142
0.587548
bb9c3130e843596deb9c188af654a861ddc43efe
654
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.user.auth.secondparty.token.verify response. * * @author auto create * @since 1.0, 2019-07-16 20:05:01 */ public class AlipayUserAuthSecondpartyTokenVerifyResponse extends AlipayResponse { private static final long serialVersionUID = 2455352858373156429L; /** * 淘宝用户id */ @ApiField("tb_user_id") private String tbUserId; public void setTbUserId(String tbUserId) { this.tbUserId = tbUserId; } public String getTbUserId( ) { return this.tbUserId; } }
21.096774
83
0.711009
bba1e4df4e9b6a7664600dc0fb00c33524432443
11,527
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.entitlement; /** * Entitlement and XACML related constant values */ public class PDPConstants { public static final String POLICY_TYPE = "policyType"; public static final String POLICY_EDITOR_TYPE = "policyEditor"; public static final String BASIC_POLICY_EDITOR_META_DATA = "basicPolicyEditorMetaData"; public static final String BASIC_POLICY_EDITOR_META_DATA_AMOUNT = "NoOfBasicPolicyEditorMetaData"; public static final String ACTIVE_POLICY = "isActive"; public static final String PROMOTED_POLICY = "promoted"; public static final String POLICY_VERSION = "version"; public static final String LAST_MODIFIED_TIME = "lastModifiedTime"; public static final String LAST_MODIFIED_USER = "lastModifiedUser"; public static final String POLICY_LIFE_CYCLE = "policyLifeStatus"; public static final String POLICY_ORDER = "policyOrder"; public static final String MAX_POLICY_ORDER = "maxPolicyOrder"; public static final String POLICY_ELEMENT = "Policy"; public static final String POLICY_REFERENCE = "policyIdReferences"; public static final String POLICY_SET_REFERENCE = "policySetIdReferences"; public static final String APPLY_ELEMENT = "Apply"; public static final String MATCH_ELEMENT = "Match"; public static final String SUBJECT_ELEMENT = "Subject"; public static final String ACTION_ELEMENT = "Action"; public static final String RESOURCE_ELEMENT = "Resource"; public static final String ENVIRONMENT_ELEMENT = "Environment"; public static final String SUBJECT_CATEGORY_ID = "Subject"; public static final String ACTION_CATEGORY_ID = "Action"; public static final String RESOURCE_CATEGORY_ID = "Resource"; public static final String ENVIRONMENT_CATEGORY_ID = "Environment"; public static final String ANY_OF = "AnyOf"; public static final String ALL_OF = "AllOf"; public static final String RESOURCE_CATEGORY_URI = "urn:oasis:names:tc:xacml:3.0:" + "attribute-category:resource"; public static final String SUBJECT_CATEGORY_URI = "urn:oasis:names:tc:xacml:1.0:" + "subject-category:access-subject"; public static final String ACTION_CATEGORY_URI = "urn:oasis:names:tc:xacml:3.0:" + "attribute-category:action"; public static final String ENVIRONMENT_CATEGORY_URI = "urn:oasis:names:tc:xacml:3.0:" + "attribute-category:environment"; public static final String TARGET_ELEMENT = "Target"; public static final String RULE_ELEMENT = "Rule"; public static final String CONDITION_ELEMENT = "Condition"; public static final String FUNCTION_ELEMENT = "Function"; public static final String ATTRIBUTE_SELECTOR = "AttributeSelector"; public static final String ATTRIBUTE_VALUE = "AttributeValue"; public static final String FUNCTION = "Function"; public static final String VARIABLE_REFERENCE = "VariableReference"; public static final String ATTRIBUTE_DESIGNATOR = "AttributeDesignator"; public static final String ATTRIBUTE_ID = "AttributeId"; public static final String ATTRIBUTE = "Attribute"; public static final String DATA_TYPE = "DataType"; public static final String CATEGORY = "Category"; public static final String REQUEST_CONTEXT_PATH = "RequestContextPath"; public static final String SUBJECT_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; public static final String SUBJECT_CATEGORY_DEFAULT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; public static final String SUBJECT_ID_ROLE = "http://wso2.org/claims/role"; public static final String RULE_EFFECT_PERMIT = "Permit"; public static final String RULE_EFFECT_DENY = "Deny"; public static final String RESPONSE_RESULT = "Result"; public static final String RESPONSE_DECISION = "Decision"; public static final String RESPONSE_RESOURCE_ID = "ResourceId"; public static final String POLICY_META_DATA = "policyMetaData"; public static final int POLICY_META_DATA_ARRAY_LENGTH = 4; public static final String AUTHORIZATION_PERMISSION = "/permission/admin/configure"; public static final String ENTITLEMENT_CACHE_MANAGER = "ENTITLEMENT_CACHE_MANAGER"; public static final String PIP_RESOURCE_CACHE = "PIP_RESOURCE_CACHE"; public static final String PDP_DECISION_CACHE = "PDP_DECISION_CACHE"; public static final String PDP_SIMPLE_DECISION_CACHE = "PDP_SIMPLE_DECISION_CACHE"; public static final String PDP_DECISION_INVALIDATION_CACHE = "PDP_DECISION_INVALIDATION_CACHE"; public static final String PIP_ABSTRACT_INVALIDATION_CACHE = "PIP_ABSTRACT_INVALIDATION_CACHE"; public static final String POLICY_SEARCH_CACHE = "POLICY_SEARCH_CACHE"; public static final String PIP_ABSTRACT_RESOURCE_CACHE = "PIP_ABSTRACT_RESOURCE_CACHE"; public static final String PIP_ATTRIBUTE_CACHE = "PIP_ATTRIBUTE_CACHE"; public static final String PIP_ABSTRACT_ATTRIBUTE_CACHE = "PIP_ABSTRACT_ATTRIBUTE_CACHE"; public static final String ENTITLEMENT_POLICY_INVALIDATION_CACHE = "ENTITLEMENT_POLICY_INVALIDATION_CACHE"; public static final int DEFAULT_ITEMS_PER_PAGE = 10; public static final String UNKNOWN = "UNKNOWN"; public static final String REQUEST_ELEMENT = "Request"; public static final String REQ_RES_CONTEXT = "urn:oasis:names:tc:xacml:2.0:context:schema:os"; public static final String REQ_SCHEME = "http://www.w3.org/2001/XMLSchema-instance"; public static final String STRING_DATA_TYPE = "http://www.w3.org/2001/XMLSchema#string"; public static final String RESOURCE_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; public static final String ACTION_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:action:action-id"; public static final String ENVIRONMENT_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:environment:environment-id"; public static final String RESOURCE_SCOPE_ID = "urn:oasis:names:tc:xacml:1.0:resource:scope"; public static final String RESOURCE_DESCENDANTS = "Descendants"; public static final String RESOURCE_CHILDREN = "Children"; public static final String ATTRIBUTE_SEPARATOR = ","; public static final String SEARCH_WARNING_MESSAGE1 = "Attribute values are not defined directly"; public static final String SEARCH_WARNING_MESSAGE2 = "No Attributes are defined"; public static final String SEARCH_WARNING_MESSAGE3 = "Attribute Selector Element is contained " + "with Xpath expression"; public static final String SEARCH_WARNING_MESSAGE4 = "Apply Element is not contained within Condition Element"; public static final String SEARCH_ERROR = "Search_Error"; public static final String SEARCH_ERROR_MESSAGE = "Therefore Advance Search can not be proceeded. " + "Please de-active this policy, If policy is not" + " relevant for the search"; public static final String XACML_3_POLICY_XMLNS = "urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"; public static final String XACML_2_POLICY_XMLNS = "urn:oasis:names:tc:xacml:2.0:policy:schema:os"; public static final String XACML_1_POLICY_XMLNS = "urn:oasis:names:tc:xacml:1.0:policy"; public static final String XACML_3_POLICY_SCHEMA_FILE = "xacml3.xsd"; public static final String XACML_2_POLICY_SCHEMA_FILE = "xacml2.xsd"; public static final String XACML_1_POLICY_SCHEMA_FILE = "xacml1.xsd"; public static final String ENTITLEMENT_POLICY_PUBLISHER = "/repository/identity/entitlement/publisher/"; public static final String ENTITLEMENT_POLICY_PUBLISHER_VERIFICATION = "/repository/identity/entitlement/publisher/verification/"; public static final String ENTITLEMENT_POLICY_VERSION = "/repository/identity/entitlement/policy/version/"; public static final String ENTITLEMENT_POLICY_DATA = "/repository/identity/entitlement/policy/data/"; public static final String ENTITLEMENT_POLICY_PAP = "/repository/identity/entitlement/policy/pap/"; // entitlement.properties file configurations public static final String ON_DEMAND_POLICY_LOADING = "PDP.OnDemangPolicyLoading.Enable"; public static final String ON_DEMAND_POLICY_MAX_POLICY_ENTRIES = "PDP.OnDemangPolicyLoading.MaxInMemoryPolicies"; public static final String MAX_POLICY_REFERENCE_ENTRIES = "PDP.References.MaxPolicyEntries"; public static final int MAX_NO_OF_IN_MEMORY_POLICIES = 10; public static final String DECISION_CACHING = "PDP.DecisionCaching.Enable"; public static final String DECISION_CACHING_INTERVAL = "PDP.DecisionCaching.CachingInterval"; public static final String ATTRIBUTE_CACHING = "PDP.AttributeCaching.Enable"; public static final String ATTRIBUTE_CACHING_INTERVAL = "PDP.AttributeCaching.CachingInterval"; public static final String RESOURCE_CACHING = "PDP.ResourceCaching.Enable"; public static final String RESOURCE_CACHING_INTERVAL = "PDP.DecisionCaching.CachingInterval"; public static final String PDP_ENABLE = "PDP.Enable"; public static final String PAP_ENABLE = "PAP.Enable"; public static final String BALANA_CONFIG_ENABLE = "PDP.Balana.Config.Enable"; public static final String MULTIPLE_DECISION_PROFILE_ENABLE = "PDP.Multiple.Decision.Profile.Enable"; public static final String FILESYSTEM_POLICY_PATH = "PAP.Policy.Add.Start.Policy.File.Path"; public static final String START_UP_POLICY_ADDING = "PAP.Policy.Add.Start.Enable"; public static final String POLICY_ID_REGEXP_PATTERN = "PAP.Policy.Id.Regexp.Pattern"; public static final String ENTITLEMENT_ITEMS_PER_PAGE = "PAP.Items.Per.Page"; public static final String PDP_GLOBAL_COMBINING_ALGORITHM = "PDP.Global.Policy.Combining.Algorithm"; public static final String REGISTRY_MEDIA_TYPE = "application/xacml-policy+xml"; public static final String ENTITLEMENT_ENGINE_CACHING_INTERVAL = "Entitlement.Engine.CachingInterval"; public static final String PDP_REGISTRY_LEVEL_POLICY_CACHE_CLEAR = "PDP.Registry.Level.Policy.Cache.Clear"; public static final String POLICY_CACHING_INTERVAL = "PDP.PolicyCaching.CachingInterval"; public static final String XACML_JSON_SHORT_FORM_ENABLED = "JSON.Shorten.Form.Enabled"; public static final String USER_CATEGORY = "http://wso2.org/identity/user"; public static final String USER_TYPE_ID = USER_CATEGORY + "/user-type"; }
40.304196
115
0.741737
768e0d1b1a4b3ce8dae5e3f0ca1c922a0395c069
2,753
package mcjty.rftools.shapes; import io.netty.buffer.ByteBuf; import mcjty.lib.network.TypedMapTools; import mcjty.lib.thirteen.Context; import mcjty.lib.typed.Key; import mcjty.lib.typed.Type; import mcjty.lib.typed.TypedMap; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumHand; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import java.util.function.Supplier; /** * This is a packet that can be used to update the NBT on the held item of a player. */ public class PacketUpdateNBTShapeCard implements IMessage { private TypedMap args; @Override public void fromBytes(ByteBuf buf) { args = TypedMapTools.readArguments(buf); } @Override public void toBytes(ByteBuf buf) { TypedMapTools.writeArguments(buf, args); } public PacketUpdateNBTShapeCard() { } public PacketUpdateNBTShapeCard(ByteBuf buf) { fromBytes(buf); } public PacketUpdateNBTShapeCard(TypedMap arguments) { this.args = arguments; } public void handle(Supplier<Context> supplier) { Context ctx = supplier.get(); ctx.enqueueWork(() -> { EntityPlayerMP playerEntity = ctx.getSender(); ItemStack heldItem = playerEntity.getHeldItem(EnumHand.MAIN_HAND); if (heldItem.isEmpty()) { return; } NBTTagCompound tagCompound = heldItem.getTagCompound(); if (tagCompound == null) { tagCompound = new NBTTagCompound(); heldItem.setTagCompound(tagCompound); } for (Key<?> akey : args.getKeys()) { String key = akey.getName(); if (Type.STRING.equals(akey.getType())) { tagCompound.setString(key, (String) args.get(akey)); } else if (Type.INTEGER.equals(akey.getType())) { tagCompound.setInteger(key, (Integer) args.get(akey)); } else if (Type.DOUBLE.equals(akey.getType())) { tagCompound.setDouble(key, (Double) args.get(akey)); } else if (Type.BOOLEAN.equals(akey.getType())) { tagCompound.setBoolean(key, (Boolean) args.get(akey)); } else if (Type.BLOCKPOS.equals(akey.getType())) { throw new RuntimeException("BlockPos not supported for PacketUpdateNBTItem!"); } else if (Type.ITEMSTACK.equals(akey.getType())) { throw new RuntimeException("ItemStack not supported for PacketUpdateNBTItem!"); } } }); ctx.setPacketHandled(true); } }
36.223684
99
0.621504
ba2a8bbb09126000ab1da7fdba56d01c54155ecf
775
package com.sen.concurrency2.chapter17; import java.util.Random; /** * @Author: Sen * @Date: 2019/12/11 01:34 * @Description: 取货工人 */ public class WorkerThread extends Thread { private final Channel channel; private final static Random RANDOM = new Random(System.currentTimeMillis()); public WorkerThread(String name, Channel channel) { super(name); this.channel = channel; } @Override public void run() { while (true) { Request request = channel.take(); System.out.println(getName() + " take " + request); try { Thread.sleep(RANDOM.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
22.794118
80
0.579355
7959ee68c023ba643e4495882942a8ae3d2b1b0e
5,353
package org.apache.lucene.test; import org.apache.lucene.document.Document; import org.apache.lucene.document.DoublePoint; import org.apache.lucene.document.Field; import org.apache.lucene.document.IntPoint; import org.apache.lucene.document.LatLonDocValuesField; import org.apache.lucene.document.LatLonPoint; import org.apache.lucene.document.LongPoint; import org.apache.lucene.document.StoredField; import org.apache.lucene.document.StringField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.ByteBuffersDirectory; import org.apache.lucene.store.MMapDirectory; import java.io.IOException; import java.math.BigDecimal; import java.nio.file.Path; import java.util.Random; /** * @author chengzhengzheng * @date 2021/1/8 */ public class TestSearch { public static void main(String[] args) throws Exception { // MMapDirectory directory = new MMapDirectory(Path.of("/Users/chengzheng/lucenedir/")); // ByteBuffersDirectory directory = new ByteBuffersDirectory(); IndexWriterConfig conf = new IndexWriterConfig(); IndexWriter indexWriter = new IndexWriter(directory, conf); for (int i = 1; i < 10000000; i++) { try { indexWriter.addDocument(buildRandomDocument()); } catch (IOException e) { e.printStackTrace(); } } indexWriter.commit(); for (int i = 0;i <100;i++){ new Thread(new Runnable() { @Override public void run() { while (true){ try { int age = new Random().nextInt(100); indexWriter.updateDocument(new Term("age", String.valueOf(age)),buildRandomDocument()); } catch (IOException e) { e.printStackTrace(); } } } }).start(); } // DirectoryReader reader = DirectoryReader.open(directory); // IndexSearcher indexSearcher = new IndexSearcher(reader); // // TopDocs res = indexSearcher.search(new MatchAllDocsQuery(), 1000); // ScoreDoc[] scoreDocs = res.scoreDocs; // for (ScoreDoc scoreDoc : scoreDocs) { // Document info = reader.document(scoreDoc.doc); // for (IndexableField rw : info) { // System.out.print(rw.name() + ":" + rw.stringValue() + "\t"); // } // System.out.println(); // } System.in.read(); } public static Document buildRandomDocument() { Document document = new Document(); Random random = new Random(); int length = 6; int i = random.nextInt(5); StringBuilder sb = new StringBuilder(); for (int j = 0; j < length + i; j++) { sb.append(random.nextInt(10)); } document.add(new StringField("id", sb.toString(), Field.Store.YES)); int age = random.nextInt(100); document.add(new IntPoint("age", age)); document.add(new StoredField("age", age)); double faceScore = Math.random(); document.add(new DoublePoint("faceScore", faceScore)); document.add(new StoredField("faceScore", faceScore)); long l = System.currentTimeMillis() - random.nextInt(1000 * 100000); document.add(new LongPoint("last_app_online_time", l)); document.add(new StoredField("last_app_online_time", l)); long l1 = System.currentTimeMillis() - random.nextInt(1000 * 100000); document.add(new LongPoint("last_marry_online_time", l1)); document.add(new StoredField("last_marry_online_time", l1)); String level = String.valueOf(random.nextInt(4)); document.add(new StringField("level", level, Field.Store.YES)); String s = String.valueOf(random.nextInt(100) > 50 ? Boolean.TRUE : Boolean.FALSE); document.add(new StringField("real_person", s, Field.Store.YES)); String[] strings = randomLonLat(73.807171, 134.495648, 20.287309, 51.251166); document.add(new LatLonPoint("location", Double.parseDouble(strings[0]), Double.parseDouble(strings[1]))); return document; } /** * @param MinLon :最小经度 MaxLon: 最大经度 * MinLat:最小纬度 * MaxLat:最大纬度 * @return @throws * @Description: 在矩形内随机生成经纬度 */ public static String[] randomLonLat(double MinLon, double MaxLon, double MinLat, double MaxLat) { BigDecimal db = new BigDecimal(Math.random() * (MaxLon - MinLon) + MinLon); String lon = db.setScale(6, BigDecimal.ROUND_HALF_UP).toString();// 小数后6位 db = new BigDecimal(Math.random() * (MaxLat - MinLat) + MinLat); String lat = db.setScale(6, BigDecimal.ROUND_HALF_UP).toString(); return new String[]{lat, lon}; } }
37.433566
115
0.615543
e94fc3d2dded81b3c8767444b77e09adacab758e
4,214
/* * Copyright 2017-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.cloud.services.modeling.validation.process; import org.activiti.bpmn.model.BpmnModel; import org.activiti.bpmn.model.EndEvent; import org.activiti.bpmn.model.SequenceFlow; import org.activiti.bpmn.model.StartEvent; import org.activiti.cloud.modeling.api.ModelValidationError; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; public class StartEventIncomingOutgoingFlowValidatorTest { private StartEventIncomingOutgoingFlowValidator startEventIncomingOutgoingFlowValidator; private final String startEventId = "start"; private final String startEventName = "startEventName"; @BeforeEach void setUp() { startEventIncomingOutgoingFlowValidator = new StartEventIncomingOutgoingFlowValidator(); } @Test public void should_returnError_when_startEventOutgoingFlowIsEmpty() { BpmnModel bpmnModel = CreateBpmnModelTestHelper.createOneTaskTestProcess(); StartEvent startEvent = (StartEvent) bpmnModel.getMainProcess().getFlowElement(startEventId); startEvent.setName(startEventName); startEvent.setOutgoingFlows(new ArrayList<>()); assertThat(startEventIncomingOutgoingFlowValidator.validate(startEvent)) .extracting(ModelValidationError::getProblem, ModelValidationError::getDescription, ModelValidationError::getValidatorSetName, ModelValidationError::getReferenceId) .contains(tuple(StartEventIncomingOutgoingFlowValidator.NO_OUTGOING_FLOW_PROBLEM, format(StartEventIncomingOutgoingFlowValidator.NO_OUTGOING_FLOW_PROBLEM_DESCRIPTION, startEventName, startEventId), StartEventIncomingOutgoingFlowValidator.START_EVENT_FLOWS_VALIDATOR_NAME, startEventId)); } @Test public void should_returnError_when_startEventIncomingFlowIsNotEmpty() { BpmnModel bpmnModel = CreateBpmnModelTestHelper.createOneTaskTestProcess(); StartEvent startEvent = (StartEvent) bpmnModel.getMainProcess().getFlowElement(startEventId); startEvent.setName(startEventName); SequenceFlow incomingFlow = new SequenceFlow(); startEvent.getIncomingFlows().add(incomingFlow); assertThat(startEventIncomingOutgoingFlowValidator.validate(startEvent)) .extracting(ModelValidationError::getProblem, ModelValidationError::getDescription, ModelValidationError::getValidatorSetName, ModelValidationError::getReferenceId) .contains(tuple(StartEventIncomingOutgoingFlowValidator.INCOMING_FLOW_ON_START_EVENT_PROBLEM, format(StartEventIncomingOutgoingFlowValidator.INCOMING_FLOW_ON_START_EVENT_PROBLEM_DESCRIPTION, startEventName, startEventId), StartEventIncomingOutgoingFlowValidator.START_EVENT_FLOWS_VALIDATOR_NAME, startEventId)); } @Test public void canValidate_should_returnTrue_when_itsAStartEvent() { assertThat(startEventIncomingOutgoingFlowValidator.canValidate(new StartEvent())).isTrue(); } @Test public void canValidate_should_returnTrue_when_itsNotAStartEvent() { assertThat(startEventIncomingOutgoingFlowValidator.canValidate(new EndEvent())).isFalse(); } }
46.822222
155
0.738728
d5edbfbf6fea6f018388ae072392742a8845e802
4,721
package medical.home; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.view.View; import android.widget.CheckBox; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import com.android.myapplication.R; import medical.goals.AgentGoal; import medical.goals.GoalActivity; import medical.monitor.AgentPulso; import medical.monitor.MonitorActivity; import medical.profile.PatientProfileActivity; public class DialogSelectParameter extends Dialog implements View.OnClickListener { private AgentHome agent; private CheckBox pulsoBox; private CheckBox ecgBox; private CheckBox info_check; private TextView textInmediate; private TextView infoText; private TextView textScheduled; public DialogSelectParameter(@NonNull Context context, AgentHome agentHome) { super(context); setContentView(R.layout.dialog_parameter); findViewById(R.id.actionButton).setOnClickListener(this); agent = agentHome; ecgBox = findViewById(R.id.ecgCheck); ecgBox.setOnClickListener(this); pulsoBox = findViewById(R.id.pulsoCheck); pulsoBox.setOnClickListener(this); textInmediate = findViewById(R.id.imediateText); textInmediate.setOnClickListener(this); textScheduled = findViewById(R.id.scheduleText); textScheduled.setOnClickListener(this); info_check = findViewById(R.id.info_check); info_check.setOnClickListener(this); infoText = findViewById(R.id.info_text); infoText.setOnClickListener(this); } private void change(int state) { if (state == 0) { pulsoBox.setChecked(true); textInmediate.setTextColor(ContextCompat.getColor(getContext(), R.color.blue_strong)); ecgBox.setChecked(false); textScheduled.setTextColor(ContextCompat.getColor(getContext(), R.color.gray_strong)); info_check.setChecked(false); infoText.setTextColor(ContextCompat.getColor(getContext(), R.color.gray_strong)); } else if (state == 1) { pulsoBox.setChecked(false); textInmediate.setTextColor(ContextCompat.getColor(getContext(), R.color.gray_strong)); ecgBox.setChecked(true); textScheduled.setTextColor(ContextCompat.getColor(getContext(), R.color.blue_strong)); info_check.setChecked(false); infoText.setTextColor(ContextCompat.getColor(getContext(), R.color.gray_strong)); } else if (state == 2) { pulsoBox.setChecked(false); textInmediate.setTextColor(ContextCompat.getColor(getContext(), R.color.gray_strong)); ecgBox.setChecked(false); textScheduled.setTextColor(ContextCompat.getColor(getContext(), R.color.gray_strong)); info_check.setChecked(true); infoText.setTextColor(ContextCompat.getColor(getContext(), R.color.blue_strong)); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.pulsoCheck: case R.id.imediateText: change(0); break; case R.id.ecgCheck: case R.id.scheduleText: change(1); break; case R.id.info_check: case R.id.info_text: change(2); break; case R.id.closeButton: dismiss(); break; case R.id.actionButton: if (pulsoBox.isChecked()) { AgentPulso.INSTANCE.type = pulsoBox.isChecked() ? 0 : 1; Intent in = new Intent(v.getContext(), MonitorActivity.class); v.getContext().startActivity(in); this.dismiss(); } else if (ecgBox.isChecked()) { Intent in = new Intent(v.getContext(), GoalActivity.class); AgentGoal.getInstance().idUser = agent.select.getUID(); v.getContext().startActivity(in); this.dismiss(); } else if (info_check.isChecked()) { Intent in = new Intent(v.getContext(), PatientProfileActivity.class); in.putExtra("patient", agent.serializePatient()); v.getContext().startActivity(in); this.dismiss(); } else Toast.makeText(v.getContext(), "Por favor seleccione una categoría", Toast.LENGTH_SHORT).show(); break; } } }
32.784722
116
0.622326
38b15bdf8f43181032a95b753a845646f7842ffd
3,242
package com.dea42.watchlist.search; import com.dea42.watchlist.entity.Shows; import com.dea42.watchlist.utils.MessageHelper; import java.io.Serializable; import java.util.Date; import javax.validation.constraints.NotBlank; import lombok.Data; import org.hibernate.validator.constraints.Length; import org.springframework.data.domain.Sort; import org.springframework.format.annotation.DateTimeFormat; /** * Title: ShowsSearchForm <br> * Description: Class for holding data from the Shows table for searching. <br> * Copyright: Copyright (c) 2001-2021<br> * Company: RMRR<br> * * @author Gened by com.dea42.build.GenSpring version 0.7.2<br> * @version 0.7.2<br> */ @Data public class ShowsSearchForm implements Serializable { private static final long serialVersionUID = 1L; private String cancelled = ""; private String epguidesshowname = ""; /* info=ColInfo(fNum=2, colName=id, msgKey=Shows.id, vName=id, type=Long, jtype=null, stype=-5, gsName=Id, length=0, pk=true, defaultVal=null, constraint=null, required=true, list=true, jsonIgnore=false, unique=false, hidden=false, password=false, email=false, created=false, lastMod=false, adminOnly=false, foreignTable=null, foreignCol=null, colScale=0, colPrecision=0, comment= * Table name: Shows<br> * Column name: id<br> * Catalog name: Watchlist<br> * Primary key sequence: 1<br> * Primary key name: PRIMARY<br> * <br>) */ private Long idMin; private Long idMax; private String incanceledas = ""; private String lastshow = ""; private String network = ""; private String premiere = ""; @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss") private Date premieredateMin; @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss") private Date premieredateMax; private String status = ""; private String tivoname = ""; private String sortField = "id"; private int page = 1; private int pageSize = 10; private boolean sortAsc = true; private int totalPages = 0; private long totalItems = 0; private SearchType doOr = SearchType.ADD; private boolean advanced = true; /** * Clones Shows obj into form * * @param obj */ public static ShowsSearchForm getInstance(Shows obj) { ShowsSearchForm form = new ShowsSearchForm(); form.setCancelled(obj.getCancelled()); form.setEpguidesshowname(obj.getEpguidesshowname()); form.setIdMin(obj.getId()); form.setIdMax(obj.getId()); form.setIncanceledas(obj.getIncanceledas()); form.setLastshow(obj.getLastshow()); form.setNetwork(obj.getNetwork()); form.setPremiere(obj.getPremiere()); form.setPremieredateMin(obj.getPremieredate()); form.setPremieredateMax(obj.getPremieredate()); form.setStatus(obj.getStatus()); form.setTivoname(obj.getTivoname()); return form; } /** * Generate a Sort from fields * @return */ public Sort getSort() { if (sortAsc) return Sort.by(sortField).ascending(); return Sort.by(sortField).descending(); } public String getSortDir() { if (sortAsc) return "asc"; else return "desc"; } public String getReverseSortDir() { if (sortAsc) return "desc"; else return "asc"; } boolean getSortAscFlip() { return !sortAsc; } }
30.584906
405
0.70512
6eac99c154492beac77966bc73f808e4e9e28ffa
1,600
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. 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 majordodo.security.sasl; import java.util.Base64; import java.util.HashMap; import java.util.Map; import javax.security.sasl.Sasl; /** * Sasl Utility * * @author enrico.olivelli */ public class SaslUtils { public static final String AUTH_DIGEST_MD5 = "DIGEST-MD5"; public static final String DEFAULT_REALM = "default"; static Map<String, String> getSaslProps() { Map<String, String> props = new HashMap<String, String>(); props.put(Sasl.POLICY_NOPLAINTEXT, "true"); return props; } /** * Encode a password as a base64-encoded char[] array. * * @param password as a byte array. * @return password as a char array. */ static char[] encodePassword(byte[] password) { return Base64.getEncoder().encodeToString(password).toCharArray(); } }
28.571429
74
0.716875
06bccc2b1e646d5a02546169a61202d8f94e1e08
842
package com.kenshine.pattern2.decorator; /** * @version v1.0 * @ClassName: Client * @Description: 测试类 * @Author: kenshine * * * 装饰者模式 */ public class Client { public static void main(String[] args) { //点一份炒饭 FastFood food = new FriedRice(); System.out.println(food.getDesc() + " " + food.cost() + "元"); System.out.println("==============="); //在上面的炒饭中加一个鸡蛋 food = new Egg(food); System.out.println(food.getDesc() + " " + food.cost() + "元"); System.out.println("================"); //再加一个鸡蛋 food = new Egg(food); System.out.println(food.getDesc() + " " + food.cost() + "元"); System.out.println("================"); food = new Bacon(food); System.out.println(food.getDesc() + " " + food.cost() + "元"); } }
24.057143
70
0.502375
70a35b68805bc996612b7910222fabf4c1c6d529
2,602
/** * */ package com.nowgroup.kenan.batch; import java.io.Serializable; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @author dtorresf * */ @Entity @Table(name = "company") public class Company implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String name; private String alias; /** * @return the id */ @Id @Column(name = "company_id") public Integer getId() { return id; } /** * @param id * the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the name */ @Column(name = "company_name") public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the alias */ @Column(name = "company_alias") public String getAlias() { return alias; } /** * @param alias * the alias to set */ public void setAlias(String alias) { this.alias = alias; } public String md5HashCode() { String s = this.name + this.alias; MessageDigest m; try { m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return String.valueOf(this.hashCode()); } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Company other = (Company) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Company [id=" + id + ", name=" + name + ", alias=" + alias + "]"; } }
18.323944
75
0.617986
a2b6f833a3e47a57299f907523b5a4073e0d3af1
252
package com.codeboy.hadoop.base; public class HadoopConstants { public static final String CONFKEY_FS_NAME = "fs.default.name"; public static final String CONFKEY_JOB_UGI = "hadoop.job.ugi"; public static final String HDFS_PREFIX = "hdfs://"; }
25.2
64
0.761905
aa891a2fe6537927e3128939eb6a7caa47c076fe
4,520
package com.yunpian.sdk.service; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import com.yunpian.sdk.model.FlowPackage; import com.yunpian.sdk.model.FlowStatus; import com.yunpian.sdk.model.ResultDO; import com.yunpian.sdk.model.SmsBatchSend; import com.yunpian.sdk.model.FlowSend; import com.yunpian.sdk.model.SmsSingleSend; import com.yunpian.sdk.model.VoiceSend; import com.yunpian.sdk.model.SmsReply; import com.yunpian.sdk.model.SmsStatus; import com.yunpian.sdk.model.Template; import com.yunpian.sdk.model.User; import com.yunpian.sdk.model.VoiceStatus; /** * Created by bingone on 16/1/19. */ @Deprecated public class YunpianRestTest { public static YunpianRestClient client; @BeforeClass public static void init() { client = new YunpianRestClient("327d7f6aca319be83cbcb92eb9b6eff6"); } @Test public void testSendSms() throws UnsupportedEncodingException { YunpianRestClient client = new YunpianRestClient("your apikey"); SmsOperator smsOperator = client.getSmsOperator(); // 单条发送 ResultDO<SmsSingleSend> r1 = smsOperator.singleSend("18210374138", "【云片网】您的验证码是1234"); System.out.println(r1); // 批量发送 ResultDO<SmsBatchSend> r2 = smsOperator.batchSend("13012312316,13112312312,123321,333,111", "【云片网】您的验证码是1234"); System.out.println(r2); List<String> mobile = Arrays.asList("13012312321,13012312322,13012312323,130123123".split(",")); List<String> text = Arrays.asList("【云片网】您的验证码是1234,【云片网】您的验证码是1234,【云片网】您的验证码是1234,【云片网】您的验证码是1234".split(",")); // 个性化发送 ResultDO<SmsBatchSend> r3 = smsOperator.multiSend(mobile, text); System.out.println(r3); // (不推荐使用) // String tpl_value = URLEncoder.encode("#code#", Config.ENCODING) + "=" // + URLEncoder // .encode("1234", Config.ENCODING) + "&" + // URLEncoder.encode("#company#", Config.ENCODING) // + "=" + URLEncoder.encode("云片网", Config.ENCODING); // // tpl batch send // ResultDO<SendBatchSmsInfo> r4 = // smsOperator.tplBatchSend("13200000000,13212312312,123321,333,111", // "1", tpl_value); // System.out.println(r4); // // tpl single send // ResultDO<SendSingleSmsInfo> r5 = // smsOperator.tplSingleSend("15404450000", "1", tpl_value); // System.out.println(r5); // System.out.println(smsOperator.getRecord(new // Date(System.currentTimeMillis()),new // Date(System.currentTimeMillis()),"","","")); // System.out.println(smsOperator // .getRecord(new Date(System.currentTimeMillis()), new // Date(System.currentTimeMillis()),"","","")); } @Test public void testUser() { UserOperator userOperator = client.getUserOperator(); ResultDO<User> resultDO = userOperator.get(); System.out.println(resultDO); } @Test public void testTpl() { TplOperator tplOperator = client.getTplOperator(); ResultDO<List<Template>> resultDO = tplOperator.getDefault(); System.out.println(resultDO); resultDO = tplOperator.get(); System.out.println(resultDO); resultDO = tplOperator.getDefault("2"); System.out.println(resultDO); ResultDO<Template> result = tplOperator.add("【bbb】大倪#asdf#"); System.out.println(result); resultDO = tplOperator.get(String.valueOf(result.getData().getTpl_id())); System.out.println(resultDO); result = tplOperator.update(String.valueOf(result.getData().getTpl_id()), "【aaa】大倪#asdf#"); System.out.println(result); result = tplOperator.del(String.valueOf(result.getData().getTpl_id())); System.out.println(result); } @Test public void testFlow() { FlowOperator flowOperator = client.getFlowOperator(); ResultDO<List<FlowPackage>> r1 = flowOperator.getPackage(); System.out.println(r1); r1 = flowOperator.getPackage("10086"); System.out.println(r1); ResultDO<FlowSend> r2 = flowOperator.recharge("18700000000", "1008601"); System.out.println(r2); ResultDO<List<FlowStatus>> r3 = flowOperator.pullStatus(); System.out.println(r3); } @Test public void testVoice() { VoiceOperator voiceOperator = client.getVoiceOperator(); ResultDO<VoiceSend> resultDO = voiceOperator.send("18700000000", "4325"); System.out.println(resultDO); ResultDO<List<VoiceStatus>> result = voiceOperator.pullStatus(); System.out.println(result); } @Test public void testReport() { SmsOperator smsOperator = client.getSmsOperator(); ResultDO<List<SmsReply>> r1 = smsOperator.pullReply(); System.out.println(r1); ResultDO<List<SmsStatus>> r2 = smsOperator.pullStatus(); System.out.println(r2); } }
32.517986
114
0.73031
f88297a06efa208d52c31d0aeaa95a32aec88462
8,384
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package com.facebook.drawee; public final class R { private R() {} public static final class attr { private attr() {} public static final int actualImageResource = 0x7f020022; public static final int actualImageScaleType = 0x7f020023; public static final int actualImageUri = 0x7f020024; public static final int backgroundImage = 0x7f020035; public static final int fadeDuration = 0x7f02007e; public static final int failureImage = 0x7f02007f; public static final int failureImageScaleType = 0x7f020080; public static final int overlayImage = 0x7f0200b9; public static final int placeholderImage = 0x7f0200c1; public static final int placeholderImageScaleType = 0x7f0200c2; public static final int pressedStateOverlayImage = 0x7f0200c7; public static final int progressBarAutoRotateInterval = 0x7f0200c8; public static final int progressBarImage = 0x7f0200c9; public static final int progressBarImageScaleType = 0x7f0200ca; public static final int retryImage = 0x7f0200d3; public static final int retryImageScaleType = 0x7f0200d4; public static final int roundAsCircle = 0x7f0200d5; public static final int roundBottomEnd = 0x7f0200d6; public static final int roundBottomLeft = 0x7f0200d7; public static final int roundBottomRight = 0x7f0200d8; public static final int roundBottomStart = 0x7f0200d9; public static final int roundTopEnd = 0x7f0200da; public static final int roundTopLeft = 0x7f0200db; public static final int roundTopRight = 0x7f0200dc; public static final int roundTopStart = 0x7f0200dd; public static final int roundWithOverlayColor = 0x7f0200de; public static final int roundedCornerRadius = 0x7f0200df; public static final int roundingBorderColor = 0x7f0200e0; public static final int roundingBorderPadding = 0x7f0200e1; public static final int roundingBorderWidth = 0x7f0200e2; public static final int viewAspectRatio = 0x7f020128; } public static final class id { private id() {} public static final int center = 0x7f070049; public static final int centerCrop = 0x7f07004a; public static final int centerInside = 0x7f07004b; public static final int fitBottomStart = 0x7f07005d; public static final int fitCenter = 0x7f07005e; public static final int fitEnd = 0x7f07005f; public static final int fitStart = 0x7f070060; public static final int fitXY = 0x7f070061; public static final int focusCrop = 0x7f070063; public static final int none = 0x7f070077; } public static final class styleable { private styleable() {} public static final int[] GenericDraweeHierarchy = { 0x7f020023, 0x7f020035, 0x7f02007e, 0x7f02007f, 0x7f020080, 0x7f0200b9, 0x7f0200c1, 0x7f0200c2, 0x7f0200c7, 0x7f0200c8, 0x7f0200c9, 0x7f0200ca, 0x7f0200d3, 0x7f0200d4, 0x7f0200d5, 0x7f0200d6, 0x7f0200d7, 0x7f0200d8, 0x7f0200d9, 0x7f0200da, 0x7f0200db, 0x7f0200dc, 0x7f0200dd, 0x7f0200de, 0x7f0200df, 0x7f0200e0, 0x7f0200e1, 0x7f0200e2, 0x7f020128 }; public static final int GenericDraweeHierarchy_actualImageScaleType = 0; public static final int GenericDraweeHierarchy_backgroundImage = 1; public static final int GenericDraweeHierarchy_fadeDuration = 2; public static final int GenericDraweeHierarchy_failureImage = 3; public static final int GenericDraweeHierarchy_failureImageScaleType = 4; public static final int GenericDraweeHierarchy_overlayImage = 5; public static final int GenericDraweeHierarchy_placeholderImage = 6; public static final int GenericDraweeHierarchy_placeholderImageScaleType = 7; public static final int GenericDraweeHierarchy_pressedStateOverlayImage = 8; public static final int GenericDraweeHierarchy_progressBarAutoRotateInterval = 9; public static final int GenericDraweeHierarchy_progressBarImage = 10; public static final int GenericDraweeHierarchy_progressBarImageScaleType = 11; public static final int GenericDraweeHierarchy_retryImage = 12; public static final int GenericDraweeHierarchy_retryImageScaleType = 13; public static final int GenericDraweeHierarchy_roundAsCircle = 14; public static final int GenericDraweeHierarchy_roundBottomEnd = 15; public static final int GenericDraweeHierarchy_roundBottomLeft = 16; public static final int GenericDraweeHierarchy_roundBottomRight = 17; public static final int GenericDraweeHierarchy_roundBottomStart = 18; public static final int GenericDraweeHierarchy_roundTopEnd = 19; public static final int GenericDraweeHierarchy_roundTopLeft = 20; public static final int GenericDraweeHierarchy_roundTopRight = 21; public static final int GenericDraweeHierarchy_roundTopStart = 22; public static final int GenericDraweeHierarchy_roundWithOverlayColor = 23; public static final int GenericDraweeHierarchy_roundedCornerRadius = 24; public static final int GenericDraweeHierarchy_roundingBorderColor = 25; public static final int GenericDraweeHierarchy_roundingBorderPadding = 26; public static final int GenericDraweeHierarchy_roundingBorderWidth = 27; public static final int GenericDraweeHierarchy_viewAspectRatio = 28; public static final int[] SimpleDraweeView = { 0x7f020022, 0x7f020023, 0x7f020024, 0x7f020035, 0x7f02007e, 0x7f02007f, 0x7f020080, 0x7f0200b9, 0x7f0200c1, 0x7f0200c2, 0x7f0200c7, 0x7f0200c8, 0x7f0200c9, 0x7f0200ca, 0x7f0200d3, 0x7f0200d4, 0x7f0200d5, 0x7f0200d6, 0x7f0200d7, 0x7f0200d8, 0x7f0200d9, 0x7f0200da, 0x7f0200db, 0x7f0200dc, 0x7f0200dd, 0x7f0200de, 0x7f0200df, 0x7f0200e0, 0x7f0200e1, 0x7f0200e2, 0x7f020128 }; public static final int SimpleDraweeView_actualImageResource = 0; public static final int SimpleDraweeView_actualImageScaleType = 1; public static final int SimpleDraweeView_actualImageUri = 2; public static final int SimpleDraweeView_backgroundImage = 3; public static final int SimpleDraweeView_fadeDuration = 4; public static final int SimpleDraweeView_failureImage = 5; public static final int SimpleDraweeView_failureImageScaleType = 6; public static final int SimpleDraweeView_overlayImage = 7; public static final int SimpleDraweeView_placeholderImage = 8; public static final int SimpleDraweeView_placeholderImageScaleType = 9; public static final int SimpleDraweeView_pressedStateOverlayImage = 10; public static final int SimpleDraweeView_progressBarAutoRotateInterval = 11; public static final int SimpleDraweeView_progressBarImage = 12; public static final int SimpleDraweeView_progressBarImageScaleType = 13; public static final int SimpleDraweeView_retryImage = 14; public static final int SimpleDraweeView_retryImageScaleType = 15; public static final int SimpleDraweeView_roundAsCircle = 16; public static final int SimpleDraweeView_roundBottomEnd = 17; public static final int SimpleDraweeView_roundBottomLeft = 18; public static final int SimpleDraweeView_roundBottomRight = 19; public static final int SimpleDraweeView_roundBottomStart = 20; public static final int SimpleDraweeView_roundTopEnd = 21; public static final int SimpleDraweeView_roundTopLeft = 22; public static final int SimpleDraweeView_roundTopRight = 23; public static final int SimpleDraweeView_roundTopStart = 24; public static final int SimpleDraweeView_roundWithOverlayColor = 25; public static final int SimpleDraweeView_roundedCornerRadius = 26; public static final int SimpleDraweeView_roundingBorderColor = 27; public static final int SimpleDraweeView_roundingBorderPadding = 28; public static final int SimpleDraweeView_roundingBorderWidth = 29; public static final int SimpleDraweeView_viewAspectRatio = 30; } }
65.5
428
0.754771
646b468e0c1a5fb7aac7f1282b8057ae446aa76b
5,722
/* * Copyright 2021 DeNA Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.packetproxyhub.controller.route; import com.google.inject.Inject; import com.packetproxyhub.entity.Id; import com.packetproxyhub.entity.Ids; import com.packetproxyhub.entity.Org; import com.packetproxyhub.entity.Orgs; import com.packetproxyhub.interactor.IOrgService; import org.apache.commons.io.IOUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; // Orgs Endpoints // GET /orgs (list orgs) // POST /orgs/ (create a org) // GET /orgs/111 (get the org) // GET /orgs/all (get all orgs) // PUT /orgs/111 (edit the org) // DELETE /orgs/111 (delete the org) public class OrgRoute extends Route { @Inject private IOrgService orgService; @Override public boolean getIfMatch(String path, HttpServletRequest request, HttpServletResponse response) { // list orgs if (match("/orgs", path, (a) -> { try { Id myAccountId = getAccountId(request); Ids orgIds = orgService.listReadableOrgIds(myAccountId); response.setStatus(HttpServletResponse.SC_OK); replyResponseAsJson(response, orgIds.toJson()); } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } })) { return true; } // get all orgs if (match ("/orgs/all", path, (a) -> { try { Id myAccountId = getAccountId(request); Orgs orgs = orgService.listReadableOrgs(myAccountId); response.setStatus(HttpServletResponse.SC_OK); replyResponseAsJson(response, orgs.toJson()); } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } })) { return true; } // get a org if (match ("/orgs/{orgId}", path, (a) -> { try { Id myAccountId = getAccountId(request); Id orgId = Id.createFromString(a.get("orgId")); Org org = orgService.getOrg(myAccountId, orgId); if (org == null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } response.setStatus(HttpServletResponse.SC_OK); replyResponseAsJson(response, org.toJson()); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); e.printStackTrace(); } })) { return true; } return false; } @Override public boolean postIfMatch(String path, HttpServletRequest request, HttpServletResponse response) { // create a new org if (match ("/orgs/", path, (a) -> { try { Id accountId = getAccountId(request); String body = IOUtils.toString(request.getReader()); Org org = Org.createFromJson(body); Id orgId = orgService.createOrg(accountId, org); response.setStatus(HttpServletResponse.SC_OK); replyResponseAsJson(response, orgId.toJson()); } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_CONFLICT); } })) { return true; } return false; } @Override public boolean putIfMatch(String path, HttpServletRequest request, HttpServletResponse response) { // edit the org if (match ("/orgs/{orgId}", path, (a) -> { try { Id myAccountId = getAccountId(request); Id orgId = Id.createFromString(a.get("orgId")); String body = IOUtils.toString(request.getReader()); Org putOrg = Org.createFromJson(body); orgService.updateOrg(myAccountId, orgId, putOrg); response.setStatus(HttpServletResponse.SC_OK); replyResponseAsJson(response, "{\"status\":\"ok\"}"); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); e.printStackTrace(); } })) { return true; } return false; } @Override public boolean deleteIfMatch(String path, HttpServletRequest request, HttpServletResponse response) { // delete the org if (match ("/orgs/{orgId}", path, (a) -> { try { Id myAccountId = getAccountId(request); Id orgId = Id.createFromString(a.get("orgId")); orgService.removeOrg(myAccountId, orgId); response.setStatus(HttpServletResponse.SC_OK); replyResponseAsJson(response, "{\"status\":\"ok\"}"); } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } })) { return true; } return false; } }
34.46988
105
0.590877
b3bca9fd6c025f4b5dfe84438a9b8a2dcdefc38b
4,589
package com.iheartradio.m3u8.data; import java.util.List; import java.util.Objects; public class MasterPlaylist { private final List<PlaylistData> mPlaylists; private final List<IFrameStreamInfo> mIFramePlaylists; private final List<MediaData> mMediaData; private final List<String> mUnknownTags; private final StartData mStartData; private MasterPlaylist(List<PlaylistData> playlists, List<IFrameStreamInfo> iFramePlaylists, List<MediaData> mediaData, List<String> unknownTags, StartData startData) { mPlaylists = DataUtil.emptyOrUnmodifiable(playlists); mIFramePlaylists = DataUtil.emptyOrUnmodifiable(iFramePlaylists); mMediaData = DataUtil.emptyOrUnmodifiable(mediaData); mUnknownTags = DataUtil.emptyOrUnmodifiable(unknownTags); mStartData = startData; } public List<PlaylistData> getPlaylists() { return mPlaylists; } public List<IFrameStreamInfo> getIFramePlaylists() { return mIFramePlaylists; } public List<MediaData> getMediaData() { return mMediaData; } public boolean hasUnknownTags() { return mUnknownTags.size() > 0; } public List<String> getUnknownTags() { return mUnknownTags; } public boolean hasStartData() { return mStartData != null; } public StartData getStartData() { return mStartData; } public Builder buildUpon() { return new Builder(mPlaylists, mIFramePlaylists, mMediaData, mUnknownTags); } @Override public int hashCode() { return Objects.hash(mMediaData, mPlaylists, mIFramePlaylists, mUnknownTags, mStartData); } @Override public boolean equals(Object o) { if (!(o instanceof MasterPlaylist)) { return false; } MasterPlaylist other = (MasterPlaylist) o; return Objects.equals(mMediaData, other.mMediaData) && Objects.equals(mPlaylists, other.mPlaylists) && Objects.equals(mIFramePlaylists, other.mIFramePlaylists) && Objects.equals(mUnknownTags, other.mUnknownTags) && Objects.equals(mStartData, other.mStartData); } @Override public String toString() { return new StringBuilder() .append("(MasterPlaylist") .append(" mPlaylists=").append(mPlaylists.toString()) .append(" mIFramePlaylists=").append(mIFramePlaylists.toString()) .append(" mMediaData=").append(mMediaData.toString()) .append(" mUnknownTags=").append(mUnknownTags.toString()) .append(" mStartData=").append(mStartData.toString()) .append(")") .toString(); } public static class Builder { private List<PlaylistData> mPlaylists; private List<IFrameStreamInfo> mIFramePlaylists; private List<MediaData> mMediaData; private List<String> mUnknownTags; private StartData mStartData; public Builder() { } private Builder(List<PlaylistData> playlists, List<IFrameStreamInfo> iFramePlaylists, List<MediaData> mediaData, List<String> unknownTags) { mPlaylists = playlists; mIFramePlaylists = iFramePlaylists; mMediaData = mediaData; mUnknownTags = unknownTags; } private Builder(List<PlaylistData> playlists, List<MediaData> mediaData) { mPlaylists = playlists; mMediaData = mediaData; } public Builder withPlaylists(List<PlaylistData> playlists) { mPlaylists = playlists; return this; } public Builder withIFramePlaylists(List<IFrameStreamInfo> iFramePlaylists) { mIFramePlaylists = iFramePlaylists; return this; } public Builder withMediaData(List<MediaData> mediaData) { mMediaData = mediaData; return this; } public Builder withUnknownTags(List<String> unknownTags) { mUnknownTags = unknownTags; return this; } public Builder withStartData(StartData startData) { mStartData = startData; return this; } public MasterPlaylist build() { return new MasterPlaylist(mPlaylists, mIFramePlaylists, mMediaData, mUnknownTags, mStartData); } } }
33.253623
173
0.615603
d541bceb3031c7d12caeb93def163e37eb3ef93d
707
package net.andreinc.mockneat.unit.user; import net.andreinc.mockneat.MockNeat; import net.andreinc.mockneat.abstraction.MockUnitBase; import net.andreinc.mockneat.abstraction.MockUnitString; import net.andreinc.mockneat.types.enums.DictType; import java.util.function.Supplier; public class NonBinaryGenders extends MockUnitBase implements MockUnitString { public static NonBinaryGenders nonBinaryGenders() { return MockNeat.threadLocal().nonBinaryGenders(); } public NonBinaryGenders(MockNeat mockNeat) { super(mockNeat); } @Override public Supplier<String> supplier() { return mockNeat.dicts().type(DictType.NON_BINARY_GENDERS).supplier(); } }
26.185185
78
0.759547
d82027d975e46bffb3f0825daff4009791cfb9cf
9,469
/* Copyright 2018 Telstra Open Source * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openkilda.testing.tools; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.core.Every.everyItem; import org.openkilda.messaging.info.event.IslChangeType; import org.openkilda.messaging.info.event.IslInfoData; import org.openkilda.messaging.info.event.PathNode; import org.openkilda.northbound.dto.v1.links.LinkEnableBfdDto; import org.openkilda.northbound.dto.v1.links.LinkParametersDto; import org.openkilda.northbound.dto.v1.links.LinkPropsDto; import org.openkilda.northbound.dto.v1.links.LinkUnderMaintenanceDto; import org.openkilda.testing.model.topology.TopologyDefinition; import org.openkilda.testing.model.topology.TopologyDefinition.Isl; import org.openkilda.testing.service.lockkeeper.LockKeeperService; import org.openkilda.testing.service.lockkeeper.model.ASwitchFlow; import org.openkilda.testing.service.northbound.NorthboundService; import net.jodah.failsafe.Failsafe; import net.jodah.failsafe.RetryPolicy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @Component public class IslUtils { @Autowired private NorthboundService northbound; @Autowired private LockKeeperService lockKeeper; /** * Waits until all passed ISLs have the specified status. Fails after defined timeout. * Checks happen via Northbound API calls. * * @param isls which ISLs should have the specified status * @param expectedStatus which status to wait for specified ISLs */ public void waitForIslStatus(List<Isl> isls, IslChangeType expectedStatus, RetryPolicy retryPolicy) { List<IslInfoData> actualIsl = Failsafe.with(retryPolicy .retryIf(states -> states != null && ((List<IslInfoData>) states).stream() .map(IslInfoData::getState) .anyMatch(state -> !expectedStatus.equals(state)))) .get(() -> { List<IslInfoData> allLinks = northbound.getAllLinks(); return isls.stream().map(isl -> getIslInfo(allLinks, isl).get()).collect(Collectors.toList()); }); assertThat(actualIsl, everyItem(hasProperty("state", equalTo(expectedStatus)))); } public void waitForIslStatus(List<Isl> isls, IslChangeType expectedStatus) { waitForIslStatus(isls, expectedStatus, retryPolicy()); } /** * Gets actual Northbound representation of the certain ISL. * * @param isl ISL to search in 'getAllLinks' results */ public Optional<IslInfoData> getIslInfo(Isl isl) { return getIslInfo(northbound.getAllLinks(), isl); } /** * Finds certain ISL in list of 'IslInfoData' objects. Passed ISL is our internal ISL representation, while * IslInfoData is returned from NB. * * @param islsInfo list where to search certain ISL * @param isl what ISL to look for */ public Optional<IslInfoData> getIslInfo(List<IslInfoData> islsInfo, Isl isl) { return islsInfo.stream().filter(link -> { PathNode src = link.getSource(); PathNode dst = link.getDestination(); return src.getPortNo() == isl.getSrcPort() && dst.getPortNo() == isl.getDstPort() && src.getSwitchId().equals(isl.getSrcSwitch().getDpId()) && dst.getSwitchId().equals(isl.getDstSwitch().getDpId()); }).findFirst(); } /** * Converts a given Isl object to LinkPropsDto object. * * @param isl Isl object to convert * @param props Isl props to set when creating LinkPropsDto */ public LinkPropsDto toLinkProps(Isl isl, HashMap props) { return new LinkPropsDto(isl.getSrcSwitch().getDpId().toString(), isl.getSrcPort(), isl.getDstSwitch().getDpId().toString(), isl.getDstPort(), props); } /** * Converts a given Isl object to LinkParametersDto object. * * @param isl Isl object to convert */ public LinkParametersDto toLinkParameters(Isl isl) { return new LinkParametersDto(isl.getSrcSwitch().getDpId().toString(), isl.getSrcPort(), isl.getDstSwitch().getDpId().toString(), isl.getDstPort()); } /** * Converts a given IslInfoData object to LinkParametersDto object. * * @param isl IslInfoData object to convert */ public LinkParametersDto toLinkParameters(IslInfoData isl) { return new LinkParametersDto(isl.getSource().getSwitchId().toString(), isl.getSource().getPortNo(), isl.getDestination().getSwitchId().toString(), isl.getDestination().getPortNo()); } /** * Converts a given Isl object to LinkUnderMaintenanceDto object. * * @param isl Isl object to convert */ public LinkUnderMaintenanceDto toLinkUnderMaintenance(Isl isl, boolean underMaintenance, boolean evacuate) { return new LinkUnderMaintenanceDto(isl.getSrcSwitch().getDpId().toString(), isl.getSrcPort(), isl.getDstSwitch().getDpId().toString(), isl.getDstPort(), underMaintenance, evacuate); } /** * Converts a given IslInfoData object to LinkUnderMaintenanceDto object. * * @param isl IslInfoData object to convert */ public LinkUnderMaintenanceDto toLinkUnderMaintenance(IslInfoData isl, boolean underMaintenance, boolean evacuate) { return new LinkUnderMaintenanceDto(isl.getSource().getSwitchId().toString(), isl.getSource().getPortNo(), isl.getDestination().getSwitchId().toString(), isl.getDestination().getPortNo(), underMaintenance, evacuate); } public LinkEnableBfdDto toLinkEnableBfd(Isl isl, boolean bfd) { return new LinkEnableBfdDto(isl.getSrcSwitch().getDpId().toString(), isl.getSrcPort(), isl.getDstSwitch().getDpId().toString(), isl.getDstPort(), bfd); } /** * Simulates a physical ISL replug from one switch-port to another switch-port. Uses a-switch. * * @param srcIsl The initial ISL which is going to be replugged. Should go through a-switch * @param replugSource replug source or destination end of the ISL * @param dstIsl The destination 'isl'. Usually a free link, which is connected to a-switch at one end * @param plugIntoSource Whether to connect to src or dst end of the dstIsl. Usually src end for not-connected ISLs * @param portDown Whether to simulate a 'port down' event when unplugging * @return New ISL which is expected to be discovered after the replug */ public TopologyDefinition.Isl replug(TopologyDefinition.Isl srcIsl, boolean replugSource, TopologyDefinition.Isl dstIsl, boolean plugIntoSource, boolean portDown) { ASwitchFlow srcASwitch = srcIsl.getAswitch(); ASwitchFlow dstASwitch = dstIsl.getAswitch(); //unplug List<Integer> portsToUnplug = Collections.singletonList( replugSource ? srcASwitch.getInPort() : srcASwitch.getOutPort()); if (portDown) { lockKeeper.portsDown(portsToUnplug); } //change flow on aSwitch //delete old flow if (srcASwitch.getInPort() != null && srcASwitch.getOutPort() != null) { lockKeeper.removeFlows(Arrays.asList(srcASwitch, srcASwitch.getReversed())); } //create new flow ASwitchFlow aswFlowForward = new ASwitchFlow(srcASwitch.getInPort(), plugIntoSource ? dstASwitch.getInPort() : dstASwitch.getOutPort()); lockKeeper.addFlows(Arrays.asList(aswFlowForward, aswFlowForward.getReversed())); //plug back if (portDown) { lockKeeper.portsUp(portsToUnplug); } return TopologyDefinition.Isl.factory( replugSource ? (plugIntoSource ? dstIsl.getSrcSwitch() : dstIsl.getDstSwitch()) : srcIsl.getSrcSwitch(), replugSource ? (plugIntoSource ? dstIsl.getSrcPort() : dstIsl.getDstPort()) : srcIsl.getSrcPort(), replugSource ? srcIsl.getDstSwitch() : (plugIntoSource ? dstIsl.getSrcSwitch() : dstIsl.getDstSwitch()), replugSource ? srcIsl.getDstPort() : (plugIntoSource ? dstIsl.getSrcPort() : dstIsl.getDstPort()), 0, aswFlowForward); } private RetryPolicy retryPolicy() { return new RetryPolicy() .withDelay(3, TimeUnit.SECONDS) .withMaxRetries(20); } }
43.837963
120
0.679375
9ae84bfc523fb1e9d31248cd0c2aa024ff7f8a74
2,891
/******************************************************************************* * Software Name : RCS IMS Stack * * Copyright (C) 2010-2016 Orange. * * 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.gsma.rcs.chat; import com.gsma.rcs.core.ParseFailureException; import com.gsma.rcs.core.ims.service.im.chat.resourcelist.ResourceListDocument; import com.gsma.rcs.core.ims.service.im.chat.resourcelist.ResourceListParser; import com.gsma.rcs.utils.logger.Logger; import android.test.AndroidTestCase; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; public class ResourceListParserTest extends AndroidTestCase { private static final String sXmlContentToParse1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">\n" + "\t<list>\n" + "\t\t<entry cp:copyControl=\"to\" uri=\"sip:[email protected]\"/>\n" + "\t\t<entry cp:copyControl=\"cc\" uri=\"sip:[email protected]\"/>\n" + "\t\t<entry cp:copyControl=\"bcc\" uri=\"sip:[email protected]\"/>\n" + "\t</list>\n" + "</resource-lists>"; private Logger logger = Logger.getLogger(this.getClass().getName()); public void testGetResourceListDocument() throws ParserConfigurationException, SAXException, IOException, ParseFailureException { ResourceListParser parser = new ResourceListParser(new InputSource( new ByteArrayInputStream(sXmlContentToParse1.getBytes()))); parser.parse(); ResourceListDocument rlistDoc = parser.getResourceList(); if (logger.isActivated()) { if (rlistDoc.getEntries() != null) { logger.info("resources number = " + rlistDoc.getEntries().size()); } else { logger.info("resources list is null"); } } assertTrue(rlistDoc.getEntries().contains("sip:[email protected]")); assertTrue(rlistDoc.getEntries().contains("sip:[email protected]")); assertTrue(rlistDoc.getEntries().contains("sip:[email protected]")); } }
42.514706
130
0.643376
2d549525e71c8e8f59656a68992f99113234fb8b
1,185
package org.qw3rtrun.aub.engine.opengl; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL41; import static org.lwjgl.opengl.GL11.GL_FALSE; import static org.lwjgl.opengl.GL20.*; public abstract class Shader extends GLObject { private final ShaderTypeEnum type; private final String glsl; Shader(ShaderTypeEnum type, String glsl) { super(() -> { int shader = GL41.glCreateShaderProgramv(type.getCode(), glsl); int status = glGetProgrami(shader, GL_LINK_STATUS); if (status == GL_FALSE) { int infoLogLength = glGetProgrami(shader, GL_INFO_LOG_LENGTH); String infoLog = glGetProgramInfoLog(shader, infoLogLength); throw new ShaderProgramCompileException(String.format("Compile failure in %s shader:\n%s\n", type, infoLog.trim())); } return shader; }); this.type = type; this.glsl = glsl; } public ShaderTypeEnum getType() { return type; } public String getGLSL() { return glsl; } @Override protected void glDelete(int pointer) { GL20.glDeleteProgram(pointer); } }
27.55814
132
0.632068
100c1b8301ef48a6852b4b4eee5d13f71d4a8681
14,021
package repository; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import io.ebean.Ebean; import io.ebean.EbeanServer; import io.ebean.SerializableConflictException; import io.ebean.Transaction; import io.ebean.TxScope; import io.ebean.annotation.TxIsolation; import java.util.List; import java.util.Optional; import javax.inject.Inject; import javax.persistence.NonUniqueResultException; import javax.persistence.RollbackException; import models.LifecycleStage; import models.Program; import models.Question; import models.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import play.db.ebean.EbeanConfig; import services.program.BlockDefinition; import services.program.ProgramDefinition; import services.program.ProgramQuestionDefinition; import services.program.predicate.AndNode; import services.program.predicate.LeafOperationExpressionNode; import services.program.predicate.OrNode; import services.program.predicate.PredicateDefinition; import services.program.predicate.PredicateExpressionNode; /** A repository object for dealing with versioning of questions and programs. */ public class VersionRepository { private final EbeanServer ebeanServer; private final Logger LOG = LoggerFactory.getLogger(VersionRepository.class); private final ProgramRepository programRepository; @Inject public VersionRepository(EbeanConfig ebeanConfig, ProgramRepository programRepository) { this.ebeanServer = Ebean.getServer(checkNotNull(ebeanConfig).defaultServer()); this.programRepository = checkNotNull(programRepository); } /** * Publish a new version of all programs and questions. All DRAFT programs/questions will become * ACTIVE, and all ACTIVE programs/questions without a draft will be copied to the next version. */ public void publishNewSynchronizedVersion() { try { ebeanServer.beginTransaction(); Version draft = getDraftVersion(); Version active = getActiveVersion(); Preconditions.checkState( draft.getPrograms().size() > 0, "Must have at least 1 program in the draft version."); // Associate any active programs that aren't present in the draft with the draft. active.getPrograms().stream() // Exclude programs deleted in the draft. .filter( activeProgram -> !draft.programIsTombstoned(activeProgram.getProgramDefinition().adminName())) // Exclude programs that are in the draft already. .filter( activeProgram -> draft.getPrograms().stream() .noneMatch( draftProgram -> activeProgram .getProgramDefinition() .adminName() .equals(draftProgram.getProgramDefinition().adminName()))) // For each active program not associated with the draft, associate it with the draft. .forEach( activeProgramNotInDraft -> { activeProgramNotInDraft.addVersion(draft); activeProgramNotInDraft.save(); }); // Associate any active questions that aren't present in the draft with the draft. active.getQuestions().stream() // Exclude questions deleted in the draft. .filter( activeQuestion -> !draft.questionIsTombstoned(activeQuestion.getQuestionDefinition().getName())) // Exclude questions that are in the draft already. .filter( activeQuestion -> draft.getQuestions().stream() .noneMatch( draftQuestion -> activeQuestion .getQuestionDefinition() .getName() .equals(draftQuestion.getQuestionDefinition().getName()))) // For each active question not associated with the draft, associate it with the draft. .forEach( activeQuestionNotInDraft -> { activeQuestionNotInDraft.addVersion(draft); activeQuestionNotInDraft.save(); }); // Move forward the ACTIVE version. active.setLifecycleStage(LifecycleStage.OBSOLETE); draft.setLifecycleStage(LifecycleStage.ACTIVE); active.save(); draft.save(); draft.refresh(); ebeanServer.commitTransaction(); } finally { ebeanServer.endTransaction(); } } /** Get the current draft version. Creates it if one does not exist. */ public Version getDraftVersion() { Optional<Version> version = ebeanServer .find(Version.class) .where() .eq("lifecycle_stage", LifecycleStage.DRAFT) .findOneOrEmpty(); if (version.isPresent()) { return version.get(); } else { // Suspends any existing thread-local transaction if one exists. // This method is often called by two portions of the same outer transaction, // microseconds apart. It's extremely important that there only ever be one // draft version, so we need the highest transaction isolation level - // `SERIALIZABLE` means that the two transactions run as if each transaction // was the only transaction running on the whole database. That is, if any // other code accesses these rows or executes any query which would modify them, // the transaction is rolled back (a RollbackException is thrown). We // are forced to retry. This is expensive in relative terms, but new drafts // are very rare. It is unlikely this will represent a real performance penalty // for any applicant - or even any admin, really. Transaction transaction = ebeanServer.beginTransaction( TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE)); try { Version newDraftVersion = new Version(LifecycleStage.DRAFT); ebeanServer.insert(newDraftVersion); ebeanServer .find(Version.class) .forUpdate() .where() .eq("lifecycle_stage", LifecycleStage.DRAFT) .findOne(); transaction.commit(); return newDraftVersion; } catch (NonUniqueResultException | SerializableConflictException | RollbackException e) { transaction.rollback(e); // We must end the transaction here since we are going to recurse and try again. // We cannot have this transaction on the thread-local transaction stack when that // happens. transaction.end(); return getDraftVersion(); } finally { // This may come after a prior call to `transaction.end` in the event of a // precondition failure - this is okay, since it a double-call to `end` on // a particular transaction. Only double calls to ebeanServer.endTransaction // must be avoided. transaction.end(); } } } public Version getActiveVersion() { return ebeanServer .find(Version.class) .where() .eq("lifecycle_stage", LifecycleStage.ACTIVE) .findOne(); } private Optional<Question> getLatestVersionOfQuestion(long questionId) { String questionName = ebeanServer.find(Question.class).setId(questionId).select("name").findSingleAttribute(); Optional<Question> draftQuestion = getDraftVersion().getQuestions().stream() .filter(question -> question.getQuestionDefinition().getName().equals(questionName)) .findFirst(); if (draftQuestion.isPresent()) { return draftQuestion; } return getActiveVersion().getQuestions().stream() .filter(question -> question.getQuestionDefinition().getName().equals(questionName)) .findFirst(); } /** * For each question in this program, check whether it is the most up-to-date version of the * question which is either DRAFT or ACTIVE. If it is not, update the pointer to the most * up-to-date version of the question, using the given transaction. This method can only be called * on a draft program. */ public void updateQuestionVersions(Program draftProgram) { Preconditions.checkArgument(isInactive(draftProgram), "input program must not be active."); Preconditions.checkArgument( isDraft(draftProgram), "input program must be in the current draft version."); ProgramDefinition.Builder updatedDefinition = draftProgram.getProgramDefinition().toBuilder().setBlockDefinitions(ImmutableList.of()); for (BlockDefinition block : draftProgram.getProgramDefinition().blockDefinitions()) { LOG.trace("Updating screen (block) {}.", block.id()); updatedDefinition.addBlockDefinition(updateQuestionVersions(draftProgram.id, block)); } draftProgram = new Program(updatedDefinition.build()); LOG.trace("Submitting update."); ebeanServer.update(draftProgram); draftProgram.refresh(); } public boolean isInactive(Question question) { return !getActiveVersion().getQuestions().stream() .anyMatch(activeQuestion -> activeQuestion.id.equals(question.id)); } public boolean isInactive(Program program) { return !getActiveVersion().getPrograms().stream() .anyMatch(activeProgram -> activeProgram.id.equals(program.id)); } public boolean isDraft(Question question) { return getDraftVersion().getQuestions().stream() .anyMatch(draftQuestion -> draftQuestion.id.equals(question.id)); } public boolean isDraft(Program program) { return getDraftVersion().getPrograms().stream() .anyMatch(draftProgram -> draftProgram.id.equals(program.id)); } private BlockDefinition updateQuestionVersions(long programDefinitionId, BlockDefinition block) { BlockDefinition.Builder updatedBlock = block.toBuilder().setProgramQuestionDefinitions(ImmutableList.of()); // Update questions contained in this block. for (ProgramQuestionDefinition question : block.programQuestionDefinitions()) { Optional<Question> updatedQuestion = getLatestVersionOfQuestion(question.id()); LOG.trace( "Updating question ID {} to new ID {}.", question.id(), updatedQuestion.orElseThrow().id); updatedBlock.addQuestion( question.loadCompletely( programDefinitionId, updatedQuestion.orElseThrow().getQuestionDefinition())); } // Update questions referenced in this block's predicate(s) if (block.visibilityPredicate().isPresent()) { PredicateDefinition oldPredicate = block.visibilityPredicate().get(); updatedBlock.setVisibilityPredicate( PredicateDefinition.create( updatePredicateNode(oldPredicate.rootNode()), oldPredicate.action())); } if (block.optionalPredicate().isPresent()) { PredicateDefinition oldPredicate = block.optionalPredicate().get(); updatedBlock.setOptionalPredicate( Optional.of( PredicateDefinition.create( updatePredicateNode(oldPredicate.rootNode()), oldPredicate.action()))); } return updatedBlock.build(); } // Update the referenced question IDs in all leaf nodes. Since nodes are immutable, we // recursively recreate the tree with updated leaf nodes. @VisibleForTesting protected PredicateExpressionNode updatePredicateNode(PredicateExpressionNode current) { switch (current.getType()) { case AND: AndNode and = current.getAndNode(); ImmutableSet<PredicateExpressionNode> updatedAndChildren = and.children().stream().map(this::updatePredicateNode).collect(toImmutableSet()); return PredicateExpressionNode.create(AndNode.create(updatedAndChildren)); case OR: OrNode or = current.getOrNode(); ImmutableSet<PredicateExpressionNode> updatedOrChildren = or.children().stream().map(this::updatePredicateNode).collect(toImmutableSet()); return PredicateExpressionNode.create(OrNode.create(updatedOrChildren)); case LEAF_OPERATION: LeafOperationExpressionNode leaf = current.getLeafNode(); Optional<Question> updated = getLatestVersionOfQuestion(leaf.questionId()); return PredicateExpressionNode.create( leaf.toBuilder().setQuestionId(updated.orElseThrow().id).build()); default: return current; } } public void updateProgramsForNewDraftQuestion(long oldId) { getDraftVersion().getPrograms().stream() .filter(program -> program.getProgramDefinition().hasQuestion(oldId)) .forEach(program -> updateQuestionVersions(program)); getActiveVersion().getPrograms().stream() .filter(program -> program.getProgramDefinition().hasQuestion(oldId)) .filter( program -> getDraftVersion() .getProgramByName(program.getProgramDefinition().adminName()) .isEmpty()) .forEach(program -> programRepository.createOrUpdateDraft(program)); } public List<Version> listAllVersions() { return ebeanServer.find(Version.class).findList(); } public void setLive(long versionId) { Version draftVersion = getDraftVersion(); Version activeVersion = getActiveVersion(); Version newActiveVersion = ebeanServer.find(Version.class).setId(versionId).findOne(); newActiveVersion.setLifecycleStage(LifecycleStage.ACTIVE); newActiveVersion.save(); activeVersion.setLifecycleStage(LifecycleStage.OBSOLETE); activeVersion.save(); draftVersion.setLifecycleStage(LifecycleStage.DELETED); draftVersion.save(); } }
43.679128
100
0.683974
82195d320b50bb5f86282615fe703783da42139c
3,799
/** * Copyright (c) 2016 - 2018 Syncleus, 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. */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. * * Since product implements StAX API, it has dependencies to StAX API * classes. * * For additional credits (generally to people who reported problems) * see CREDITS file. */ package com.aparapi.examples.configuration; import com.aparapi.*; import com.aparapi.internal.kernel.*; import java.util.*; /** * Tests device selection via {@link com.aparapi.internal.kernel.KernelManager}. * * @author freemo * @version $Id: $Id */ public class ConfigurationDemo { /** * <p>main.</p> * * @param ignored an array of {@link java.lang.String} objects. */ public static void main(String[] ignored) { StringBuilder report; List<Integer> tests = Arrays.asList(0, 1, 2, 3); int reps = 1; for (int rep = 0; rep < reps; ++rep) { runTests(rep == 0, tests); if (rep % 100 == 99 || rep == 0 || rep == reps - 1) { report = new StringBuilder("rep = " + rep + "\n"); KernelManager.instance().reportDeviceUsage(report, true); System.out.println(report); } } } private static void runTests(boolean verbose, List<Integer> testIndicesToRun) { final int globalSize = 1; Kernel kernel; if (testIndicesToRun.contains(0)) { if (verbose) { System.out.println(); System.out.println("Testing default KernelPreferences with kernel which cannot be run in OpenCL, with fallback algorithm"); System.out.println(); } kernel = new KernelWithAlternateFallbackAlgorithm(); kernel.execute(globalSize); kernel.dispose(); } if (testIndicesToRun.contains(1)) { if (verbose) { System.out.println(); System.out.println("Testing default KernelPreferences with kernel which cannot be run in OpenCL, without fallback algorithm"); System.out.println(); } kernel = new KernelWithoutAlternateFallbackAlgorithm(); kernel.execute(globalSize); kernel.dispose(); } if (testIndicesToRun.contains(2)) { if (verbose) { System.out.println(); System.out.println("Retesting previous case, should jump straight to regular java implementation without warnings"); System.out.println(); } kernel = new KernelWithoutAlternateFallbackAlgorithm(); kernel.execute(globalSize); kernel.dispose(); } if (testIndicesToRun.contains(3)) { if (verbose) { System.out.println(); System.out.println("Testing default KernelPreferences with kernel which should be run in OpenCL"); System.out.println(); } KernelOkayInOpenCL clKernel = new KernelOkayInOpenCL(); kernel = clKernel; kernel.execute(clKernel.inChars.length); String result = new String(clKernel.outChars); if (verbose) { System.out.println("kernel output: " + result); } kernel.dispose(); } } }
33.324561
138
0.62885
fa824e59caffc1feec8673b4e1cb2326e099f7ff
833
package mn223dn_assign3; public class MultiDisplay { private int displayCount = 0; private String displayMessage = "" ; public MultiDisplay(){ } public MultiDisplay(String msg, int count){ displayMessage = msg; displayCount = count; } public void setDisplayMessage(String msg){ displayMessage = msg; } public void setDisplayCount(int count){ displayCount = count; } public void display(){ for (int i=0; i<displayCount; i++){ System.out.println(displayMessage);} } public void display(String msg, int count){ displayMessage = msg; displayCount = count; for (int i=0; i<displayCount; i++){ System.out.println(displayMessage);} } public String getDisplayMessage(){ return displayMessage; } public int getDisplayCount(){ return displayCount; } }
21.358974
45
0.678271
714da9084aa7a9a07493b35160e3a5561d5150cd
3,701
package android.support.p000v4.view; import android.os.Bundle; import android.view.View; import android.view.View.AccessibilityDelegate; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; /* renamed from: android.support.v4.view.AccessibilityDelegateCompatJellyBean */ class AccessibilityDelegateCompatJellyBean { /* renamed from: android.support.v4.view.AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean */ public interface AccessibilityDelegateBridgeJellyBean { boolean dispatchPopulateAccessibilityEvent(View view, AccessibilityEvent accessibilityEvent); Object getAccessibilityNodeProvider(View view); void onInitializeAccessibilityEvent(View view, AccessibilityEvent accessibilityEvent); void onInitializeAccessibilityNodeInfo(View view, Object obj); void onPopulateAccessibilityEvent(View view, AccessibilityEvent accessibilityEvent); boolean onRequestSendAccessibilityEvent(ViewGroup viewGroup, View view, AccessibilityEvent accessibilityEvent); boolean performAccessibilityAction(View view, int i, Bundle bundle); void sendAccessibilityEvent(View view, int i); void sendAccessibilityEventUnchecked(View view, AccessibilityEvent accessibilityEvent); } AccessibilityDelegateCompatJellyBean() { } public static Object newAccessibilityDelegateBridge(final AccessibilityDelegateBridgeJellyBean bridge) { return new AccessibilityDelegate() { public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { return bridge.dispatchPopulateAccessibilityEvent(host, event); } public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { bridge.onInitializeAccessibilityEvent(host, event); } public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { bridge.onInitializeAccessibilityNodeInfo(host, info); } public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { bridge.onPopulateAccessibilityEvent(host, event); } public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) { return bridge.onRequestSendAccessibilityEvent(host, child, event); } public void sendAccessibilityEvent(View host, int eventType) { bridge.sendAccessibilityEvent(host, eventType); } public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { bridge.sendAccessibilityEventUnchecked(host, event); } public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { return (AccessibilityNodeProvider) bridge.getAccessibilityNodeProvider(host); } public boolean performAccessibilityAction(View host, int action, Bundle args) { return bridge.performAccessibilityAction(host, action, args); } }; } public static Object getAccessibilityNodeProvider(Object delegate, View host) { return ((AccessibilityDelegate) delegate).getAccessibilityNodeProvider(host); } public static boolean performAccessibilityAction(Object delegate, View host, int action, Bundle args) { return ((AccessibilityDelegate) delegate).performAccessibilityAction(host, action, args); } }
43.034884
121
0.734396
0abd90dfbb594c4038f19f4dae5e7fd30e170e24
903
package com.springboot.controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController @RequestMapping("/blog") public class BlogController { @RequestMapping("/{id}") public ModelAndView show(@PathVariable("id") Integer id) { ModelAndView mav = new ModelAndView(); mav.addObject("id", id); mav.setViewName("blog"); return mav; } @RequestMapping("/query") public ModelAndView query(@RequestParam(value = "q", required = false)String q) { ModelAndView mav = new ModelAndView(); mav.addObject("query", q); mav.setViewName("query"); return mav; } }
30.1
85
0.707641
41c957210cd8699cae527f437f6b8b83866af71d
1,287
package algorithm.easy; import java.util.*; /** * Created by Kyle on 09/05/2017. */ public class IntersectionOfTwoArray { public int[] intersection(int[] nums1, int[] nums2) { HashMap<Integer, Integer> map = new HashMap<>(); List<Integer> result = new ArrayList<>(); for (int num : nums1) { if (map.containsKey(num)) map.put(num, map.get(num) + 1); else map.put(num, 1); } for (int num : nums2) { if (map.containsKey(num) && map.get(num) > 0) { result.add(num); map.put(num, map.get(num) - 1); } } int[] res = new int[result.size()]; int i = 0; for (int num : result) res[i++] = num; return res; } public int[] intersectionWithNoDuplicate(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); Set<Integer> intersectSet = new HashSet<>(); for (Integer i : nums1) { set.add(i); } for (int i : nums2) { if (set.contains(i)) intersectSet.add(i); } int i = 0; int[] result = new int[intersectSet.size()]; for (int num : intersectSet) { result[i++] = num; } return result; } }
27.978261
72
0.496503
0e779f46b3c38b9ee0cd674a5ae9b96255ffc829
248
package org.robolectric.shadows; import android.text.TextPaint; import org.robolectric.annotation.Implements; /** * Shadow for {@link android.text.TextPaint}. */ @Implements(TextPaint.class) public class ShadowTextPaint extends ShadowPaint { }
20.666667
50
0.78629
751163fd98878fd1b04dadd02aac98d6cb9ef562
1,935
package com.andcreations.ae.tex.font; import java.io.File; import com.andcreations.ae.tex.font.data.TexFontData; /** * @author Mikolaj Gucki */ public class TexFontCfg { /** The font identifier. */ private String id; /** The font data. */ private TexFontData data; /** The path to the output image from which subtextures are extracted. */ private File imageFile; /** The output Lua file. */ private File luaFile; /** The output raw file. */ private File rawFile; /** The output mask file. */ private File maskFile; /** The output data file. */ private File dataFile; /** */ public TexFontCfg(String id,TexFontData data) { this.id = id; this.data = data; } /** */ public String getId() { return id; } /** */ public TexFontData getData() { return data; } /** */ public void setImageFile(File imageFile) { this.imageFile = imageFile; } /** */ public File getImageFile() { return imageFile; } /** */ public void setLuaFile(File luaFile) { this.luaFile = luaFile; } /** */ public File getLuaFile() { return luaFile; } /** */ public void setRawFile(File rawFile) { this.rawFile = rawFile; } /** */ public File getRawFile() { return rawFile; } /** */ public void setMaskFile(File maskFile) { this.maskFile = maskFile; } /** */ public File getMaskFile() { return maskFile; } /** */ public void setDataFile(File dataFile) { this.dataFile = dataFile; } /** */ public File getDataFile() { return dataFile; } }
19.744898
78
0.497674
1209b5015d9157d35494ccc8fbda2ba948a72642
8,946
package com.lufax.jijin.daixiao.gson; import com.lufax.jijin.fundation.gson.BaseGson; import java.util.List; public class JijinDaixiaoInfoGson extends BaseGson{ private List<JijinExBuyLimitGson> jijinExBuyLimitGsons; //2.1 认申购起点限额 private List<JijinExDiscountGson> jijinExDiscountGsons;//2.2 优惠费率 private JijinExIncomeModeGson jijinExIncomeModeGson; //2.3 默认分红方式 private JijinExSellDayCountGson jijinExSellDayCountGson; //2.4 赎回到帐日期 private List<JijinExFeeGson> jijinExFeeGsons; //2.5 费率 private List<JijinExNetValueGson> jijinExNetValueGsons; //2.6 历史净值列表(单品页显示最多5条) private List<JijinExNetValueGson> jijinExNetValueAllGsons; //2.6 历史净值全量数据 private JijinExScopeGson jijinExScopeGson; //2.7 基金规模信息 private List<JijinExGradeGson> jijinExGradeGsons;//2.8 基金评级列表 private JijinExInfoGson jijinExInfoGson;//2.9 基金基本信息 private List<JijinExDividendGson> jijinExDividendGsons; //2.10历史分红列表 private JijinExFundTypeGson jijinExFundTypeGson; //2.11 基金分类 private JijinExRiskGradeGson jijinExRiskGradeGson; //2.12 风险等级 private List<JijinExMfPerformGson> jijinExMfPerformGsons;//2.13 基金净值增长率 private List<JijinExFxPerformGson> jijinExFxPerformGsons;//2.14 指数涨跌幅 private JijinExSellLimitGson jijinExSellLimitGson; //2.15 赎回转换起点 /*private List<JijinExGoodSubjectGson> jijinExGoodSubjectGsons;//2.16 精选主题 private List<JijinExHotSubjectGson> jijinExHotSubjectGsons;//2.17 人气方案 */ private List<JijinExManagerGson> jijinExManagerGsons; //2.18基金经理列表 private List<JijinExYieldRateGson> jijinExYieldRate5Gsons; //2.19 货基年化收益列表(单品页显示最多5条) private List<JijinExYieldRateGson> jijinExYieldRateGsons;//2.19 货基七日/万分收益 private List<JijinExAssetConfGson> assetConfs; //2.20 资产配置 private JijinExAssetConfGson assetConf;//资产配置应该只有一条 private List<JijinExIndustryConfGson> industryConfs; //2.21 行业配置 private List<JijinExStockConfGson> stockConfs; //2.22 股票配置 private List<JijinExBondConfGson> bondConfs; //2.23 债券配置 //private List<JijinExAnnounceGson> announces; //2.25 基金公告 private JijinExCharacterGson character; //2.26 基金特性 public List<JijinExAssetConfGson> getAssetConfs() { return assetConfs; } public void setAssetConfs(List<JijinExAssetConfGson> assetConfs) { this.assetConfs = assetConfs; } public List<JijinExBuyLimitGson> getJijinExBuyLimitGsons() { return jijinExBuyLimitGsons; } public void setJijinExBuyLimitGsons(List<JijinExBuyLimitGson> jijinExBuyLimitGsons) { this.jijinExBuyLimitGsons = jijinExBuyLimitGsons; } public List<JijinExDiscountGson> getJijinExDiscountGsons() { return jijinExDiscountGsons; } public void setJijinExDiscountGsons(List<JijinExDiscountGson> jijinExDiscountGsons) { this.jijinExDiscountGsons = jijinExDiscountGsons; } public JijinExIncomeModeGson getJijinExIncomeModeGson() { return jijinExIncomeModeGson; } public void setJijinExIncomeModeGson(JijinExIncomeModeGson jijinExIncomeModeGson) { this.jijinExIncomeModeGson = jijinExIncomeModeGson; } public JijinExSellDayCountGson getJijinExSellDayCountGson() { return jijinExSellDayCountGson; } public void setJijinExSellDayCountGson(JijinExSellDayCountGson jijinExSellDayCountGson) { this.jijinExSellDayCountGson = jijinExSellDayCountGson; } public List<JijinExFeeGson> getJijinExFeeGsons() { return jijinExFeeGsons; } public void setJijinExFeeGsons(List<JijinExFeeGson> jijinExFeeGsons) { this.jijinExFeeGsons = jijinExFeeGsons; } public JijinExScopeGson getJijinExScopeGson() { return jijinExScopeGson; } public void setJijinExScopeGson(JijinExScopeGson jijinExScopeGson) { this.jijinExScopeGson = jijinExScopeGson; } public List<JijinExGradeGson> getJijinExGradeGsons() { return jijinExGradeGsons; } public void setJijinExGradeGsons(List<JijinExGradeGson> jijinExGradeGsons) { this.jijinExGradeGsons = jijinExGradeGsons; } public JijinExInfoGson getJijinExInfoGson() { return jijinExInfoGson; } public void setJijinExInfoGson(JijinExInfoGson jijinExInfoGson) { this.jijinExInfoGson = jijinExInfoGson; } public List<JijinExDividendGson> getJijinExDividendGsons() { return jijinExDividendGsons; } public void setJijinExDividendGsons(List<JijinExDividendGson> jijinExDividendGsons) { this.jijinExDividendGsons = jijinExDividendGsons; } public JijinExFundTypeGson getJijinExFundTypeGson() { return jijinExFundTypeGson; } public void setJijinExFundTypeGson(JijinExFundTypeGson jijinExFundTypeGson) { this.jijinExFundTypeGson = jijinExFundTypeGson; } public JijinExRiskGradeGson getJijinExRiskGradeGson() { return jijinExRiskGradeGson; } public void setJijinExRiskGradeGson(JijinExRiskGradeGson jijinExRiskGradeGson) { this.jijinExRiskGradeGson = jijinExRiskGradeGson; } public List<JijinExMfPerformGson> getJijinExMfPerformGsons() { return jijinExMfPerformGsons; } public void setJijinExMfPerformGsons(List<JijinExMfPerformGson> jijinExMfPerformGsons) { this.jijinExMfPerformGsons = jijinExMfPerformGsons; } public List<JijinExFxPerformGson> getJijinExFxPerformGsons() { return jijinExFxPerformGsons; } public void setJijinExFxPerformGsons(List<JijinExFxPerformGson> jijinExFxPerformGsons) { this.jijinExFxPerformGsons = jijinExFxPerformGsons; } public JijinExSellLimitGson getJijinExSellLimitGson() { return jijinExSellLimitGson; } public void setJijinExSellLimitGson(JijinExSellLimitGson jijinExSellLimitGson) { this.jijinExSellLimitGson = jijinExSellLimitGson; } /* public List<JijinExGoodSubjectGson> getJijinExGoodSubjectGsons() { return jijinExGoodSubjectGsons; } public void setJijinExGoodSubjectGsons(List<JijinExGoodSubjectGson> jijinExGoodSubjectGsons) { this.jijinExGoodSubjectGsons = jijinExGoodSubjectGsons; } public List<JijinExHotSubjectGson> getJijinExHotSubjectGsons() { return jijinExHotSubjectGsons; } public void setJijinExHotSubjectGsons(List<JijinExHotSubjectGson> jijinExHotSubjectGsons) { this.jijinExHotSubjectGsons = jijinExHotSubjectGsons; }*/ public List<JijinExManagerGson> getJijinExManagerGsons() { return jijinExManagerGsons; } public void setJijinExManagerGsons(List<JijinExManagerGson> jijinExManagerGsons) { this.jijinExManagerGsons = jijinExManagerGsons; } public List<JijinExNetValueGson> getJijinExNetValueGsons() { return jijinExNetValueGsons; } public void setJijinExNetValueGsons(List<JijinExNetValueGson> jijinExNetValueGsons) { this.jijinExNetValueGsons = jijinExNetValueGsons; } public List<JijinExNetValueGson> getJijinExNetValueAllGsons() { return jijinExNetValueAllGsons; } public void setJijinExNetValueAllGsons(List<JijinExNetValueGson> jijinExNetValueAllGsons) { this.jijinExNetValueAllGsons = jijinExNetValueAllGsons; } public List<JijinExYieldRateGson> getJijinExYieldRateGsons() { return jijinExYieldRateGsons; } public void setJijinExYieldRateGsons(List<JijinExYieldRateGson> jijinExYieldRateGsons) { this.jijinExYieldRateGsons = jijinExYieldRateGsons; } public List<JijinExYieldRateGson> getJijinExYieldRate5Gsons() { return jijinExYieldRate5Gsons; } public void setJijinExYieldRate5Gsons(List<JijinExYieldRateGson> jijinExYieldRate5Gsons) { this.jijinExYieldRate5Gsons = jijinExYieldRate5Gsons; } public JijinExCharacterGson getCharacter() { return character; } public void setCharacter(JijinExCharacterGson character) { this.character = character; } public List<JijinExIndustryConfGson> getIndustryConfs() { return industryConfs; } public void setIndustryConfs(List<JijinExIndustryConfGson> industryConfs) { this.industryConfs = industryConfs; } public List<JijinExStockConfGson> getStockConfs() { return stockConfs; } public void setStockConfs(List<JijinExStockConfGson> stockConfs) { this.stockConfs = stockConfs; } public List<JijinExBondConfGson> getBondConfs() { return bondConfs; } public void setBondConfs(List<JijinExBondConfGson> bondConfs) { this.bondConfs = bondConfs; } public JijinExAssetConfGson getAssetConf() { return assetConf; } public void setAssetConf(JijinExAssetConfGson assetConf) { this.assetConf = assetConf; } /* public List<JijinExAnnounceGson> getAnnounces() { return announces; } public void setAnnounces(List<JijinExAnnounceGson> announces) { this.announces = announces; }*/ }
33.380597
98
0.75218
cef74ae12ae74247b6c043e2adf1a46bcb3c7110
5,098
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.authorization.implementation; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.resourcemanager.authorization.AuthorizationManager; import com.azure.resourcemanager.authorization.models.ActiveDirectoryApplication; import com.azure.resourcemanager.authorization.models.ActiveDirectoryApplications; import com.azure.resourcemanager.authorization.fluent.inner.ApplicationInner; import com.azure.resourcemanager.authorization.fluent.ApplicationsClient; import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.CreatableResourcesImpl; import com.azure.resourcemanager.resources.fluentcore.arm.models.HasManager; import java.util.UUID; import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; import reactor.core.publisher.Mono; /** The implementation of Applications and its parent interfaces. */ public class ActiveDirectoryApplicationsImpl extends CreatableResourcesImpl<ActiveDirectoryApplication, ActiveDirectoryApplicationImpl, ApplicationInner> implements ActiveDirectoryApplications, HasManager<AuthorizationManager> { private ApplicationsClient innerCollection; private AuthorizationManager manager; public ActiveDirectoryApplicationsImpl( final ApplicationsClient client, final AuthorizationManager authorizationManager) { this.innerCollection = client; this.manager = authorizationManager; } @Override public PagedIterable<ActiveDirectoryApplication> list() { return new PagedIterable<>(listAsync()); } @Override public PagedFlux<ActiveDirectoryApplication> listAsync() { return PagedConverter.flatMapPage(inner().listAsync(), applicationInner -> { ActiveDirectoryApplicationImpl application = this.wrapModel(applicationInner); return application.refreshCredentialsAsync().thenReturn(application); }); } @Override protected ActiveDirectoryApplicationImpl wrapModel(ApplicationInner applicationInner) { if (applicationInner == null) { return null; } return new ActiveDirectoryApplicationImpl(applicationInner, manager()); } @Override public ActiveDirectoryApplicationImpl getById(String id) { return (ActiveDirectoryApplicationImpl) getByIdAsync(id).block(); } @Override public Mono<ActiveDirectoryApplication> getByIdAsync(String id) { return innerCollection .getAsync(id) .flatMap( applicationInner -> new ActiveDirectoryApplicationImpl(applicationInner, manager()).refreshCredentialsAsync()); } @Override public ActiveDirectoryApplication getByName(String spn) { return getByNameAsync(spn).block(); } @Override public Mono<ActiveDirectoryApplication> getByNameAsync(String name) { final String trimmed = name.replaceFirst("^'+", "").replaceAll("'+$", ""); return inner() .listAsync(String.format("displayName eq '%s'", trimmed)) .singleOrEmpty() .switchIfEmpty( Mono .defer( () -> { try { UUID.fromString(trimmed); return inner().listAsync(String.format("appId eq '%s'", trimmed)).singleOrEmpty(); } catch (IllegalArgumentException e) { return Mono.empty(); } })) .map(applicationInner -> new ActiveDirectoryApplicationImpl(applicationInner, manager())) .flatMap(activeDirectoryApplication -> activeDirectoryApplication.refreshCredentialsAsync()); } @Override protected ActiveDirectoryApplicationImpl wrapModel(String name) { return new ActiveDirectoryApplicationImpl(new ApplicationInner().withDisplayName(name), manager()); } @Override public Mono<Void> deleteByIdAsync(String id) { return inner().deleteAsync(id); } @Override public ActiveDirectoryApplicationImpl define(String name) { return wrapModel(name); } @Override public AuthorizationManager manager() { return this.manager; } public ApplicationsClient inner() { return this.innerCollection; } @Override public PagedIterable<ActiveDirectoryApplication> listByFilter(String filter) { return new PagedIterable<>(listByFilterAsync(filter)); } @Override public PagedFlux<ActiveDirectoryApplication> listByFilterAsync(String filter) { return PagedConverter.flatMapPage(inner().listAsync(filter), applicationInner -> { ActiveDirectoryApplicationImpl application = this.wrapModel(applicationInner); return application.refreshCredentialsAsync().thenReturn(application); }); } }
38.916031
114
0.695175
4bb373be74c213295531d2a41b42aaa9b409db89
797
package mage.cards.r; import java.util.UUID; import mage.abilities.effects.common.continuous.BoostControlledEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; /** * * @author Styxo */ public final class RallyingFire extends CardImpl { public RallyingFire(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{2}{R}"); // Creatures you control get +2/+0 until end of turn. this.getSpellAbility().addEffect(new BoostControlledEffect(2, 0, Duration.EndOfTurn)); } private RallyingFire(final RallyingFire card) { super(card); } @Override public RallyingFire copy() { return new RallyingFire(this); } }
23.441176
94
0.705144
920a54f264afb322e47d1d8e3f62f806378d52d2
4,043
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.lib; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.Stack; import org.apache.hadoop.hive.ql.parse.SemanticException; /** * base class for operator graph walker this class takes list of starting ops * and walks them one by one. it maintains list of walked operators * (dispatchedList) and a list of operators that are discovered but not yet * dispatched */ public class DefaultGraphWalker implements GraphWalker { protected Stack<Node> opStack; protected final List<Node> toWalk = new ArrayList<Node>(); protected final HashMap<Node, Object> retMap = new HashMap<Node, Object>(); protected final Dispatcher dispatcher; /** * Constructor. * * @param disp * dispatcher to call for each op encountered */ public DefaultGraphWalker(Dispatcher disp) { dispatcher = disp; opStack = new Stack<Node>(); } /** * @return the toWalk */ public List<Node> getToWalk() { return toWalk; } /** * @return the doneList */ protected Set<Node> getDispatchedList() { return retMap.keySet(); } /** * Dispatch the current operator. * * @param nd * node being walked * @param ndStack * stack of nodes encountered * @throws SemanticException */ public void dispatch(Node nd, Stack<Node> ndStack) throws SemanticException { dispatchAndReturn(nd, ndStack); } /** * Returns dispatch result */ public <T> T dispatchAndReturn(Node nd, Stack<Node> ndStack) throws SemanticException { Object[] nodeOutputs = null; if (nd.getChildren() != null) { nodeOutputs = new Object[nd.getChildren().size()]; int i = 0; for (Node child : nd.getChildren()) { nodeOutputs[i++] = retMap.get(child); } } Object retVal = dispatcher.dispatch(nd, ndStack, nodeOutputs); retMap.put(nd, retVal); return (T) retVal; } /** * starting point for walking. * * @throws SemanticException */ public void startWalking(Collection<Node> startNodes, HashMap<Node, Object> nodeOutput) throws SemanticException { toWalk.addAll(startNodes); while (toWalk.size() > 0) { Node nd = toWalk.remove(0); walk(nd); if (nodeOutput != null && getDispatchedList().contains(nd)) { nodeOutput.put(nd, retMap.get(nd)); } } } /** * walk the current operator and its descendants. * * @param nd * current operator in the graph * @throws SemanticException */ protected void walk(Node nd) throws SemanticException { if (opStack.empty() || nd != opStack.peek()) { opStack.push(nd); } if ((nd.getChildren() == null) || getDispatchedList().containsAll(nd.getChildren())) { // all children are done or no need to walk the children if (!getDispatchedList().contains(nd)) { dispatch(nd, opStack); } opStack.pop(); return; } // add children, self to the front of the queue in that order getToWalk().add(0, nd); getToWalk().removeAll(nd.getChildren()); getToWalk().addAll(0, nd.getChildren()); } }
28.272727
89
0.664358
bc637ed4f5b91188faa79982b1aabf5836218fb5
4,947
/* * Copyright 2010 Capgemini and Contributors * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package net.sf.appstatus.core; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.List; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.appstatus.core.services.IService; import net.sf.appstatus.core.services.IServiceManager; import net.sf.appstatus.core.services.IServiceMonitor; /** * This is the entry point for services monitor. * * <p> * Must be initialized once before calling other methods. * <p> * AppStatusServices services = new AppStatusServices(); <br/> * services.init(); * </p> * * @author Nicolas Richeton * */ @Deprecated public class AppStatusServices { private static Logger logger = LoggerFactory.getLogger(AppStatusServices.class); private boolean initDone = false; private IObjectInstantiationListener objectInstanciationListener = null; private IServiceManager serviceManager = null; private IServletContextProvider servletContextProvider = null; /** * Status Service creator. */ public AppStatusServices() { } private void checkInit() { if (!initDone) { logger.warn("Not initialized. Starting init"); init(); } } /** * Try to instantiate a class. * * @param className * @return an object instance of "className" class or null if instantiation * is not possible */ private Object getClassInstance(String className) { Object obj = null; if (objectInstanciationListener != null) { obj = objectInstanciationListener.getInstance(className); } if (obj == null) { try { obj = Class.forName(className).newInstance(); } catch (ClassNotFoundException e) { logger.warn("Class {} not found ", className, e); } catch (InstantiationException e) { logger.warn("Cannot instanciate {} ", className, e); } catch (IllegalAccessException e) { logger.warn("Cannot access class {} for instantiation ", className, e); } } if (obj != null) { injectServletContext(obj); } return obj; } public IServiceMonitor getServiceMonitor(String name, String group) { checkInit(); IService batch = null; if (serviceManager != null) { batch = serviceManager.getService(name, group); return serviceManager.getMonitor(batch); } return null; } public List<IService> getServices() { return serviceManager.getServices(); } public IServletContextProvider getServletContext() { return servletContextProvider; } public synchronized void init() { if (initDone) { logger.warn("Already initialized"); return; } try { // Load plugins loadPlugins(); } catch (Exception e) { logger.error("Initialization error", e); } initDone = true; } private void injectServletContext(Object instance) { // Inject servlet context if possible if (instance instanceof IServletContextAware && servletContextProvider != null) { ((IServletContextAware) instance).setServletContext(servletContextProvider.getServletContext()); } } private void loadPlugins() { try { Enumeration<URL> plugins = AppStatusServices.class.getClassLoader() .getResources("net/sf/appstatus/plugin.properties"); while (plugins.hasMoreElements()) { URL url = plugins.nextElement(); logger.info(url.toString()); Properties p = loadProperties(url); // serviceManager String serviceManagerClass = p.getProperty("serviceManager"); if (serviceManagerClass != null) { serviceManager = (IServiceManager) getClassInstance(serviceManagerClass); } } } catch (IOException e) { logger.warn("Error loading plugins", e); } } /** * Load a properties file from a given URL. * * @param url * an url * @return a {@link Properties} object * @throws IOException * in an error occurs */ private Properties loadProperties(URL url) throws IOException { // Load plugin configuration Properties p = new Properties(); InputStream is = url.openStream(); p.load(is); is.close(); return p; } public void setObjectInstanciationListener(IObjectInstantiationListener objectInstanciationListener) { this.objectInstanciationListener = objectInstanciationListener; } public void setServletContextProvider(IServletContextProvider servletContext) { this.servletContextProvider = servletContext; } }
25.369231
103
0.717202
ac37563a117f0fb2bc3df895dcc7925712ddf0ea
245
package com.example.financia.exception; public class ErroAutenticacao extends RuntimeException{ /** * */ private static final long serialVersionUID = 1L; public ErroAutenticacao(String mensagem) { super(mensagem); } }
17.5
56
0.706122
5c1f89874603d61726064a475d977f113eb1a499
2,577
/* * 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 org.multireserve.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * * @author Nikkor50 */ public class LoginInterceptor implements HandlerInterceptor { //protected final Log logger = LogFactory.getLog(LoginInterceptor.class); private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class); String nologin = "http://www.bing.com"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("Pre-handle"); HttpSession session = request.getSession(); logger.info(request.getParameter("sessionId")); String servletpath = request.getServletPath(); if (servletpath != null && servletpath.equals("/logout.do")) { return true; } else { String contextpath = request.getContextPath(); logger.info("context path = " + contextpath); // query parameter String querystring = request.getQueryString() == null ? "" : request.getQueryString(); //System.out.println("query string = " + querystring); String[] qs = querystring.split("&"); String qsv = ""; int len = qs.length; for (int i = 0; i < len; i++) { if (qs[i].startsWith("method=")) { qsv = qs[i].substring(7); } } String empno = (String) session.getAttribute("empno"); } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { //System.out.println("Post-handle"); logger.info("Post-handle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { //System.out.println("after-Completion"); logger.info("after-Completion"); } }
31.048193
89
0.638339
5782b1856984b7b7a3c40bb3e051f203adf1d27f
11,653
/* * 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.stanbol.entityhub.jersey.utils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.mail.BodyPart; import javax.mail.MessagingException; import javax.mail.internet.MimeMultipart; import javax.mail.internet.ParseException; import javax.mail.util.ByteArrayDataSource; import javax.ws.rs.FormParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.MessageBodyReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utilities for implementing {@link MessageBodyReader}. * @author Rupert Westenthaler * */ public final class MessageBodyReaderUtils { private MessageBodyReaderUtils(){ /*do not instantiate Util classes */ }; private final static Logger log = LoggerFactory.getLogger(MessageBodyReaderUtils.class); /** * Returns content parsed as {@link MediaType#APPLICATION_FORM_URLENCODED}. * It assumes that the encoding and the content is defined by own parameters. * For the content this method allows to parse several parameters. The first * existing one is used to get the content. The parameter actually used to * retrieve the content will be available via {@link RequestData#getName()}.<p> * This Method will load the content several time into memory and should * not be used for big contents. However this should be fine in cases * data are parsed as {@link MediaType#APPLICATION_FORM_URLENCODED}<p> * This Method is necessary because within {@link MessageBodyReader} one * can not use the {@link FormParam} annotations because only the * {@link InputStream} is parsed to the * {@link MessageBodyReader#readFrom(Class, Type, java.lang.annotation.Annotation[], MediaType, javax.ws.rs.core.MultivaluedMap, InputStream)} * method<p> * To test this Method with curl use: * <code><pre> * curl -v -X POST --data-urlencode "{encodingParam}=application/rdf+xml" * --data-urlencode "{contentParam}@{datafile}" * {serviceURL} * </pre></code> * Note that between {contentParam} and the datafile MUST NOT be a '='! * @param formData the data of the form as stream * @param charset the charset used for the form data * @param encodingParam the parameter name used to parse the encoding * @param contentParams the list of parameters used for the content. The first * existing parameter is used to parse the content. Additional ones are * ignored. * @return The parsed content (MediaType and InputStream) * @throws IOException On any exception while reading from the parsed stream. * @throws UnsupportedEncodingException if the parsed charset is not supported * by this plattform * @throws IllegalArgumentException In case of a {@link Status#BAD_REQUEST} */ public static RequestData formForm(InputStream formData,String charset, String encodingParam,List<String> contentParams) throws IOException,UnsupportedEncodingException,IllegalArgumentException{ Map<String,String> params = JerseyUtils.parseForm(formData, charset); log.debug("Read from Form:"); MediaType mediaType; if(encodingParam != null){ String mediaTypeString = params.get(encodingParam); log.debug(" > encoding: {}={}",encodingParam,mediaTypeString); if(mediaTypeString != null){ try { mediaType = MediaType.valueOf(mediaTypeString); } catch (IllegalArgumentException e) { throw new IllegalStateException(String.format( "Illegal formatted Content-Type %s parsed by parameter %s", encodingParam,mediaTypeString),e); } } else { mediaType = null; } } else { log.debug(" > encoding: no encoding prameter set"); mediaType = null; } log.debug(" <- mediaType = {}",mediaType); InputStream entityStream = null; String contentParam = null; Iterator<String> contentParamIterator = contentParams.iterator(); while(entityStream == null && contentParamIterator.hasNext()){ contentParam = contentParamIterator.next(); String content = params.get(contentParam); log.debug(" > content: {}={}",contentParam,content); if(content != null){ entityStream = new ByteArrayInputStream(content.getBytes(charset)); } } if(entityStream == null){ throw new IllegalArgumentException(String.format( "No content found for any of the following parameters %s", contentParams)); } return new RequestData(mediaType,contentParam,entityStream); } /** * Returns content parsed from {@link MediaType#MULTIPART_FORM_DATA}. * It iterates over all {@link BodyPart}s and tries to create {@link RequestData} * instances. In case the {@link BodyPart#getContentType()} is not present or * can not be parsed, the {@link RequestData#getMediaType()} is set to * <code>null</code>. If {@link BodyPart#getInputStream()} is not defined an * {@link IllegalArgumentException} is thrown. The {@link BodyPart#getFileName()} * is used for {@link RequestData#getName()}. The ordering of the returned * Content instances is the same as within the {@link MimeMultipart} instance * parsed from the input stream. <p> * This Method does NOT load the data into memory, but returns directly the * {@link InputStream}s as returned by the {@link BodyPart}s. Therefore * it is saved to be used with big attachments.<p> * This Method is necessary because within {@link MessageBodyReader} one * can not use the usual annotations as used within Resources. so this method * allows to access the data directly from the parameters available from the * {@link MessageBodyReader#readFrom(Class, Type, java.lang.annotation.Annotation[], MediaType, javax.ws.rs.core.MultivaluedMap, InputStream)} * method<p> * To test this Method with curl use: * <code><pre> * curl -v -X POST -F "content=@{dataFile};type={mimeType}" * {serviceURL} * </pre></code> * Note that between {contentParam} and the datafile MUST NOT be a '='! * @param mimeData the mime encoded data * @param mediaType the mediaType (parsed to the {@link ByteArrayDataSource} * constructor) * @return the contents parsed from the {@link BodyPart}s * @throws IOException an any Exception while reading the stream or * {@link MessagingException} exceptions other than {@link ParseException}s * @throws IllegalArgumentException If a {@link InputStream} is not available * for any {@link BodyPart} or on {@link ParseException}s while reading the * MimeData from the stream. */ public static List<RequestData> fromMultipart(InputStream mimeData, MediaType mediaType) throws IOException, IllegalArgumentException{ ByteArrayDataSource ds = new ByteArrayDataSource(mimeData, mediaType.toString()); List<RequestData> contents = new ArrayList<RequestData>(); try { MimeMultipart data = new MimeMultipart(ds); //For now search the first bodypart that fits and only debug the others for(int i = 0;i < data.getCount();i++){ BodyPart bp = data.getBodyPart(i); String fileName = bp.getFileName(); MediaType mt; try { mt = bp.getContentType()!=null?MediaType.valueOf(bp.getContentType()):null; }catch (IllegalArgumentException e) { log.warn(String.format( "Unable to parse MediaType form Mime Bodypart %s: " + " fileName %s | Disposition %s | Description %s", i+1,fileName,bp.getDisposition(),bp.getDescription()),e); mt = null; } InputStream stream = bp.getInputStream(); if(stream == null){ throw new IllegalArgumentException(String.format( "Unable to get InputStream for Mime Bodypart %s: " + "mediaType %s fileName %s | Disposition %s | Description %s", i+1,fileName,bp.getDisposition(),bp.getDescription())); } else { contents.add(new RequestData(mt,bp.getFileName(),stream)); } } } catch (ParseException e) { throw new IllegalStateException(String.format( "Unable to parse data from %s request", MediaType.MULTIPART_FORM_DATA_TYPE),e); } catch (MessagingException e) { throw new IOException("Exception while reading "+ MediaType.MULTIPART_FORM_DATA_TYPE+" request",e); } return contents; } /** * Simple class that holds the MediaType, Name and the content as * {@link InputStream}. * @author Rupert Westenthaler * */ public static class RequestData { private final MediaType mediaType; private final InputStream entityStream; private final String contentName; public RequestData(MediaType mediaType,String contentName,InputStream entityStream) { if(entityStream == null){ throw new IllegalArgumentException("The parsed Inputstream MUST NOT be NULL!"); } this.mediaType = mediaType; this.entityStream = entityStream; this.contentName = contentName; } /** * The media type or <code>null</code> if not known * @return the mediaType */ public MediaType getMediaType() { return mediaType; } /** * The stream with the data * @return the entityStream */ public InputStream getEntityStream() { return entityStream; } /** * The name of the content (e.g. the parameter used to parse the content * or the filename provided by the {@link BodyPart}) or <code>null</code> * if not present. The documentation of methods returning instances of * this class should document what is used as name. * @return the contentName */ public String getName() { return contentName; } } }
47.954733
198
0.648331
a203ff98830749e79f976e71230ed92d4a80d7c2
2,390
package aima.core.environment.map; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import aima.core.agent.Action; import aima.core.agent.Percept; import aima.core.agent.impl.DynamicPercept; import aima.core.search.framework.ActionsFunction; import aima.core.search.framework.PerceptToStateFunction; import aima.core.search.framework.ResultFunction; /** * @author Ciaran O'Reilly * */ public class MapFunctionFactory { private static ResultFunction resultFunction; private static PerceptToStateFunction perceptToStateFunction; public static ActionsFunction getActionsFunction(Map map) { return new MapActionsFunction(map, false); } public static ActionsFunction getReverseActionsFunction(Map map) { return new MapActionsFunction(map, true); } public static ResultFunction getResultFunction() { if (null == resultFunction) { resultFunction = new MapResultFunction(); } return resultFunction; } private static class MapActionsFunction implements ActionsFunction { private Map map = null; private boolean reverseMode; public MapActionsFunction(Map map, boolean reverseMode) { this.map = map; this.reverseMode = reverseMode; } public Set<Action> actions(Object state) { Set<Action> actions = new LinkedHashSet<Action>(); String location = state.toString(); List<String> linkedLocations = reverseMode ? map.getPossiblePrevLocations(location) : map.getPossibleNextLocations(location); for (String linkLoc : linkedLocations) { actions.add(new MoveToAction(linkLoc)); } return actions; } } public static PerceptToStateFunction getPerceptToStateFunction() { if (null == perceptToStateFunction) { perceptToStateFunction = new MapPerceptToStateFunction(); } return perceptToStateFunction; } private static class MapResultFunction implements ResultFunction { public MapResultFunction() { } public Object result(Object s, Action a) { if (a instanceof MoveToAction) { MoveToAction mta = (MoveToAction) a; return mta.getToLocation(); } // The Action is not understood or is a NoOp // the result will be the current state. return s; } } private static class MapPerceptToStateFunction implements PerceptToStateFunction { public Object getState(Percept p) { return ((DynamicPercept) p).getAttribute(DynAttributeNames.PERCEPT_IN); } } }
26.263736
86
0.758159
4e7908d482938cb6b21aa92620ca7fe12bbb4d1a
2,200
// by MisaGani 2018 // Tesla Showcase package com.misagani.teslashowcase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private RecyclerView rvCategory; private ArrayList<Tesla> list; private ArrayList<Tesla> listSortir; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rvCategory = findViewById(R.id.rv_category); rvCategory.setHasFixedSize(true); list = new ArrayList<>(); list.addAll(TeslaData.getListData()); listSortir = new ArrayList<>(); showCardView(); } private void showCardView() { rvCategory.setLayoutManager(new LinearLayoutManager(this)); CardViewAdapter cardViewAdapter = new CardViewAdapter(this); cardViewAdapter.setListTesla(list); rvCategory.setAdapter(cardViewAdapter); ItemClickSupport.addTo(rvCategory).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() { @Override public void onItemClicked(RecyclerView recyclerView, int position, View v) { showDetail(position); } }); } private void showDetail(int position) { listSortir.removeAll(TeslaData.getListData()); listSortir.addAll(TeslaData.getListData().subList(position,position + 1)); rvCategory.setLayoutManager(new LinearLayoutManager(this)); DetailsActivity detailActivity = new DetailsActivity(this); detailActivity.setDetailTesla(listSortir); rvCategory.setAdapter(detailActivity); ItemClickSupport.addTo(rvCategory).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() { @Override public void onItemClicked(RecyclerView recyclerView, int position, View v) { showCardView(); } }); } }
31.428571
108
0.681818
965524d5617e9d3d9abdfa4456b6717fcc863dee
15,523
package org.xbib.netty.http.client.transport; import io.netty.channel.Channel; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory; import io.netty.handler.codec.http.multipart.HttpDataFactory; import io.netty.handler.ssl.SslHandler; import org.xbib.net.PercentDecoder; import org.xbib.net.URL; import org.xbib.net.URLSyntaxException; import org.xbib.netty.http.client.Client; import org.xbib.netty.http.client.api.ClientTransport; import org.xbib.netty.http.common.HttpAddress; import org.xbib.netty.http.client.api.Request; import org.xbib.netty.http.client.api.BackOff; import org.xbib.netty.http.common.HttpResponse; import org.xbib.netty.http.common.cookie.Cookie; import org.xbib.netty.http.common.cookie.CookieBox; import javax.net.ssl.SSLSession; import java.io.IOException; import java.net.ConnectException; import java.nio.charset.MalformedInputException; import java.nio.charset.StandardCharsets; import java.nio.charset.UnmappableCharacterException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.SortedMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; public abstract class BaseTransport implements ClientTransport { private static final Logger logger = Logger.getLogger(BaseTransport.class.getName()); protected final Client client; protected final HttpAddress httpAddress; protected Throwable throwable; private static final Request DUMMY = Request.builder(HttpMethod.GET).build(); private final Map<Request, Channel> channels; private SSLSession sslSession; public final Map<String, Flow> flowMap; protected final SortedMap<String, Request> requests; private CookieBox cookieBox; protected HttpDataFactory httpDataFactory; public BaseTransport(Client client, HttpAddress httpAddress) { this.client = client; this.httpAddress = httpAddress; this.channels = new ConcurrentHashMap<>(); this.flowMap = new ConcurrentHashMap<>(); this.requests = new ConcurrentSkipListMap<>(); this.httpDataFactory = new DefaultHttpDataFactory(); } @Override public HttpAddress getHttpAddress() { return httpAddress; } /** * Method for executing the request and respond in a completable future. * * @param request request * @param supplier supplier * @param <T> supplier result * @return completable future */ @Override public <T> CompletableFuture<T> execute(Request request, Function<HttpResponse, T> supplier) throws IOException { Objects.requireNonNull(supplier); final CompletableFuture<T> completableFuture = new CompletableFuture<>(); request.setResponseListener(response -> { if (response != null) { completableFuture.complete(supplier.apply(response)); } else { completableFuture.cancel(true); } close(); }); request.setTimeoutListener(req -> completableFuture.completeExceptionally(new TimeoutException())); request.setExceptionListener(completableFuture::completeExceptionally); execute(request); return completableFuture; } @Override public void close() { get(); cancel(); } @Override public boolean isFailed() { return throwable != null; } @Override public Throwable getFailure() { return throwable; } /** * The underlying network layer failed. * So we fail all (open) promises. * @param throwable the exception */ @Override public void fail(Channel channel, Throwable throwable) { // do not fail more than once if (this.throwable != null) { return; } this.throwable = throwable; logger.log(Level.SEVERE, "channel " + channel + " failing: " + throwable.getMessage(), throwable); for (Flow flow : flowMap.values()) { flow.fail(throwable); } } @Override public void inactive(Channel channel) { // do nothing } @Override public ClientTransport get() { return get(client.getClientConfig().getReadTimeoutMillis(), TimeUnit.MILLISECONDS); } @Override public ClientTransport get(long value, TimeUnit timeUnit) { if (!flowMap.isEmpty()) { for (Map.Entry<String, Flow> entry : flowMap.entrySet()) { Flow flow = entry.getValue(); if (!flow.isClosed()) { for (Integer key : flow.keys()) { String requestKey = getRequestKey(entry.getKey(), key); try { CompletableFuture<Boolean> timeoutFuture = flow.get(key); Boolean timeout = timeoutFuture.get(value, timeUnit); if (timeout) { completeRequest(requestKey); } else { completeRequestTimeout(requestKey, new TimeoutException()); } } catch (TimeoutException e) { completeRequestTimeout(requestKey, new TimeoutException()); } catch (Exception e) { completeRequestExceptionally(requestKey, e); flow.fail(e); } finally { flow.remove(key); } } flow.close(); } } flowMap.clear(); } channels.values().forEach(channel -> { try { client.releaseChannel(channel, true); } catch (IOException e) { logger.log(Level.WARNING, e.getMessage(), e); } }); return this; } @Override public void cancel() { if (!flowMap.isEmpty()) { for (Map.Entry<String, Flow> entry : flowMap.entrySet()) { Flow flow = entry.getValue(); for (Integer key : flow.keys()) { try { flow.get(key).cancel(true); } catch (Exception e) { completeRequestExceptionally(getRequestKey(entry.getKey(), key), e); flow.fail(e); } finally { flow.remove(key); } } flow.close(); } } channels.values().forEach(channel -> { try { client.releaseChannel(channel, true); } catch (IOException e) { logger.log(Level.WARNING, e.getMessage(), e); } }); flowMap.clear(); channels.clear(); requests.clear(); httpDataFactory.cleanAllHttpData(); } @Override public SSLSession getSession() { return sslSession; } protected abstract String getRequestKey(String channelId, Integer streamId); Channel mapChannel(Request request) throws IOException { Channel channel; if (!client.hasPooledConnections()) { channel = channels.get(DUMMY); if (channel == null) { channel = switchNextChannel(); } channels.put(DUMMY, channel); } else { channel = switchNextChannel(); channels.put(request, channel); } SslHandler sslHandler = channel.pipeline().get(SslHandler.class); sslSession = sslHandler != null ? sslHandler.engine().getSession() : null; return channel; } private Channel switchNextChannel() throws IOException { Channel channel = client.newChannel(httpAddress); if (channel != null) { channel.attr(TRANSPORT_ATTRIBUTE_KEY).set(this); waitForSettings(); } else { ConnectException connectException; if (httpAddress != null) { connectException = new ConnectException("unable to connect to " + httpAddress); } else if (client.hasPooledConnections()) { connectException = new ConnectException("unable to get channel from pool"); } else { // API misuse connectException = new ConnectException("unable to get channel"); } this.throwable = connectException; throw connectException; } return channel; } protected Request continuation(Request request, HttpResponse httpResponse) throws URLSyntaxException { if (httpResponse == null) { return null; } if (request == null) { // push promise or something else return null; } try { if (request.canRedirect()) { int status = httpResponse.getStatus().getCode(); switch (status) { case 300: case 301: case 302: case 303: case 305: case 307: case 308: String location = httpResponse.getHeaders().getHeader(HttpHeaderNames.LOCATION); location = new PercentDecoder(StandardCharsets.UTF_8.newDecoder()).decode(location); if (location != null) { logger.log(Level.FINE, "found redirect location: " + location); URL redirUrl = URL.base(request.url()).resolve(location); HttpMethod method = httpResponse.getStatus().getCode() == 303 ? HttpMethod.GET : request.httpMethod(); Request.Builder newHttpRequestBuilder = Request.builder(method, request) .url(redirUrl); request.url().getQueryParams().forEach(pair -> newHttpRequestBuilder.addParameter(pair.getFirst(), pair.getSecond()) ); request.cookies().forEach(newHttpRequestBuilder::addCookie); Request newHttpRequest = newHttpRequestBuilder.build(); StringBuilder hostAndPort = new StringBuilder(); hostAndPort.append(redirUrl.getHost()); if (redirUrl.getPort() != null) { hostAndPort.append(':').append(redirUrl.getPort()); } newHttpRequest.headers().set(HttpHeaderNames.HOST, hostAndPort.toString()); logger.log(Level.FINE, "redirect url: " + redirUrl); return newHttpRequest; } break; default: break; } } } catch (MalformedInputException | UnmappableCharacterException e) { this.throwable = e; } return null; } protected Request retry(Request request, HttpResponse httpResponse) { if (httpResponse == null) { // no response present, invalid in any way return null; } if (request == null) { // push promise or something else return null; } if (request.isBackOff()) { BackOff backOff = request.getBackOff() != null ? request.getBackOff() : client.getClientConfig().getBackOff(); int status = httpResponse.getStatus ().getCode(); switch (status) { case 403: case 404: case 500: case 502: case 503: case 504: case 507: case 509: if (backOff != null) { long millis = backOff.nextBackOffMillis(); if (millis != BackOff.STOP) { logger.log(Level.FINE, () -> "status = " + status + " backing off request by " + millis + " milliseconds"); try { Thread.sleep(millis); } catch (InterruptedException e) { // ignore } return request; } } break; default: break; } } return null; } private void completeRequest(String requestKey) { if (requestKey != null) { Request request = requests.get(requestKey); if (request != null && request.getCompletableFuture() != null) { request.getCompletableFuture().complete(request); } } } private void completeRequestExceptionally(String requestKey, Throwable throwable) { if (requestKey != null) { Request request = requests.get(requestKey); if (request != null) { request.onException(throwable); } } } private void completeRequestTimeout(String requestKey, TimeoutException timeoutException) { if (requestKey != null) { Request request = requests.get(requestKey); if (request != null) { request.onTimeout(); } } } @Override public void setCookieBox(CookieBox cookieBox) { this.cookieBox = cookieBox; } @Override public CookieBox getCookieBox() { return cookieBox; } void addCookie(Cookie cookie) { if (cookieBox == null) { this.cookieBox = new CookieBox(32); } cookieBox.put(cookie, true); } List<Cookie> matchCookiesFromBox(Request request) { return cookieBox == null ? Collections.emptyList() : cookieBox.keySet().stream().filter(cookie -> matchCookie(request.url(), cookie) ).collect(Collectors.toList()); } List<Cookie> matchCookies(Request request) { return request.cookies().stream().filter(cookie -> matchCookie(request.url(), cookie) ).collect(Collectors.toList()); } private boolean matchCookie(URL url, Cookie cookie) { boolean domainMatch = cookie.domain() == null || url.getHost().endsWith(cookie.domain()); if (!domainMatch) { return false; } boolean pathMatch = "/".equals(cookie.path()) || url.getPath().startsWith(cookie.path()); if (!pathMatch) { return false; } boolean secureScheme = "https".equals(url.getScheme()); return (secureScheme && cookie.isSecure()) || (!secureScheme && !cookie.isSecure()); } }
36.016241
135
0.550989
7d218a24680d76c466ef042a3091ad46c293735d
971
/* * Copyright (C) 2018 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 com.udacity.popularmovies.utilities; import android.support.annotation.StringDef; /** * Created by McCrog on 07/04/2018. * */ @StringDef({ SortOrder.POPULAR, SortOrder.TOP_RATED, SortOrder.FAVORITES }) public @interface SortOrder { String POPULAR = "popular"; String TOP_RATED = "top_rated"; String FAVORITES = "favorites"; }
30.34375
75
0.734295
331370bba6ee368406b34820d254dee7eb1b62db
1,441
import java.util.ArrayList; public class MergeSortFreq { public int count = 0; public void mergesort(ArrayList<Term> theArray){ ArrayList<Term> tempArray = new ArrayList<Term>(); mergesort(theArray, tempArray, 0, theArray.size()-1); } private void merge(ArrayList<Term> theArray, ArrayList<Term> tempArray, int first, int mid, int last){ WebPages wp = new WebPages(); int first1 = first; int last1 = mid; int first2 = mid + 1; int last2 = last; int index = first1; while((first1<=last1) && (first2 <= last2)){ if(Integer.compare(theArray.get(first1).getTotalFrequency(),theArray.get(first2).getTotalFrequency()) <= 0 ) { count++; tempArray.add(index, theArray.get(first1)); first1++; }else{ tempArray.add(index, theArray.get(first2)); first2++; } index++; } while(first1 <= last1){ tempArray.add(index, theArray.get(first1)); first1++; index++; } while(first2<=last2){ tempArray.add(index, theArray.get(first2)); first2++; index++; } for(index = first; index<=last; index++){ theArray.set(index,tempArray.get(index)); } } public void mergesort(ArrayList<Term> theArray, ArrayList<Term> tempArray, int first, int last){ if(first<last){ int mid = (first+last)/2; mergesort(theArray, tempArray, first, mid); mergesort(theArray, tempArray, mid+1, last); merge(theArray, tempArray, first, mid, last); } } }
23.241935
113
0.651631
cb49a1689cf80e4e6c6bbbbd66e947d6ed1d35d9
16,934
/** * Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET * (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije * informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE * COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp., * INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM * ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC)) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.societies.thirdpartyservices.idisaster; import android.app.AlertDialog; import android.app.ListActivity; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import org.societies.android.api.cis.SocialContract; import org.societies.thirdpartyservices.idisaster.R; /** * This activity allows the users to manage the disaster teams they own and * or the disaster teams they subscribe to. * * @author [email protected] * */ public class DisasterListActivity extends ListActivity { private ContentResolver resolver; private Cursor ownTeamCursor; // used for the teams the user owns private int ownTeams; // keep track of number of own teams private Cursor memberTeamCursor; // used for the teams the user is member of private int memberTeams; // keep track of number of member teams private ArrayAdapter<String> disasterAdapter; private ListView listView; @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView (R.layout.disaster_list_layout); listView = getListView(); resolver = getContentResolver(); if (iDisasterApplication.testDataUsed) { // Test data // The adapter should not be set in onResume since the Android Adapter // mechanism is used for update. See DisasterCreateactivity. iDisasterApplication.getInstance().disasterAdapter = new ArrayAdapter<String> (this, R.layout.disaster_list_item, R.id.disaster_item, iDisasterApplication.getInstance().disasterNameList); listView.setAdapter(iDisasterApplication.getInstance().disasterAdapter); } // Otherwise the data are fetched in onResume // Add listener for short click. listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick (AdapterView<?> parent, View view, int position, long id) { if (iDisasterApplication.testDataUsed) { // Test data iDisasterApplication.getInstance().selectedTeam.name = iDisasterApplication.getInstance().disasterNameList.get(position); iDisasterApplication.getInstance().selectedTeam.globalId = Integer.toString(position); // Store the selected disaster in application preferences // iDisasterApplication.getInstance().setDisasterTeamName (name); } else { if (position < ownTeams) { // Retrieve information from list of teams the user owns ownTeamCursor.moveToPosition(position); iDisasterApplication.getInstance().selectedTeam.name = ownTeamCursor.getString(ownTeamCursor .getColumnIndex(SocialContract.Communities.NAME)); iDisasterApplication.getInstance().selectedTeam.globalId = ownTeamCursor.getString(ownTeamCursor .getColumnIndex(SocialContract.Communities.GLOBAL_ID)); iDisasterApplication.getInstance().selectedTeam.ownFlag = true; } else if ((position-ownTeams) < memberTeams){ // Retrieve information from list of teams the user is member of memberTeamCursor.moveToPosition(position-ownTeams); iDisasterApplication.getInstance().selectedTeam.name = memberTeamCursor.getString(memberTeamCursor .getColumnIndex(SocialContract.Communities.NAME)); iDisasterApplication.getInstance().selectedTeam.globalId = memberTeamCursor.getString(memberTeamCursor .getColumnIndex(SocialContract.Communities.GLOBAL_ID)); iDisasterApplication.getInstance().selectedTeam.ownFlag = false; } } // TODO: Remove test code // Toast.makeText(getApplicationContext(), // "Click ListItem Number " + (position+1) + " " + iDisasterApplication.getInstance().selectedTeam.name, // Toast.LENGTH_LONG).show(); // Start the Disaster Activity startActivity (new Intent(DisasterListActivity.this, DisasterActivity.class)); // The activity is kept on stack (check also that "noHistory" is not set in Manifest // finish(); } }); //TODO: Add listener for long click // listView.setOnItemLongClickListener(new DrawPopup()); } // onCreate /** * onResume is called at start of the active lifetime. * The list of disaster teams is retrieved from SocialProvider and assigned to * view. * The data are fetched each time the activity becomes visible as these data * may be changed by other users (info fetched from the Cloud) */ @Override protected void onResume() { super.onResume(); // Test data are set in onCreate - see explanation above if (! iDisasterApplication.testDataUsed) { if (disasterAdapter!= null) disasterAdapter.clear(); if (getOwnDisasterTeams() // Retrieve disaster teams I am owner of .equals(iDisasterApplication.getInstance().QUERY_EXCEPTION)) { showQueryExceptionDialog (); // Exception: Display dialog and terminates activity } if (getMemberDisasterTeams() // Retrieve teams I am member of .equals(iDisasterApplication.getInstance().QUERY_EXCEPTION)) { showQueryExceptionDialog (); // Exception: Display dialog and terminates activity } assignAdapter (); // Display them } } /** * onPause releases all data. * Called when resuming a previous activity (for instance using back button) */ @Override protected void onPause() { super.onPause (); // TODO: check the following: // When using managedQuery(), the activity keeps a reference to the cursor and close it // whenever needed (in onDestroy() for instance.) // When using a contentResolver's query(), the developer has to manage the cursor as a sensitive // resource. If you forget, for instance, to close() it in onDestroy(), you will leak // underlying resources (logcat will warn you about it.) // // ownTeamCursor.close(); // memberTeamCursor.close(); } /** * getOwnDisasterTeams retrieves the list of disaster teams owned by the user * from Social Provider. */ private String getOwnDisasterTeams () { if (ownTeamCursor != null) { ownTeamCursor.close(); // "close" releases data but does not set to null ownTeamCursor = null; } Uri uri = SocialContract.Communities.CONTENT_URI; String[] projection = new String[] { SocialContract.Communities.GLOBAL_ID, // Retrieve CIS global ID SocialContract.Communities.NAME}; // Retrieve CIS name (will be displayed to the user) // All communities // String selection = null; // String[] selectionArgs = null; // TEST CODE: communities of type disaster // String selection = SocialContract.Communities.TYPE + " = disaster"; // String[] selectionArgs = null; // TEST CODE: communities I am owning // String selection = SocialContract.Communities.OWNER_ID + "= ?"; // String[] selectionArgs = new String[] {iDisasterApplication.getInstance().me.globalId}; // TODO: Add a check on user identity? String selection = SocialContract.Communities.TYPE + "= ? AND " + SocialContract.Communities.OWNER_ID + "= ?"; String[] selectionArgs = new String[] {"disaster", // The CIS type is "disaster" iDisasterApplication.getInstance().me.globalId}; // The user is owner String sortOrder = SocialContract.Communities.NAME + " COLLATE LOCALIZED ASC"; // Alphabetic order (to reverse order, use "DESC" instead of "ASC" try { ownTeamCursor = resolver.query(uri, projection, selection, selectionArgs,sortOrder); } catch (Exception e) { iDisasterApplication.getInstance().debug (2, "Query to "+ uri + "causes an exception"); return iDisasterApplication.getInstance().QUERY_EXCEPTION; } return iDisasterApplication.getInstance().QUERY_SUCCESS; } /** * getMemberDisasterTeams retrieves the list of disaster teams the user is * member of from Social Provider. */ private String getMemberDisasterTeams () { if (memberTeamCursor != null) { memberTeamCursor.close(); // "close" releases data but does not set to null memberTeamCursor = null; } // Step 1: get GLOBAL_IDs for CIS I am member of Uri membershipUri = SocialContract.Membership.CONTENT_URI; String[] membershipProjection = new String[] { SocialContract.Membership.GLOBAL_ID_COMMUNITY}; String membershipSelection = SocialContract.Membership.GLOBAL_ID_MEMBER + "= ?"; String[] membershipSelectionArgs = new String[] {iDisasterApplication.getInstance().me.globalId}; // The user is owner Cursor membershipCursor; try { membershipCursor = resolver.query(membershipUri, membershipProjection, membershipSelection, membershipSelectionArgs, null /* sortOrder*/); } catch (Exception e) { iDisasterApplication.getInstance().debug (2, "Query to "+ membershipUri + "causes an exception"); return iDisasterApplication.getInstance().QUERY_EXCEPTION; } // Step 2: retrieve the communities with the GLOBAL_IDs retrieved above if (membershipCursor == null) { // No cursor was set iDisasterApplication.getInstance().debug (2, "No information can be retrieved in membershipCursor"); return iDisasterApplication.getInstance().QUERY_EMPTY; } if (membershipCursor.getCount() == 0) { // The user is not member of any community return iDisasterApplication.getInstance().QUERY_EMPTY; } // Get GLOBAL_ID and NAME for CIS I am member of Uri communitiesUri = SocialContract.Communities.CONTENT_URI; String[] communitiesProjection = new String[] { SocialContract.Communities.GLOBAL_ID, SocialContract.Communities.NAME}; // Build selection string and selectionArgs string boolean first = true; String communitiesSelection = new String(); ArrayList <String> communitiesSelectionArgs = new ArrayList <String> (); while (membershipCursor.moveToNext()) { if (first) { first = false; communitiesSelection = SocialContract.Communities.GLOBAL_ID + "= ?"; communitiesSelectionArgs.add (membershipCursor.getString( (membershipCursor.getColumnIndex(SocialContract.Membership.GLOBAL_ID_COMMUNITY)))); } else { communitiesSelection = communitiesSelection + " AND " + SocialContract.Communities.GLOBAL_ID + "= ?"; communitiesSelectionArgs.add (membershipCursor.getString( (membershipCursor.getColumnIndex(SocialContract.Membership.GLOBAL_ID_COMMUNITY)))); } } membershipCursor.close(); // "close" releases no more needed data //TODO: not sure the current cursor, if any, should be close first try { memberTeamCursor = resolver.query (communitiesUri, communitiesProjection, communitiesSelection, communitiesSelectionArgs.toArray(new String[communitiesSelectionArgs.size()]), null /* sortOrder*/); } catch (Exception e) { iDisasterApplication.getInstance().debug (2, "Query to "+ membershipUri + "causes an exception"); return iDisasterApplication.getInstance().QUERY_EXCEPTION; } return iDisasterApplication.getInstance().QUERY_SUCCESS; // // When using managedQuery(), the activity keeps a reference to the cursor and close it // whenever needed (in onDestroy() for instance.) // When using a contentResolver's query(), the developer has to manage the cursor as a sensitive // resource. If you forget, for instance, to close() it in onDestroy(), you will leak // underlying resources (logcat will warn you about it.) // } /** * assignAdapter assigns data to display to adapter and adapter to view. */ private void assignAdapter () { ownTeams= 0; memberTeams= 0; ArrayList<String> disasterList = new ArrayList<String> (); // An empty List will be assigned to Adapter // if ((ownTeamCursor == null) && (memberTeamCursor == null)) { // An empty List will be assigned to Adapter // if ((ownTeamCursor != null) && (memberTeamCursor != null)) { // if ((ownTeamCursor.getCount() == 0) && (memberTeamCursor.getCount() == 0)) { if (ownTeamCursor != null) { if (ownTeamCursor.getCount() != 0) { while (ownTeamCursor.moveToNext()) { ownTeams++; String displayName = "owned: " + ownTeamCursor.getString(ownTeamCursor .getColumnIndex(SocialContract.Communities.NAME)); disasterList.add (displayName); } } } if (memberTeamCursor != null) { if (memberTeamCursor.getCount() != 0) { while (memberTeamCursor.moveToNext()) { memberTeams++; String displayName = "member of: " + memberTeamCursor.getString(memberTeamCursor .getColumnIndex(SocialContract.Communities.NAME)); disasterList.add (displayName); } } } disasterAdapter = new ArrayAdapter<String> (this, R.layout.disaster_list_item, R.id.disaster_item, disasterList); listView.setAdapter(disasterAdapter); } /** * onCreateOptionsMenu creates the activity menu. */ @Override public boolean onCreateOptionsMenu(Menu menu){ menu.clear(); getMenuInflater().inflate(R.menu.disaster_list_menu, menu); // It is possible to set up a variable menu // menu.findItem (R.id....).setVisible(true); return true; } /** * onOptionsItemSelected handles the selection of an item in the activity menu. */ @Override public boolean onOptionsItemSelected (MenuItem item) { switch (item.getItemId()) { case R.id.disasterMenuAdd: startActivity(new Intent(DisasterListActivity.this, DisasterCreateActivity.class)); break; default: break; } return true; } /** * showQueryExceptionDialog displays a dialog to the user and terminates activity. */ private void showQueryExceptionDialog () { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.setMessage(getString(R.string.dialogQueryException)) .setCancelable(false) .setPositiveButton (getString(R.string.dialogOK), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // add termination code code eventually finish (); return; } }); AlertDialog alert = alertBuilder.create(); alert.show(); } }
40.223278
131
0.703319
3b037b83233b6a3ce7e2ed2d7f3050e2b2fac828
17,408
package net.honarnama.sell.activity; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import net.honarnama.GRPCUtils; import net.honarnama.HonarnamaBaseApp; import net.honarnama.base.BuildConfig; import net.honarnama.base.utils.GravityTextWatcher; import net.honarnama.base.utils.NetworkManager; import net.honarnama.base.utils.WindowUtil; import net.honarnama.nano.AuthServiceGrpc; import net.honarnama.nano.ReplyProperties; import net.honarnama.nano.RequestProperties; import net.honarnama.nano.SendLoginEmailReply; import net.honarnama.nano.SendLoginEmailRequest; import net.honarnama.nano.SimpleRequest; import net.honarnama.nano.WhoAmIReply; import net.honarnama.sell.HonarnamaSellApp; import net.honarnama.sell.R; import net.honarnama.sell.model.HonarnamaUser; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import io.fabric.sdk.android.services.concurrency.AsyncTask; public class LoginActivity extends HonarnamaSellActivity implements View.OnClickListener { private Button mRegisterAsSellerBtn; private Button mLoginButton; private EditText mUsernameEditText; ProgressDialog mProgressDialog; Snackbar mSnackbar; private Tracker mTracker; private CoordinatorLayout mCoordinatorLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTracker = HonarnamaSellApp.getInstance().getDefaultTracker(); mTracker.setScreenName("LoginActivity"); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); setContentView(R.layout.activity_login); mRegisterAsSellerBtn = (Button) findViewById(R.id.register_as_seller_btn); mRegisterAsSellerBtn.setOnClickListener(this); mLoginButton = (Button) findViewById(R.id.send_login_link_btn); mLoginButton.setOnClickListener(this); mUsernameEditText = (EditText) findViewById(R.id.login_username_edit_text); mUsernameEditText.addTextChangedListener(new GravityTextWatcher(mUsernameEditText)); mCoordinatorLayout = (CoordinatorLayout) findViewById(R.id .coordinatorLayout); if (HonarnamaUser.isLoggedIn()) { new getMeAsyncTask().execute(); } else { processIntent(getIntent()); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); processIntent(intent); } private void processIntent(Intent intent) { Uri data = intent.getData(); if (BuildConfig.DEBUG) { logD("processIntent :: data= " + data); } if (data != null) { final String loginToken = data.getQueryParameter("token"); //login with email final String register = data.getQueryParameter("register"); if (BuildConfig.DEBUG) { logD("token= " + loginToken + ", register= " + register); } if (loginToken != null && loginToken.length() > 0) { HonarnamaUser.login(loginToken); if (BuildConfig.DEBUG) { logD("getUserInfo (Calling getMeAsyncTask...)"); } if (!NetworkManager.getInstance().isNetworkEnabled(true)) { return; } else { new getMeAsyncTask().execute(); } } else if ("true".equals(register)) { Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class); startActivityForResult(registerIntent, HonarnamaBaseApp.INTENT_REGISTER_CODE); } } } @Override protected void onResume() { super.onResume(); WindowUtil.hideKeyboard(LoginActivity.this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.register_as_seller_btn: Intent intent = new Intent(LoginActivity.this, RegisterActivity.class); startActivityForResult(intent, HonarnamaBaseApp.INTENT_REGISTER_CODE); break; case R.id.send_login_link_btn: if (formInputsAreValid()) { new SendLoginEmailAsync().execute(); } break; default: break; } } @Override protected void onDestroy() { super.onDestroy(); dismissProgressDialog(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (BuildConfig.DEBUG) { logD("onActivityResult of LA // resultCode: " + resultCode); logD("onActivityResult of LA // requestCode: " + requestCode); } if (resultCode == Activity.RESULT_OK) { if (requestCode == HonarnamaBaseApp.INTENT_REGISTER_CODE) { if (intent.hasExtra(HonarnamaBaseApp.EXTRA_KEY_DISPLAY_REGISTER_SNACK_FOR_EMAIL)) { if (intent.getBooleanExtra(HonarnamaBaseApp.EXTRA_KEY_DISPLAY_REGISTER_SNACK_FOR_EMAIL, false)) { displayCustomSnackbar(getString(R.string.verification_email_sent), false); clearErrors(); } } } else { if (BuildConfig.DEBUG) { logD("Hide register message notif."); } } } super.onActivityResult(requestCode, resultCode, intent); } public class getMeAsyncTask extends AsyncTask<Void, Void, WhoAmIReply> { SimpleRequest simpleRequest; @Override protected void onPreExecute() { super.onPreExecute(); displayProgressDialog(); } @Override protected WhoAmIReply doInBackground(Void... voids) { RequestProperties rp = GRPCUtils.newRPWithDeviceInfo(); simpleRequest = new SimpleRequest(); simpleRequest.requestProperties = rp; if (BuildConfig.DEBUG) { logD("Running WhoAmI request to log user in. simpleRequest: " + simpleRequest); } WhoAmIReply whoAmIReply; try { AuthServiceGrpc.AuthServiceBlockingStub stub = GRPCUtils.getInstance().getAuthServiceGrpc(); whoAmIReply = stub.whoAmI(simpleRequest); return whoAmIReply; } catch (Exception e) { logE("Error getting whoAmIReply. simpleRequest: " + simpleRequest + ". Error: " + e, e); } return null; } @Override protected void onPostExecute(WhoAmIReply whoAmIReply) { super.onPostExecute(whoAmIReply); if (BuildConfig.DEBUG) { logD("whoAmIReply: " + whoAmIReply); } dismissProgressDialog(); if (whoAmIReply != null) { switch (whoAmIReply.replyProperties.statusCode) { case ReplyProperties.CLIENT_ERROR: logE("Got CLIENT_ERROR for whoAmIReply. whoAmIReply: " + whoAmIReply + ". simpleRequest was: " + simpleRequest); Toast.makeText(LoginActivity.this, getString(R.string.error_getting_info), Toast.LENGTH_LONG).show(); break; case ReplyProperties.SERVER_ERROR: displayCustomSnackbar(getString(R.string.server_error_try_again), true); logE("Got SERVER_ERROR for whoAmIReply. whoAmIReply: " + whoAmIReply + ". request: " + simpleRequest); break; case ReplyProperties.NOT_AUTHORIZED: //TODO (1:Login link expired or 2: 24 user deleted and user got deleted) if (BuildConfig.DEBUG) { logD("Got NOT_AUTHORIZED reply in reply to WhoAmI request."); } Toast.makeText(LoginActivity.this, getString(R.string.account_not_found) + " یا اعتبار لینک ورود منقضی شده است.", Toast.LENGTH_LONG).show(); HonarnamaUser.logout(null); displayCustomSnackbar("در صورتی که حسابتان را قبلا فعال کرده بودید، می‌توانید از طریق فرم بالا، درخواست لینک ورود جدید کنید.", false); break; case ReplyProperties.OK: HonarnamaUser.setName(whoAmIReply.account.name); HonarnamaUser.setGender(whoAmIReply.account.gender); goToControlPanel(); break; case ReplyProperties.UPGRADE_REQUIRED: displayUpgradeRequiredDialog(); HonarnamaUser.logout(null); break; } long serverMetaVersion = whoAmIReply.replyProperties.latestMetaETag; checkAndUpdateMeta(false, serverMetaVersion); } else { displayCustomSnackbar(getString(R.string.error_connecting_server_try_again), true); } } } public void goToControlPanel() { Intent intent = new Intent(LoginActivity.this, ControlPanelActivity.class); startActivity(intent); finish(); } private void dismissProgressDialog() { if (!LoginActivity.this.isFinishing()) { if (mProgressDialog != null && mProgressDialog.isShowing()) { try { mProgressDialog.dismiss(); } catch (Exception ex) { } } } } private void displayProgressDialog() { dismissProgressDialog(); mProgressDialog = new ProgressDialog(LoginActivity.this); mProgressDialog.setCancelable(false); mProgressDialog.setMessage(getString(R.string.please_wait)); if (!LoginActivity.this.isFinishing() && !mProgressDialog.isShowing()) { mProgressDialog.show(); } } public void displayCustomSnackbar(String text, Boolean displayGetMeRefreshBtn) { if (mSnackbar != null && mSnackbar.isShown()) { mSnackbar.dismiss(); } mSnackbar = Snackbar.make(mCoordinatorLayout, "", Snackbar.LENGTH_INDEFINITE); Snackbar.SnackbarLayout snackbarLayout = (Snackbar.SnackbarLayout) mSnackbar.getView(); TextView textView = (TextView) snackbarLayout.findViewById(android.support.design.R.id.snackbar_text); textView.setVisibility(View.INVISIBLE); View snackView = getLayoutInflater().inflate(R.layout.snackbar, null); TextView textViewTop = (TextView) snackView.findViewById(R.id.snack_text); textViewTop.setText(text); ImageButton imageBtn = (ImageButton) snackView.findViewById(R.id.snack_action); if (displayGetMeRefreshBtn) { imageBtn.setVisibility(View.VISIBLE); imageBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (NetworkManager.getInstance().isNetworkEnabled(true)) { new getMeAsyncTask().execute(); } } }); } else { imageBtn.setVisibility(View.GONE); } snackbarLayout.setBackgroundColor(getResources().getColor(R.color.amber)); snackbarLayout.addView(snackView, 0); mSnackbar.show(); } public void clearErrors() { mUsernameEditText.setError(null); } private boolean formInputsAreValid() { clearErrors(); if (mUsernameEditText.getText().toString().trim().length() == 0) { mUsernameEditText.requestFocus(); mUsernameEditText.setError(getString(R.string.error_email_not_set)); Toast.makeText(LoginActivity.this, getString(R.string.error_email_not_set), Toast.LENGTH_LONG).show(); return false; } if (!(android.util.Patterns.EMAIL_ADDRESS.matcher(mUsernameEditText.getText().toString().trim()).matches())) { mUsernameEditText.requestFocus(); mUsernameEditText.setError(getString(R.string.error_email_address_is_not_valid)); Toast.makeText(LoginActivity.this, getString(R.string.error_email_address_is_not_valid), Toast.LENGTH_LONG).show(); return false; } return true; } public class SendLoginEmailAsync extends AsyncTask<Void, Void, SendLoginEmailReply> { String cEmail = ""; SendLoginEmailRequest sendLoginEmailRequest; @Override protected void onPreExecute() { super.onPreExecute(); displayProgressDialog(); } @Override protected SendLoginEmailReply doInBackground(Void... voids) { sendLoginEmailRequest = new SendLoginEmailRequest(); sendLoginEmailRequest.email = mUsernameEditText.getText().toString().trim(); RequestProperties rp = GRPCUtils.newRPWithDeviceInfo(); sendLoginEmailRequest.requestProperties = rp; if (BuildConfig.DEBUG) { logD("sendLoginEmailRequest: " + sendLoginEmailRequest); } AuthServiceGrpc.AuthServiceBlockingStub stub; try { stub = GRPCUtils.getInstance().getAuthServiceGrpc(); SendLoginEmailReply sendLoginEmailReply = stub.sendLoginEmail(sendLoginEmailRequest); return sendLoginEmailReply; } catch (Exception e) { logE("Error trying to send login email request. sendLoginEmailRequest: " + sendLoginEmailRequest + ". Error: " + e, e); } return null; } @Override protected void onPostExecute(SendLoginEmailReply sendLoginEmailReply) { super.onPostExecute(sendLoginEmailReply); dismissProgressDialog(); if (BuildConfig.DEBUG) { logD("sendLoginEmailReply is: " + sendLoginEmailReply); } if (sendLoginEmailReply != null) { switch (sendLoginEmailReply.replyProperties.statusCode) { case ReplyProperties.CLIENT_ERROR: switch (sendLoginEmailReply.errorCode) { case SendLoginEmailReply.ACCOUNT_NOT_FOUND: mUsernameEditText.setError(getString(R.string.no_user_found_matching_email)); Toast.makeText(LoginActivity.this, getString(R.string.no_user_found_matching_email), Toast.LENGTH_LONG).show(); break; case SendLoginEmailReply.INVALID_EMAIL: mUsernameEditText.setError(getString(R.string.error_email_address_is_not_valid)); Toast.makeText(LoginActivity.this, getString(R.string.error_email_address_is_not_valid), Toast.LENGTH_LONG).show(); break; case SendLoginEmailReply.NO_CLIENT_ERROR: logE("Got NO_CLIENT_ERROR code for registering user. sendLoginEmailReply: " + sendLoginEmailReply + ". sendLoginEmailRequest: " + sendLoginEmailRequest); Toast.makeText(LoginActivity.this, getString(R.string.error_getting_info), Toast.LENGTH_LONG).show(); break; } // logE("Sign-up Failed. errorCode: " + sendLoginEmailReply.errorCode + // " // statusCode: " + sendLoginEmailReply.replyProperties.statusCode + // " // Error Msg: " + sendLoginEmailReply.replyProperties.errorMessage); break; case ReplyProperties.SERVER_ERROR: Toast.makeText(LoginActivity.this, getString(R.string.server_error_try_again), Toast.LENGTH_SHORT).show(); logE("Server error running send login request. request: " + sendLoginEmailRequest); break; case ReplyProperties.NOT_AUTHORIZED: HonarnamaUser.logout(LoginActivity.this); break; case ReplyProperties.OK: displayCustomSnackbar(getString(R.string.login_email_sent), false); break; case ReplyProperties.UPGRADE_REQUIRED: displayUpgradeRequiredDialog(); break; } } else { Toast.makeText(LoginActivity.this, getString(R.string.error_connecting_server_try_again), Toast.LENGTH_LONG).show(); } } } @Override protected void onStop() { super.onStop(); dismissProgressDialog(); } }
40.672897
185
0.605182
d5e9d8441689e27f48d196ad5d5d983bb6102a3e
114,376
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: WAL.proto package org.apache.hadoop.hbase.protobuf.generated; public final class WALProtos { private WALProtos() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public enum ScopeType implements com.google.protobuf.ProtocolMessageEnum { REPLICATION_SCOPE_LOCAL(0, 0), REPLICATION_SCOPE_GLOBAL(1, 1), ; public static final int REPLICATION_SCOPE_LOCAL_VALUE = 0; public static final int REPLICATION_SCOPE_GLOBAL_VALUE = 1; public final int getNumber() { return value; } public static ScopeType valueOf(int value) { switch (value) { case 0: return REPLICATION_SCOPE_LOCAL; case 1: return REPLICATION_SCOPE_GLOBAL; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<ScopeType> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<ScopeType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<ScopeType>() { public ScopeType findValueByNumber(int number) { return ScopeType.valueOf(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(index); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.getDescriptor().getEnumTypes().get(0); } private static final ScopeType[] VALUES = { REPLICATION_SCOPE_LOCAL, REPLICATION_SCOPE_GLOBAL, }; public static ScopeType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int index; private final int value; private ScopeType(int index, int value) { this.index = index; this.value = value; } // @@protoc_insertion_point(enum_scope:ScopeType) } public interface WALHeaderOrBuilder extends com.google.protobuf.MessageOrBuilder { // optional bool hasCompression = 1; boolean hasHasCompression(); boolean getHasCompression(); } public static final class WALHeader extends com.google.protobuf.GeneratedMessage implements WALHeaderOrBuilder { // Use WALHeader.newBuilder() to construct. private WALHeader(Builder builder) { super(builder); } private WALHeader(boolean noInit) {} private static final WALHeader defaultInstance; public static WALHeader getDefaultInstance() { return defaultInstance; } public WALHeader getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_WALHeader_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_WALHeader_fieldAccessorTable; } private int bitField0_; // optional bool hasCompression = 1; public static final int HASCOMPRESSION_FIELD_NUMBER = 1; private boolean hasCompression_; public boolean hasHasCompression() { return ((bitField0_ & 0x00000001) == 0x00000001); } public boolean getHasCompression() { return hasCompression_; } private void initFields() { hasCompression_ = false; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBool(1, hasCompression_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(1, hasCompression_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader)) { return super.equals(obj); } org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader other = (org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader) obj; boolean result = true; result = result && (hasHasCompression() == other.hasHasCompression()); if (hasHasCompression()) { result = result && (getHasCompression() == other.getHasCompression()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasHasCompression()) { hash = (37 * hash) + HASCOMPRESSION_FIELD_NUMBER; hash = (53 * hash) + hashBoolean(getHasCompression()); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeaderOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_WALHeader_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_WALHeader_fieldAccessorTable; } // Construct using org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); hasCompression_ = false; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader.getDescriptor(); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader getDefaultInstanceForType() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader.getDefaultInstance(); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader build() { org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader buildPartial() { org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader result = new org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.hasCompression_ = hasCompression_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader) { return mergeFrom((org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader other) { if (other == org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader.getDefaultInstance()) return this; if (other.hasHasCompression()) { setHasCompression(other.getHasCompression()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 8: { bitField0_ |= 0x00000001; hasCompression_ = input.readBool(); break; } } } } private int bitField0_; // optional bool hasCompression = 1; private boolean hasCompression_ ; public boolean hasHasCompression() { return ((bitField0_ & 0x00000001) == 0x00000001); } public boolean getHasCompression() { return hasCompression_; } public Builder setHasCompression(boolean value) { bitField0_ |= 0x00000001; hasCompression_ = value; onChanged(); return this; } public Builder clearHasCompression() { bitField0_ = (bitField0_ & ~0x00000001); hasCompression_ = false; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:WALHeader) } static { defaultInstance = new WALHeader(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:WALHeader) } public interface WALKeyOrBuilder extends com.google.protobuf.MessageOrBuilder { // required bytes encodedRegionName = 1; boolean hasEncodedRegionName(); com.google.protobuf.ByteString getEncodedRegionName(); // required bytes tableName = 2; boolean hasTableName(); com.google.protobuf.ByteString getTableName(); // required uint64 logSequenceNumber = 3; boolean hasLogSequenceNumber(); long getLogSequenceNumber(); // required uint64 writeTime = 4; boolean hasWriteTime(); long getWriteTime(); // optional .UUID clusterId = 5; boolean hasClusterId(); org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID getClusterId(); org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUIDOrBuilder getClusterIdOrBuilder(); // repeated .FamilyScope scopes = 6; java.util.List<org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope> getScopesList(); org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope getScopes(int index); int getScopesCount(); java.util.List<? extends org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScopeOrBuilder> getScopesOrBuilderList(); org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScopeOrBuilder getScopesOrBuilder( int index); // optional uint32 followingKvCount = 7; boolean hasFollowingKvCount(); int getFollowingKvCount(); } public static final class WALKey extends com.google.protobuf.GeneratedMessage implements WALKeyOrBuilder { // Use WALKey.newBuilder() to construct. private WALKey(Builder builder) { super(builder); } private WALKey(boolean noInit) {} private static final WALKey defaultInstance; public static WALKey getDefaultInstance() { return defaultInstance; } public WALKey getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_WALKey_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_WALKey_fieldAccessorTable; } private int bitField0_; // required bytes encodedRegionName = 1; public static final int ENCODEDREGIONNAME_FIELD_NUMBER = 1; private com.google.protobuf.ByteString encodedRegionName_; public boolean hasEncodedRegionName() { return ((bitField0_ & 0x00000001) == 0x00000001); } public com.google.protobuf.ByteString getEncodedRegionName() { return encodedRegionName_; } // required bytes tableName = 2; public static final int TABLENAME_FIELD_NUMBER = 2; private com.google.protobuf.ByteString tableName_; public boolean hasTableName() { return ((bitField0_ & 0x00000002) == 0x00000002); } public com.google.protobuf.ByteString getTableName() { return tableName_; } // required uint64 logSequenceNumber = 3; public static final int LOGSEQUENCENUMBER_FIELD_NUMBER = 3; private long logSequenceNumber_; public boolean hasLogSequenceNumber() { return ((bitField0_ & 0x00000004) == 0x00000004); } public long getLogSequenceNumber() { return logSequenceNumber_; } // required uint64 writeTime = 4; public static final int WRITETIME_FIELD_NUMBER = 4; private long writeTime_; public boolean hasWriteTime() { return ((bitField0_ & 0x00000008) == 0x00000008); } public long getWriteTime() { return writeTime_; } // optional .UUID clusterId = 5; public static final int CLUSTERID_FIELD_NUMBER = 5; private org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID clusterId_; public boolean hasClusterId() { return ((bitField0_ & 0x00000010) == 0x00000010); } public org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID getClusterId() { return clusterId_; } public org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUIDOrBuilder getClusterIdOrBuilder() { return clusterId_; } // repeated .FamilyScope scopes = 6; public static final int SCOPES_FIELD_NUMBER = 6; private java.util.List<org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope> scopes_; public java.util.List<org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope> getScopesList() { return scopes_; } public java.util.List<? extends org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScopeOrBuilder> getScopesOrBuilderList() { return scopes_; } public int getScopesCount() { return scopes_.size(); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope getScopes(int index) { return scopes_.get(index); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScopeOrBuilder getScopesOrBuilder( int index) { return scopes_.get(index); } // optional uint32 followingKvCount = 7; public static final int FOLLOWINGKVCOUNT_FIELD_NUMBER = 7; private int followingKvCount_; public boolean hasFollowingKvCount() { return ((bitField0_ & 0x00000020) == 0x00000020); } public int getFollowingKvCount() { return followingKvCount_; } private void initFields() { encodedRegionName_ = com.google.protobuf.ByteString.EMPTY; tableName_ = com.google.protobuf.ByteString.EMPTY; logSequenceNumber_ = 0L; writeTime_ = 0L; clusterId_ = org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.getDefaultInstance(); scopes_ = java.util.Collections.emptyList(); followingKvCount_ = 0; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasEncodedRegionName()) { memoizedIsInitialized = 0; return false; } if (!hasTableName()) { memoizedIsInitialized = 0; return false; } if (!hasLogSequenceNumber()) { memoizedIsInitialized = 0; return false; } if (!hasWriteTime()) { memoizedIsInitialized = 0; return false; } if (hasClusterId()) { if (!getClusterId().isInitialized()) { memoizedIsInitialized = 0; return false; } } for (int i = 0; i < getScopesCount(); i++) { if (!getScopes(i).isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, encodedRegionName_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, tableName_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeUInt64(3, logSequenceNumber_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeUInt64(4, writeTime_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeMessage(5, clusterId_); } for (int i = 0; i < scopes_.size(); i++) { output.writeMessage(6, scopes_.get(i)); } if (((bitField0_ & 0x00000020) == 0x00000020)) { output.writeUInt32(7, followingKvCount_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, encodedRegionName_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, tableName_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(3, logSequenceNumber_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, writeTime_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, clusterId_); } for (int i = 0; i < scopes_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(6, scopes_.get(i)); } if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(7, followingKvCount_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey)) { return super.equals(obj); } org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey other = (org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey) obj; boolean result = true; result = result && (hasEncodedRegionName() == other.hasEncodedRegionName()); if (hasEncodedRegionName()) { result = result && getEncodedRegionName() .equals(other.getEncodedRegionName()); } result = result && (hasTableName() == other.hasTableName()); if (hasTableName()) { result = result && getTableName() .equals(other.getTableName()); } result = result && (hasLogSequenceNumber() == other.hasLogSequenceNumber()); if (hasLogSequenceNumber()) { result = result && (getLogSequenceNumber() == other.getLogSequenceNumber()); } result = result && (hasWriteTime() == other.hasWriteTime()); if (hasWriteTime()) { result = result && (getWriteTime() == other.getWriteTime()); } result = result && (hasClusterId() == other.hasClusterId()); if (hasClusterId()) { result = result && getClusterId() .equals(other.getClusterId()); } result = result && getScopesList() .equals(other.getScopesList()); result = result && (hasFollowingKvCount() == other.hasFollowingKvCount()); if (hasFollowingKvCount()) { result = result && (getFollowingKvCount() == other.getFollowingKvCount()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasEncodedRegionName()) { hash = (37 * hash) + ENCODEDREGIONNAME_FIELD_NUMBER; hash = (53 * hash) + getEncodedRegionName().hashCode(); } if (hasTableName()) { hash = (37 * hash) + TABLENAME_FIELD_NUMBER; hash = (53 * hash) + getTableName().hashCode(); } if (hasLogSequenceNumber()) { hash = (37 * hash) + LOGSEQUENCENUMBER_FIELD_NUMBER; hash = (53 * hash) + hashLong(getLogSequenceNumber()); } if (hasWriteTime()) { hash = (37 * hash) + WRITETIME_FIELD_NUMBER; hash = (53 * hash) + hashLong(getWriteTime()); } if (hasClusterId()) { hash = (37 * hash) + CLUSTERID_FIELD_NUMBER; hash = (53 * hash) + getClusterId().hashCode(); } if (getScopesCount() > 0) { hash = (37 * hash) + SCOPES_FIELD_NUMBER; hash = (53 * hash) + getScopesList().hashCode(); } if (hasFollowingKvCount()) { hash = (37 * hash) + FOLLOWINGKVCOUNT_FIELD_NUMBER; hash = (53 * hash) + getFollowingKvCount(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKeyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_WALKey_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_WALKey_fieldAccessorTable; } // Construct using org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getClusterIdFieldBuilder(); getScopesFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); encodedRegionName_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); tableName_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); logSequenceNumber_ = 0L; bitField0_ = (bitField0_ & ~0x00000004); writeTime_ = 0L; bitField0_ = (bitField0_ & ~0x00000008); if (clusterIdBuilder_ == null) { clusterId_ = org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.getDefaultInstance(); } else { clusterIdBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000010); if (scopesBuilder_ == null) { scopes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { scopesBuilder_.clear(); } followingKvCount_ = 0; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey.getDescriptor(); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey getDefaultInstanceForType() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey.getDefaultInstance(); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey build() { org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey buildPartial() { org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey result = new org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.encodedRegionName_ = encodedRegionName_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.tableName_ = tableName_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.logSequenceNumber_ = logSequenceNumber_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.writeTime_ = writeTime_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } if (clusterIdBuilder_ == null) { result.clusterId_ = clusterId_; } else { result.clusterId_ = clusterIdBuilder_.build(); } if (scopesBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { scopes_ = java.util.Collections.unmodifiableList(scopes_); bitField0_ = (bitField0_ & ~0x00000020); } result.scopes_ = scopes_; } else { result.scopes_ = scopesBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000020; } result.followingKvCount_ = followingKvCount_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey) { return mergeFrom((org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey other) { if (other == org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey.getDefaultInstance()) return this; if (other.hasEncodedRegionName()) { setEncodedRegionName(other.getEncodedRegionName()); } if (other.hasTableName()) { setTableName(other.getTableName()); } if (other.hasLogSequenceNumber()) { setLogSequenceNumber(other.getLogSequenceNumber()); } if (other.hasWriteTime()) { setWriteTime(other.getWriteTime()); } if (other.hasClusterId()) { mergeClusterId(other.getClusterId()); } if (scopesBuilder_ == null) { if (!other.scopes_.isEmpty()) { if (scopes_.isEmpty()) { scopes_ = other.scopes_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensureScopesIsMutable(); scopes_.addAll(other.scopes_); } onChanged(); } } else { if (!other.scopes_.isEmpty()) { if (scopesBuilder_.isEmpty()) { scopesBuilder_.dispose(); scopesBuilder_ = null; scopes_ = other.scopes_; bitField0_ = (bitField0_ & ~0x00000020); scopesBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getScopesFieldBuilder() : null; } else { scopesBuilder_.addAllMessages(other.scopes_); } } } if (other.hasFollowingKvCount()) { setFollowingKvCount(other.getFollowingKvCount()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasEncodedRegionName()) { return false; } if (!hasTableName()) { return false; } if (!hasLogSequenceNumber()) { return false; } if (!hasWriteTime()) { return false; } if (hasClusterId()) { if (!getClusterId().isInitialized()) { return false; } } for (int i = 0; i < getScopesCount(); i++) { if (!getScopes(i).isInitialized()) { return false; } } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { bitField0_ |= 0x00000001; encodedRegionName_ = input.readBytes(); break; } case 18: { bitField0_ |= 0x00000002; tableName_ = input.readBytes(); break; } case 24: { bitField0_ |= 0x00000004; logSequenceNumber_ = input.readUInt64(); break; } case 32: { bitField0_ |= 0x00000008; writeTime_ = input.readUInt64(); break; } case 42: { org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.Builder subBuilder = org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.newBuilder(); if (hasClusterId()) { subBuilder.mergeFrom(getClusterId()); } input.readMessage(subBuilder, extensionRegistry); setClusterId(subBuilder.buildPartial()); break; } case 50: { org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder subBuilder = org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.newBuilder(); input.readMessage(subBuilder, extensionRegistry); addScopes(subBuilder.buildPartial()); break; } case 56: { bitField0_ |= 0x00000040; followingKvCount_ = input.readUInt32(); break; } } } } private int bitField0_; // required bytes encodedRegionName = 1; private com.google.protobuf.ByteString encodedRegionName_ = com.google.protobuf.ByteString.EMPTY; public boolean hasEncodedRegionName() { return ((bitField0_ & 0x00000001) == 0x00000001); } public com.google.protobuf.ByteString getEncodedRegionName() { return encodedRegionName_; } public Builder setEncodedRegionName(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; encodedRegionName_ = value; onChanged(); return this; } public Builder clearEncodedRegionName() { bitField0_ = (bitField0_ & ~0x00000001); encodedRegionName_ = getDefaultInstance().getEncodedRegionName(); onChanged(); return this; } // required bytes tableName = 2; private com.google.protobuf.ByteString tableName_ = com.google.protobuf.ByteString.EMPTY; public boolean hasTableName() { return ((bitField0_ & 0x00000002) == 0x00000002); } public com.google.protobuf.ByteString getTableName() { return tableName_; } public Builder setTableName(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; tableName_ = value; onChanged(); return this; } public Builder clearTableName() { bitField0_ = (bitField0_ & ~0x00000002); tableName_ = getDefaultInstance().getTableName(); onChanged(); return this; } // required uint64 logSequenceNumber = 3; private long logSequenceNumber_ ; public boolean hasLogSequenceNumber() { return ((bitField0_ & 0x00000004) == 0x00000004); } public long getLogSequenceNumber() { return logSequenceNumber_; } public Builder setLogSequenceNumber(long value) { bitField0_ |= 0x00000004; logSequenceNumber_ = value; onChanged(); return this; } public Builder clearLogSequenceNumber() { bitField0_ = (bitField0_ & ~0x00000004); logSequenceNumber_ = 0L; onChanged(); return this; } // required uint64 writeTime = 4; private long writeTime_ ; public boolean hasWriteTime() { return ((bitField0_ & 0x00000008) == 0x00000008); } public long getWriteTime() { return writeTime_; } public Builder setWriteTime(long value) { bitField0_ |= 0x00000008; writeTime_ = value; onChanged(); return this; } public Builder clearWriteTime() { bitField0_ = (bitField0_ & ~0x00000008); writeTime_ = 0L; onChanged(); return this; } // optional .UUID clusterId = 5; private org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID clusterId_ = org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID, org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.Builder, org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUIDOrBuilder> clusterIdBuilder_; public boolean hasClusterId() { return ((bitField0_ & 0x00000010) == 0x00000010); } public org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID getClusterId() { if (clusterIdBuilder_ == null) { return clusterId_; } else { return clusterIdBuilder_.getMessage(); } } public Builder setClusterId(org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID value) { if (clusterIdBuilder_ == null) { if (value == null) { throw new NullPointerException(); } clusterId_ = value; onChanged(); } else { clusterIdBuilder_.setMessage(value); } bitField0_ |= 0x00000010; return this; } public Builder setClusterId( org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.Builder builderForValue) { if (clusterIdBuilder_ == null) { clusterId_ = builderForValue.build(); onChanged(); } else { clusterIdBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000010; return this; } public Builder mergeClusterId(org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID value) { if (clusterIdBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010) && clusterId_ != org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.getDefaultInstance()) { clusterId_ = org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.newBuilder(clusterId_).mergeFrom(value).buildPartial(); } else { clusterId_ = value; } onChanged(); } else { clusterIdBuilder_.mergeFrom(value); } bitField0_ |= 0x00000010; return this; } public Builder clearClusterId() { if (clusterIdBuilder_ == null) { clusterId_ = org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.getDefaultInstance(); onChanged(); } else { clusterIdBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000010); return this; } public org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.Builder getClusterIdBuilder() { bitField0_ |= 0x00000010; onChanged(); return getClusterIdFieldBuilder().getBuilder(); } public org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUIDOrBuilder getClusterIdOrBuilder() { if (clusterIdBuilder_ != null) { return clusterIdBuilder_.getMessageOrBuilder(); } else { return clusterId_; } } private com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID, org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.Builder, org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUIDOrBuilder> getClusterIdFieldBuilder() { if (clusterIdBuilder_ == null) { clusterIdBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID, org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUID.Builder, org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.UUIDOrBuilder>( clusterId_, getParentForChildren(), isClean()); clusterId_ = null; } return clusterIdBuilder_; } // repeated .FamilyScope scopes = 6; private java.util.List<org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope> scopes_ = java.util.Collections.emptyList(); private void ensureScopesIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { scopes_ = new java.util.ArrayList<org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope>(scopes_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScopeOrBuilder> scopesBuilder_; public java.util.List<org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope> getScopesList() { if (scopesBuilder_ == null) { return java.util.Collections.unmodifiableList(scopes_); } else { return scopesBuilder_.getMessageList(); } } public int getScopesCount() { if (scopesBuilder_ == null) { return scopes_.size(); } else { return scopesBuilder_.getCount(); } } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope getScopes(int index) { if (scopesBuilder_ == null) { return scopes_.get(index); } else { return scopesBuilder_.getMessage(index); } } public Builder setScopes( int index, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope value) { if (scopesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureScopesIsMutable(); scopes_.set(index, value); onChanged(); } else { scopesBuilder_.setMessage(index, value); } return this; } public Builder setScopes( int index, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder builderForValue) { if (scopesBuilder_ == null) { ensureScopesIsMutable(); scopes_.set(index, builderForValue.build()); onChanged(); } else { scopesBuilder_.setMessage(index, builderForValue.build()); } return this; } public Builder addScopes(org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope value) { if (scopesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureScopesIsMutable(); scopes_.add(value); onChanged(); } else { scopesBuilder_.addMessage(value); } return this; } public Builder addScopes( int index, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope value) { if (scopesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureScopesIsMutable(); scopes_.add(index, value); onChanged(); } else { scopesBuilder_.addMessage(index, value); } return this; } public Builder addScopes( org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder builderForValue) { if (scopesBuilder_ == null) { ensureScopesIsMutable(); scopes_.add(builderForValue.build()); onChanged(); } else { scopesBuilder_.addMessage(builderForValue.build()); } return this; } public Builder addScopes( int index, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder builderForValue) { if (scopesBuilder_ == null) { ensureScopesIsMutable(); scopes_.add(index, builderForValue.build()); onChanged(); } else { scopesBuilder_.addMessage(index, builderForValue.build()); } return this; } public Builder addAllScopes( java.lang.Iterable<? extends org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope> values) { if (scopesBuilder_ == null) { ensureScopesIsMutable(); super.addAll(values, scopes_); onChanged(); } else { scopesBuilder_.addAllMessages(values); } return this; } public Builder clearScopes() { if (scopesBuilder_ == null) { scopes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { scopesBuilder_.clear(); } return this; } public Builder removeScopes(int index) { if (scopesBuilder_ == null) { ensureScopesIsMutable(); scopes_.remove(index); onChanged(); } else { scopesBuilder_.remove(index); } return this; } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder getScopesBuilder( int index) { return getScopesFieldBuilder().getBuilder(index); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScopeOrBuilder getScopesOrBuilder( int index) { if (scopesBuilder_ == null) { return scopes_.get(index); } else { return scopesBuilder_.getMessageOrBuilder(index); } } public java.util.List<? extends org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScopeOrBuilder> getScopesOrBuilderList() { if (scopesBuilder_ != null) { return scopesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(scopes_); } } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder addScopesBuilder() { return getScopesFieldBuilder().addBuilder( org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.getDefaultInstance()); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder addScopesBuilder( int index) { return getScopesFieldBuilder().addBuilder( index, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.getDefaultInstance()); } public java.util.List<org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder> getScopesBuilderList() { return getScopesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScopeOrBuilder> getScopesFieldBuilder() { if (scopesBuilder_ == null) { scopesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScopeOrBuilder>( scopes_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); scopes_ = null; } return scopesBuilder_; } // optional uint32 followingKvCount = 7; private int followingKvCount_ ; public boolean hasFollowingKvCount() { return ((bitField0_ & 0x00000040) == 0x00000040); } public int getFollowingKvCount() { return followingKvCount_; } public Builder setFollowingKvCount(int value) { bitField0_ |= 0x00000040; followingKvCount_ = value; onChanged(); return this; } public Builder clearFollowingKvCount() { bitField0_ = (bitField0_ & ~0x00000040); followingKvCount_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:WALKey) } static { defaultInstance = new WALKey(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:WALKey) } public interface FamilyScopeOrBuilder extends com.google.protobuf.MessageOrBuilder { // required bytes family = 1; boolean hasFamily(); com.google.protobuf.ByteString getFamily(); // required .ScopeType scopeType = 2; boolean hasScopeType(); org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType getScopeType(); } public static final class FamilyScope extends com.google.protobuf.GeneratedMessage implements FamilyScopeOrBuilder { // Use FamilyScope.newBuilder() to construct. private FamilyScope(Builder builder) { super(builder); } private FamilyScope(boolean noInit) {} private static final FamilyScope defaultInstance; public static FamilyScope getDefaultInstance() { return defaultInstance; } public FamilyScope getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_FamilyScope_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_FamilyScope_fieldAccessorTable; } private int bitField0_; // required bytes family = 1; public static final int FAMILY_FIELD_NUMBER = 1; private com.google.protobuf.ByteString family_; public boolean hasFamily() { return ((bitField0_ & 0x00000001) == 0x00000001); } public com.google.protobuf.ByteString getFamily() { return family_; } // required .ScopeType scopeType = 2; public static final int SCOPETYPE_FIELD_NUMBER = 2; private org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType scopeType_; public boolean hasScopeType() { return ((bitField0_ & 0x00000002) == 0x00000002); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType getScopeType() { return scopeType_; } private void initFields() { family_ = com.google.protobuf.ByteString.EMPTY; scopeType_ = org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType.REPLICATION_SCOPE_LOCAL; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasFamily()) { memoizedIsInitialized = 0; return false; } if (!hasScopeType()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, family_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeEnum(2, scopeType_.getNumber()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, family_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, scopeType_.getNumber()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope)) { return super.equals(obj); } org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope other = (org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope) obj; boolean result = true; result = result && (hasFamily() == other.hasFamily()); if (hasFamily()) { result = result && getFamily() .equals(other.getFamily()); } result = result && (hasScopeType() == other.hasScopeType()); if (hasScopeType()) { result = result && (getScopeType() == other.getScopeType()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasFamily()) { hash = (37 * hash) + FAMILY_FIELD_NUMBER; hash = (53 * hash) + getFamily().hashCode(); } if (hasScopeType()) { hash = (37 * hash) + SCOPETYPE_FIELD_NUMBER; hash = (53 * hash) + hashEnum(getScopeType()); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScopeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_FamilyScope_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_FamilyScope_fieldAccessorTable; } // Construct using org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); family_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); scopeType_ = org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType.REPLICATION_SCOPE_LOCAL; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.getDescriptor(); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope getDefaultInstanceForType() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.getDefaultInstance(); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope build() { org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope buildPartial() { org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope result = new org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.family_ = family_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.scopeType_ = scopeType_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope) { return mergeFrom((org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope other) { if (other == org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.getDefaultInstance()) return this; if (other.hasFamily()) { setFamily(other.getFamily()); } if (other.hasScopeType()) { setScopeType(other.getScopeType()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasFamily()) { return false; } if (!hasScopeType()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { bitField0_ |= 0x00000001; family_ = input.readBytes(); break; } case 16: { int rawValue = input.readEnum(); org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType value = org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; scopeType_ = value; } break; } } } } private int bitField0_; // required bytes family = 1; private com.google.protobuf.ByteString family_ = com.google.protobuf.ByteString.EMPTY; public boolean hasFamily() { return ((bitField0_ & 0x00000001) == 0x00000001); } public com.google.protobuf.ByteString getFamily() { return family_; } public Builder setFamily(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; family_ = value; onChanged(); return this; } public Builder clearFamily() { bitField0_ = (bitField0_ & ~0x00000001); family_ = getDefaultInstance().getFamily(); onChanged(); return this; } // required .ScopeType scopeType = 2; private org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType scopeType_ = org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType.REPLICATION_SCOPE_LOCAL; public boolean hasScopeType() { return ((bitField0_ & 0x00000002) == 0x00000002); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType getScopeType() { return scopeType_; } public Builder setScopeType(org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; scopeType_ = value; onChanged(); return this; } public Builder clearScopeType() { bitField0_ = (bitField0_ & ~0x00000002); scopeType_ = org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType.REPLICATION_SCOPE_LOCAL; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:FamilyScope) } static { defaultInstance = new FamilyScope(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:FamilyScope) } public interface CompactionDescriptorOrBuilder extends com.google.protobuf.MessageOrBuilder { // required bytes tableName = 1; boolean hasTableName(); com.google.protobuf.ByteString getTableName(); // required bytes encodedRegionName = 2; boolean hasEncodedRegionName(); com.google.protobuf.ByteString getEncodedRegionName(); // required bytes familyName = 3; boolean hasFamilyName(); com.google.protobuf.ByteString getFamilyName(); // repeated string compactionInput = 4; java.util.List<String> getCompactionInputList(); int getCompactionInputCount(); String getCompactionInput(int index); // repeated string compactionOutput = 5; java.util.List<String> getCompactionOutputList(); int getCompactionOutputCount(); String getCompactionOutput(int index); // required string storeHomeDir = 6; boolean hasStoreHomeDir(); String getStoreHomeDir(); } public static final class CompactionDescriptor extends com.google.protobuf.GeneratedMessage implements CompactionDescriptorOrBuilder { // Use CompactionDescriptor.newBuilder() to construct. private CompactionDescriptor(Builder builder) { super(builder); } private CompactionDescriptor(boolean noInit) {} private static final CompactionDescriptor defaultInstance; public static CompactionDescriptor getDefaultInstance() { return defaultInstance; } public CompactionDescriptor getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_CompactionDescriptor_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_CompactionDescriptor_fieldAccessorTable; } private int bitField0_; // required bytes tableName = 1; public static final int TABLENAME_FIELD_NUMBER = 1; private com.google.protobuf.ByteString tableName_; public boolean hasTableName() { return ((bitField0_ & 0x00000001) == 0x00000001); } public com.google.protobuf.ByteString getTableName() { return tableName_; } // required bytes encodedRegionName = 2; public static final int ENCODEDREGIONNAME_FIELD_NUMBER = 2; private com.google.protobuf.ByteString encodedRegionName_; public boolean hasEncodedRegionName() { return ((bitField0_ & 0x00000002) == 0x00000002); } public com.google.protobuf.ByteString getEncodedRegionName() { return encodedRegionName_; } // required bytes familyName = 3; public static final int FAMILYNAME_FIELD_NUMBER = 3; private com.google.protobuf.ByteString familyName_; public boolean hasFamilyName() { return ((bitField0_ & 0x00000004) == 0x00000004); } public com.google.protobuf.ByteString getFamilyName() { return familyName_; } // repeated string compactionInput = 4; public static final int COMPACTIONINPUT_FIELD_NUMBER = 4; private com.google.protobuf.LazyStringList compactionInput_; public java.util.List<String> getCompactionInputList() { return compactionInput_; } public int getCompactionInputCount() { return compactionInput_.size(); } public String getCompactionInput(int index) { return compactionInput_.get(index); } // repeated string compactionOutput = 5; public static final int COMPACTIONOUTPUT_FIELD_NUMBER = 5; private com.google.protobuf.LazyStringList compactionOutput_; public java.util.List<String> getCompactionOutputList() { return compactionOutput_; } public int getCompactionOutputCount() { return compactionOutput_.size(); } public String getCompactionOutput(int index) { return compactionOutput_.get(index); } // required string storeHomeDir = 6; public static final int STOREHOMEDIR_FIELD_NUMBER = 6; private java.lang.Object storeHomeDir_; public boolean hasStoreHomeDir() { return ((bitField0_ & 0x00000008) == 0x00000008); } public String getStoreHomeDir() { java.lang.Object ref = storeHomeDir_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (com.google.protobuf.Internal.isValidUtf8(bs)) { storeHomeDir_ = s; } return s; } } private com.google.protobuf.ByteString getStoreHomeDirBytes() { java.lang.Object ref = storeHomeDir_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); storeHomeDir_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { tableName_ = com.google.protobuf.ByteString.EMPTY; encodedRegionName_ = com.google.protobuf.ByteString.EMPTY; familyName_ = com.google.protobuf.ByteString.EMPTY; compactionInput_ = com.google.protobuf.LazyStringArrayList.EMPTY; compactionOutput_ = com.google.protobuf.LazyStringArrayList.EMPTY; storeHomeDir_ = ""; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasTableName()) { memoizedIsInitialized = 0; return false; } if (!hasEncodedRegionName()) { memoizedIsInitialized = 0; return false; } if (!hasFamilyName()) { memoizedIsInitialized = 0; return false; } if (!hasStoreHomeDir()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, tableName_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, encodedRegionName_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, familyName_); } for (int i = 0; i < compactionInput_.size(); i++) { output.writeBytes(4, compactionInput_.getByteString(i)); } for (int i = 0; i < compactionOutput_.size(); i++) { output.writeBytes(5, compactionOutput_.getByteString(i)); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeBytes(6, getStoreHomeDirBytes()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, tableName_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, encodedRegionName_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, familyName_); } { int dataSize = 0; for (int i = 0; i < compactionInput_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(compactionInput_.getByteString(i)); } size += dataSize; size += 1 * getCompactionInputList().size(); } { int dataSize = 0; for (int i = 0; i < compactionOutput_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(compactionOutput_.getByteString(i)); } size += dataSize; size += 1 * getCompactionOutputList().size(); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(6, getStoreHomeDirBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor)) { return super.equals(obj); } org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor other = (org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor) obj; boolean result = true; result = result && (hasTableName() == other.hasTableName()); if (hasTableName()) { result = result && getTableName() .equals(other.getTableName()); } result = result && (hasEncodedRegionName() == other.hasEncodedRegionName()); if (hasEncodedRegionName()) { result = result && getEncodedRegionName() .equals(other.getEncodedRegionName()); } result = result && (hasFamilyName() == other.hasFamilyName()); if (hasFamilyName()) { result = result && getFamilyName() .equals(other.getFamilyName()); } result = result && getCompactionInputList() .equals(other.getCompactionInputList()); result = result && getCompactionOutputList() .equals(other.getCompactionOutputList()); result = result && (hasStoreHomeDir() == other.hasStoreHomeDir()); if (hasStoreHomeDir()) { result = result && getStoreHomeDir() .equals(other.getStoreHomeDir()); } result = result && getUnknownFields().equals(other.getUnknownFields()); return result; } @java.lang.Override public int hashCode() { int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); if (hasTableName()) { hash = (37 * hash) + TABLENAME_FIELD_NUMBER; hash = (53 * hash) + getTableName().hashCode(); } if (hasEncodedRegionName()) { hash = (37 * hash) + ENCODEDREGIONNAME_FIELD_NUMBER; hash = (53 * hash) + getEncodedRegionName().hashCode(); } if (hasFamilyName()) { hash = (37 * hash) + FAMILYNAME_FIELD_NUMBER; hash = (53 * hash) + getFamilyName().hashCode(); } if (getCompactionInputCount() > 0) { hash = (37 * hash) + COMPACTIONINPUT_FIELD_NUMBER; hash = (53 * hash) + getCompactionInputList().hashCode(); } if (getCompactionOutputCount() > 0) { hash = (37 * hash) + COMPACTIONOUTPUT_FIELD_NUMBER; hash = (53 * hash) + getCompactionOutputList().hashCode(); } if (hasStoreHomeDir()) { hash = (37 * hash) + STOREHOMEDIR_FIELD_NUMBER; hash = (53 * hash) + getStoreHomeDir().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); return hash; } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptorOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_CompactionDescriptor_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.internal_static_CompactionDescriptor_fieldAccessorTable; } // Construct using org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableName_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); encodedRegionName_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); familyName_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); compactionInput_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); compactionOutput_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000010); storeHomeDir_ = ""; bitField0_ = (bitField0_ & ~0x00000020); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor.getDescriptor(); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor getDefaultInstanceForType() { return org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor.getDefaultInstance(); } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor build() { org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor buildPartial() { org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor result = new org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableName_ = tableName_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.encodedRegionName_ = encodedRegionName_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.familyName_ = familyName_; if (((bitField0_ & 0x00000008) == 0x00000008)) { compactionInput_ = new com.google.protobuf.UnmodifiableLazyStringList( compactionInput_); bitField0_ = (bitField0_ & ~0x00000008); } result.compactionInput_ = compactionInput_; if (((bitField0_ & 0x00000010) == 0x00000010)) { compactionOutput_ = new com.google.protobuf.UnmodifiableLazyStringList( compactionOutput_); bitField0_ = (bitField0_ & ~0x00000010); } result.compactionOutput_ = compactionOutput_; if (((from_bitField0_ & 0x00000020) == 0x00000020)) { to_bitField0_ |= 0x00000008; } result.storeHomeDir_ = storeHomeDir_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor) { return mergeFrom((org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor other) { if (other == org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor.getDefaultInstance()) return this; if (other.hasTableName()) { setTableName(other.getTableName()); } if (other.hasEncodedRegionName()) { setEncodedRegionName(other.getEncodedRegionName()); } if (other.hasFamilyName()) { setFamilyName(other.getFamilyName()); } if (!other.compactionInput_.isEmpty()) { if (compactionInput_.isEmpty()) { compactionInput_ = other.compactionInput_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensureCompactionInputIsMutable(); compactionInput_.addAll(other.compactionInput_); } onChanged(); } if (!other.compactionOutput_.isEmpty()) { if (compactionOutput_.isEmpty()) { compactionOutput_ = other.compactionOutput_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureCompactionOutputIsMutable(); compactionOutput_.addAll(other.compactionOutput_); } onChanged(); } if (other.hasStoreHomeDir()) { setStoreHomeDir(other.getStoreHomeDir()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasTableName()) { return false; } if (!hasEncodedRegionName()) { return false; } if (!hasFamilyName()) { return false; } if (!hasStoreHomeDir()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { bitField0_ |= 0x00000001; tableName_ = input.readBytes(); break; } case 18: { bitField0_ |= 0x00000002; encodedRegionName_ = input.readBytes(); break; } case 26: { bitField0_ |= 0x00000004; familyName_ = input.readBytes(); break; } case 34: { ensureCompactionInputIsMutable(); compactionInput_.add(input.readBytes()); break; } case 42: { ensureCompactionOutputIsMutable(); compactionOutput_.add(input.readBytes()); break; } case 50: { bitField0_ |= 0x00000020; storeHomeDir_ = input.readBytes(); break; } } } } private int bitField0_; // required bytes tableName = 1; private com.google.protobuf.ByteString tableName_ = com.google.protobuf.ByteString.EMPTY; public boolean hasTableName() { return ((bitField0_ & 0x00000001) == 0x00000001); } public com.google.protobuf.ByteString getTableName() { return tableName_; } public Builder setTableName(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; tableName_ = value; onChanged(); return this; } public Builder clearTableName() { bitField0_ = (bitField0_ & ~0x00000001); tableName_ = getDefaultInstance().getTableName(); onChanged(); return this; } // required bytes encodedRegionName = 2; private com.google.protobuf.ByteString encodedRegionName_ = com.google.protobuf.ByteString.EMPTY; public boolean hasEncodedRegionName() { return ((bitField0_ & 0x00000002) == 0x00000002); } public com.google.protobuf.ByteString getEncodedRegionName() { return encodedRegionName_; } public Builder setEncodedRegionName(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; encodedRegionName_ = value; onChanged(); return this; } public Builder clearEncodedRegionName() { bitField0_ = (bitField0_ & ~0x00000002); encodedRegionName_ = getDefaultInstance().getEncodedRegionName(); onChanged(); return this; } // required bytes familyName = 3; private com.google.protobuf.ByteString familyName_ = com.google.protobuf.ByteString.EMPTY; public boolean hasFamilyName() { return ((bitField0_ & 0x00000004) == 0x00000004); } public com.google.protobuf.ByteString getFamilyName() { return familyName_; } public Builder setFamilyName(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; familyName_ = value; onChanged(); return this; } public Builder clearFamilyName() { bitField0_ = (bitField0_ & ~0x00000004); familyName_ = getDefaultInstance().getFamilyName(); onChanged(); return this; } // repeated string compactionInput = 4; private com.google.protobuf.LazyStringList compactionInput_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureCompactionInputIsMutable() { if (!((bitField0_ & 0x00000008) == 0x00000008)) { compactionInput_ = new com.google.protobuf.LazyStringArrayList(compactionInput_); bitField0_ |= 0x00000008; } } public java.util.List<String> getCompactionInputList() { return java.util.Collections.unmodifiableList(compactionInput_); } public int getCompactionInputCount() { return compactionInput_.size(); } public String getCompactionInput(int index) { return compactionInput_.get(index); } public Builder setCompactionInput( int index, String value) { if (value == null) { throw new NullPointerException(); } ensureCompactionInputIsMutable(); compactionInput_.set(index, value); onChanged(); return this; } public Builder addCompactionInput(String value) { if (value == null) { throw new NullPointerException(); } ensureCompactionInputIsMutable(); compactionInput_.add(value); onChanged(); return this; } public Builder addAllCompactionInput( java.lang.Iterable<String> values) { ensureCompactionInputIsMutable(); super.addAll(values, compactionInput_); onChanged(); return this; } public Builder clearCompactionInput() { compactionInput_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } void addCompactionInput(com.google.protobuf.ByteString value) { ensureCompactionInputIsMutable(); compactionInput_.add(value); onChanged(); } // repeated string compactionOutput = 5; private com.google.protobuf.LazyStringList compactionOutput_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureCompactionOutputIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { compactionOutput_ = new com.google.protobuf.LazyStringArrayList(compactionOutput_); bitField0_ |= 0x00000010; } } public java.util.List<String> getCompactionOutputList() { return java.util.Collections.unmodifiableList(compactionOutput_); } public int getCompactionOutputCount() { return compactionOutput_.size(); } public String getCompactionOutput(int index) { return compactionOutput_.get(index); } public Builder setCompactionOutput( int index, String value) { if (value == null) { throw new NullPointerException(); } ensureCompactionOutputIsMutable(); compactionOutput_.set(index, value); onChanged(); return this; } public Builder addCompactionOutput(String value) { if (value == null) { throw new NullPointerException(); } ensureCompactionOutputIsMutable(); compactionOutput_.add(value); onChanged(); return this; } public Builder addAllCompactionOutput( java.lang.Iterable<String> values) { ensureCompactionOutputIsMutable(); super.addAll(values, compactionOutput_); onChanged(); return this; } public Builder clearCompactionOutput() { compactionOutput_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } void addCompactionOutput(com.google.protobuf.ByteString value) { ensureCompactionOutputIsMutable(); compactionOutput_.add(value); onChanged(); } // required string storeHomeDir = 6; private java.lang.Object storeHomeDir_ = ""; public boolean hasStoreHomeDir() { return ((bitField0_ & 0x00000020) == 0x00000020); } public String getStoreHomeDir() { java.lang.Object ref = storeHomeDir_; if (!(ref instanceof String)) { String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); storeHomeDir_ = s; return s; } else { return (String) ref; } } public Builder setStoreHomeDir(String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000020; storeHomeDir_ = value; onChanged(); return this; } public Builder clearStoreHomeDir() { bitField0_ = (bitField0_ & ~0x00000020); storeHomeDir_ = getDefaultInstance().getStoreHomeDir(); onChanged(); return this; } void setStoreHomeDir(com.google.protobuf.ByteString value) { bitField0_ |= 0x00000020; storeHomeDir_ = value; onChanged(); } // @@protoc_insertion_point(builder_scope:CompactionDescriptor) } static { defaultInstance = new CompactionDescriptor(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:CompactionDescriptor) } private static com.google.protobuf.Descriptors.Descriptor internal_static_WALHeader_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_WALHeader_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_WALKey_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_WALKey_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_FamilyScope_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_FamilyScope_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_CompactionDescriptor_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_CompactionDescriptor_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\tWAL.proto\032\013hbase.proto\"#\n\tWALHeader\022\026\n" + "\016hasCompression\030\001 \001(\010\"\266\001\n\006WALKey\022\031\n\021enco" + "dedRegionName\030\001 \002(\014\022\021\n\ttableName\030\002 \002(\014\022\031" + "\n\021logSequenceNumber\030\003 \002(\004\022\021\n\twriteTime\030\004" + " \002(\004\022\030\n\tclusterId\030\005 \001(\0132\005.UUID\022\034\n\006scopes" + "\030\006 \003(\0132\014.FamilyScope\022\030\n\020followingKvCount" + "\030\007 \001(\r\"<\n\013FamilyScope\022\016\n\006family\030\001 \002(\014\022\035\n" + "\tscopeType\030\002 \002(\0162\n.ScopeType\"\241\001\n\024Compact" + "ionDescriptor\022\021\n\ttableName\030\001 \002(\014\022\031\n\021enco" + "dedRegionName\030\002 \002(\014\022\022\n\nfamilyName\030\003 \002(\014\022", "\027\n\017compactionInput\030\004 \003(\t\022\030\n\020compactionOu" + "tput\030\005 \003(\t\022\024\n\014storeHomeDir\030\006 \002(\t*F\n\tScop" + "eType\022\033\n\027REPLICATION_SCOPE_LOCAL\020\000\022\034\n\030RE" + "PLICATION_SCOPE_GLOBAL\020\001B?\n*org.apache.h" + "adoop.hbase.protobuf.generatedB\tWALProto" + "sH\001\210\001\000\240\001\001" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_WALHeader_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_WALHeader_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_WALHeader_descriptor, new java.lang.String[] { "HasCompression", }, org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader.class, org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader.Builder.class); internal_static_WALKey_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_WALKey_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_WALKey_descriptor, new java.lang.String[] { "EncodedRegionName", "TableName", "LogSequenceNumber", "WriteTime", "ClusterId", "Scopes", "FollowingKvCount", }, org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey.class, org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey.Builder.class); internal_static_FamilyScope_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_FamilyScope_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_FamilyScope_descriptor, new java.lang.String[] { "Family", "ScopeType", }, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.class, org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope.Builder.class); internal_static_CompactionDescriptor_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_CompactionDescriptor_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_CompactionDescriptor_descriptor, new java.lang.String[] { "TableName", "EncodedRegionName", "FamilyName", "CompactionInput", "CompactionOutput", "StoreHomeDir", }, org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor.class, org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor.Builder.class); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.getDescriptor(), }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
37.872848
240
0.64183
e6f45ae4b7e84c69bc58308e1e27163e41ff5deb
1,294
package ru.job4j.converter; public class Converter { public static int rubleToEuro(int value) { return value / 70; } public static int rubleToDollar(int value) { return value / 60; } public static int euroToRuble(int value) { return value * 70; } public static int dollarToRuble(int value) { return value * 60; } public static void main(String[] args) { int expected = 2; int euro = rubleToEuro(140); boolean passed = euro == expected; System.out.println("140 rubles are " + euro + " euro. Test result: " + passed); int expectedDollar = 2; int dollar = rubleToDollar(140); passed = dollar == expectedDollar; System.out.println("140 rubles are " + dollar + " dollar. Test result: " + passed); int expectedEuro = 700; int rubleFromEuro = euroToRuble(10); passed = rubleFromEuro == expectedEuro; System.out.println("10 euro are " + rubleFromEuro + " rubles. Test result: " + passed); int expectedRuble = 600; int rubleFromDollar = dollarToRuble(10); passed = rubleFromDollar == expectedRuble; System.out.println("10 dollar are " + rubleFromDollar + " rubles. Test result: " + passed); } }
30.093023
99
0.608964
fa981ea25136a8f8b87555a4d51009472457ec95
284
package hahaha.lalala.inheri3; /* 1.父类的私有属性是可以继承但是 不能直接访问 2.子类调用资源时 优先在本类中查找 当 本类中没有时去上一层查找 如果都没有 报错 */ public class Test { public static void main(String[] args) { Cat cat = new Cat(); System.out.println("cat.age = " + cat.age); cat.eat(); } }
15.777778
51
0.612676
5d2c60c579304aca59c6d661439454cadce93732
297
package ru.ajana.work.pattern.behavior.interpreter; /** * Составное правило (правило ссылается на другое правило) * * @author Andrey Kharintsev on 16.02.2019 */ public class NonterminalExpression implements AbstractExpression { @Override public void interpreter(Context context) { } }
21.214286
66
0.760943
218584433bbab342a9fe85188d1155ef34a2ebf0
7,054
package com.example.momentum; import android.app.Activity; import android.widget.EditText; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.rule.ActivityTestRule; import com.example.momentum.habits.HabitYearActivity; import com.example.momentum.habits.ViewHabitActivity; import com.example.momentum.home.DayHabitsActivity; import com.example.momentum.login.LoginActivity; import com.robotium.solo.Solo; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class ViewHabitActivityTest { private Solo solo; @Rule public ActivityTestRule<LoginActivity> rule = new ActivityTestRule<>(LoginActivity.class, true, true); /** * This method runs before all tests and create a solo instance. */ @Before public void setUp() { solo = new Solo(InstrumentationRegistry.getInstrumentation(), rule.getActivity()); } /** * Helper method to log in with correct entries */ private void login() { solo.enterText((EditText) solo.getView(R.id.emailAddressEditText), "[email protected]"); solo.enterText((EditText) solo.getView(R.id.passwordEditText), "kaynzhell19"); solo.clickOnButton("Login"); } /** * Helper method to add a habit * Adding a habit with * title:Testing * reason: 4/4, please? * Date: November 1, 2021 * Frequency: Saturday, Sunday * Privacy: Default (Public) */ private void addHabit() { solo.clickOnView(solo.getView(R.id.navigation_add_habit)); solo.enterText((EditText) solo.getView(R.id.edit_title), "Testing"); solo.enterText((EditText) solo.getView(R.id.edit_reason), "4/4, please?"); solo.clickOnView(solo.getView(R.id.edit_date)); solo.setDatePicker(0, 2021, 10, 1); solo.clickOnText("OK"); solo.clickOnView(solo.getView(R.id.satButton)); solo.clickOnView(solo.getView(R.id.sunButton)); solo.clickOnView(solo.getView(R.id.create_habit_button)); } /** * Helper method to add another habit * title: Testing2 * reason: for more testing! * Date: November 1, 2021 * Frequency: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday * Privacy: Default (Public) */ private void addHabit2() { solo.clickOnView(solo.getView(R.id.navigation_add_habit)); solo.enterText((EditText) solo.getView(R.id.edit_title), "Testing2"); solo.enterText((EditText) solo.getView(R.id.edit_reason), "for more testing!"); solo.clickOnView(solo.getView(R.id.edit_date)); solo.setDatePicker(0, 2021, 10, 1); solo.clickOnText("OK"); solo.clickOnView(solo.getView(R.id.monButton)); solo.clickOnView(solo.getView(R.id.tueButton)); solo.clickOnView(solo.getView(R.id.wedButton)); solo.clickOnView(solo.getView(R.id.thuButton)); solo.clickOnView(solo.getView(R.id.friButton)); solo.clickOnView(solo.getView(R.id.satButton)); solo.clickOnView(solo.getView(R.id.sunButton)); solo.clickOnView(solo.getView(R.id.create_habit_button)); } /** * Helper method to delete a habit */ private void deleteHabit() { solo.clickOnView(solo.getView(R.id.card_view_delete)); solo.clickOnView(solo.getView(R.id.deleteHabitButton)); } /** * Simple test cast to verify if everything is okay. */ @Test public void start() { Activity activity = rule.getActivity(); } /** * Checks if the custom back button works correctly. */ @Test public void testBackButton() { // goes to the Activity login(); addHabit(); // goes to home, clicks on habits button and then click the newly added habit solo.clickOnView(solo.getView(R.id.navigation_home)); solo.clickOnButton("Habits"); solo.clickOnText("Testing"); // checks if it is in the ViewHabitActivity solo.assertCurrentActivity("Wrong Activity!", ViewHabitActivity.class); // clicks on the back button and checks if it went to previous activity solo.clickOnView(solo.getView(R.id.viewHabitBack)); solo.assertCurrentActivity("Wrong Activity!", MainActivity.class); // delete the habit deleteHabit(); } /** * Checks if it shows correct info given new Data */ @Test public void testConsistentInput() { // goes to the Activity login(); addHabit(); // goes to home, clicks on button and checks if the habit Testing is there solo.clickOnView(solo.getView(R.id.navigation_home)); solo.clickOnButton("Habits"); solo.waitForText("Testing", 1, 2000); // clicks the habit and checks if all it shows consistency solo.clickOnText("Testing"); solo.assertCurrentActivity("Wrong Activity!", ViewHabitActivity.class); solo.waitForText("Testing", 1, 2000); solo.waitForText("Saturday, Sunday", 1, 2000); solo.waitForText("November 01, 2021", 1, 2000); solo.waitForText("Public"); solo.waitForText("4/4, please?"); // click the visual indicator button and make sure that it goes to HabitYearActivity solo.clickOnView(solo.getView(R.id.viewIndicatorButton)); solo.assertCurrentActivity("Wrong Activity!", HabitYearActivity.class); // go back to edit activity solo.clickOnView(solo.getView(R.id.yearHabitBack)); // delete testing habit solo.clickOnView(solo.getView(R.id.viewHabitBack)); deleteHabit(); // add another habit addHabit2(); // goes to home, clicks on button and checks if the habit Testing2 is there solo.clickOnView(solo.getView(R.id.navigation_home)); solo.clickOnButton("Habits"); solo.waitForText("Testing2", 1, 2000); // clicks the habit and checks if all it shows consistency // if all frequencies are chosen, it should show Everyday solo.clickOnText("Testing2"); solo.assertCurrentActivity("Wrong Activity!", ViewHabitActivity.class); solo.waitForText("Testing2", 1, 2000); solo.waitForText("Everyday", 1, 2000); solo.waitForText("November 01, 2021", 1, 2000); solo.waitForText("Public"); solo.waitForText("for more testing!"); // click the visual indicator button and make sure that it goes to HabitYearActivity solo.clickOnView(solo.getView(R.id.viewIndicatorButton)); solo.assertCurrentActivity("Wrong Activity!", HabitYearActivity.class); // go back to view activity solo.clickOnView(solo.getView(R.id.yearHabitBack)); // delete testing2 habit solo.clickOnView(solo.getView(R.id.viewHabitBack)); deleteHabit(); } /** * Closes all activities after tests are done */ @After public void tearDown() { solo.finishOpenedActivities(); } }
35.094527
106
0.656223
71eaa57d1b68565a99b7c6de208e69a6576cfc15
4,868
package com.example.vincentale.leafguard_core.model; import java.util.ArrayList; import java.util.List; /** * Created by vincentale on 29/01/18. * Observation for caterpillars data summary */ public class CaterpillarObservation extends AbstractObservation { public static final int OBSERVATION_LIMIT = 2; private ArrayList<Caterpillar> caterpillars; /** * Counters for data post processing */ private int totalCaterpillars = 0; private int missingCaterpillars = 0; private int totalPredationMarks = 0; private int birdPredationMarks = 0; private int arthropodPredationMarks = 0; private int mammalPredationMarks = 0; private int lizardPredationMarks = 0; private int observationIndex = 0; public CaterpillarObservation() { super(); } public CaterpillarObservation(Oak referedOak, int observationIndex) { super(); if (observationIndex <= 0 || observationIndex > OBSERVATION_LIMIT) { throw new IllegalArgumentException("observationIndex is not valid. Expected between 0 and " + OBSERVATION_LIMIT + ", got : " + observationIndex); } this.uid = referedOak.getUid(); this.observationIndex = observationIndex; this.caterpillars = new ArrayList<>(Caterpillar.INDEX_LIMIT); } public int getTotalCaterpillars() { return totalCaterpillars; } public void setTotalCaterpillars(int totalCaterpillars) { this.totalCaterpillars = totalCaterpillars; } public int getMissingCaterpillars() { return missingCaterpillars; } public void setMissingCaterpillars(int missingCaterpillars) { this.missingCaterpillars = missingCaterpillars; } public int getTotalPredationMarks() { return totalPredationMarks; } public void setTotalPredationMarks(int totalPredationMarks) { this.totalPredationMarks = totalPredationMarks; } public int getBirdPredationMarks() { return birdPredationMarks; } public void setBirdPredationMarks(int birdPredationMarks) { this.birdPredationMarks = birdPredationMarks; } public int getArthropodPredationMarks() { return arthropodPredationMarks; } public void setArthropodPredationMarks(int arthropodPredationMarks) { this.arthropodPredationMarks = arthropodPredationMarks; } public int getMammalPredationMarks() { return mammalPredationMarks; } public void setMammalPredationMarks(int mammalPredationMarks) { this.mammalPredationMarks = mammalPredationMarks; } public int getLizardPredationMarks() { return lizardPredationMarks; } public void setLizardPredationMarks(int lizardPredationMarks) { this.lizardPredationMarks = lizardPredationMarks; } public CaterpillarObservation addCaterpillar(Caterpillar caterpillar) { caterpillars.add(caterpillar); totalCaterpillars++; if (caterpillar.isCatterpillarMissing()) { missingCaterpillars++; } else { if (caterpillar.isCatterpillarMissing()) { missingCaterpillars++; } if (caterpillar.isWoundByBird()) { birdPredationMarks++; totalPredationMarks++; } if (caterpillar.isWoundByInsect()) { arthropodPredationMarks++; totalPredationMarks++; } if (caterpillar.isWoundByMammal()) { mammalPredationMarks++; totalPredationMarks++; } if (caterpillar.isWoundByLizard()) { lizardPredationMarks++; totalPredationMarks++; } } return this; } public CaterpillarObservation setCaterpillars(List<Caterpillar> caterpillarList) { for (Caterpillar c : caterpillarList) { addCaterpillar(c); } return this; } public int getObservationIndex() { return observationIndex; } public void setObservationIndex(int observationIndex) { this.observationIndex = observationIndex; } @Override public String toString() { return "CaterpillarObservation{" + "uid='" + uid + '\'' + ", totalCaterpillars=" + totalCaterpillars + ", missingCaterpillars=" + missingCaterpillars + ", totalPredationMarks=" + totalPredationMarks + ", birdPredationMarks=" + birdPredationMarks + ", arthropodPredationMarks=" + arthropodPredationMarks + ", mammalPredationMarks=" + mammalPredationMarks + ", lizardPredationMarks=" + lizardPredationMarks + ", observationIndex=" + observationIndex + '}'; } }
31.205128
157
0.643385
8f7d64af6cf9bda4bede0344ce72bfb12aceaee4
1,630
package seedu.address.model.recruitment; import static java.util.Objects.requireNonNull; import static seedu.address.commons.util.AppUtil.checkArgument; /** * Represents a RecruitmentPost's minimal working experience in the address book. * Guarantees: immutable; is always valid */ public class WorkExp { public static final String MESSAGE_WORK_EXP_CONSTRAINTS = "Working Experience should only contain integers with length of at least 1 digit long" + "And the range of the working experience is from 0 to 30"; public static final String EMPLOYEE_WORK_EXP_VALIDATION_REGEX = "^(0?[0-9]|[12][0-9]|30)"; public final String workExp; /** * Constructs a {@code WorkExp}. * * @param workExp A valid Working Experience. */ public WorkExp(String workExp) { requireNonNull(workExp); checkArgument(isValidWorkExp(workExp), MESSAGE_WORK_EXP_CONSTRAINTS); this.workExp = workExp; } /** * Returns true if a given string is a valid Working Experience. */ public static boolean isValidWorkExp(String test) { return test.matches(EMPLOYEE_WORK_EXP_VALIDATION_REGEX); } @Override public String toString() { return workExp; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof WorkExp // instanceof handles nulls && workExp.equals(((WorkExp) other).workExp)); // state check } @Override public int hashCode() { return workExp.hashCode(); } }
29.636364
98
0.663804
9077e730fbe543a7981ccc1efec9b6cb89428328
2,628
package com.redoop.modules.admin.partner.repository; import com.redoop.modules.admin.partner.entity.Partner; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import javax.transaction.Transactional; import java.awt.print.Book; import java.util.List; /** * 说明:合作伙伴数据仓库 * 包名:cn.itweet.tea.admin.component.PartnerRepository * 项目名:License-Admin * 创建人:黄天浩 * 创建时间:2017年9月7日17:06:55 */ @Repository public interface PartnerRepository extends JpaRepository<Partner,String>{ /** * 前台列表显示 * @return */ @Query(value = "From Partner a WHERE a.intention = 0 order by a.auditortime DESC") Page<Partner> listByIntention(Pageable pageable); /** * 按照名称模糊查询 * @param companyname * @return */ //@Query(value = "select * from partner c where c.companyname like CONCAT('%',:companyname,'%')",nativeQuery = true) Page<Partner> findByCompanynameLike(String companyname, Pageable pageable); /** * 根据公司名称进行查询公司信息 * @param companyname * @return */ @Query(value = "select * from partner c where c.companyname like CONCAT('%',:companyname,'%')",nativeQuery = true) Partner findByComName(String companyname); /** * 认证(未认证)认证通过是0 未认证是1 * @param id */ @Modifying @Transactional @Query(value = "UPDATE Partner SET authentication = 0 ,testresult =0 WHERE id = :id") public void authenticationWRZ(@Param("id") String id); /** * 认证(未认证)认证通过是0 未认证是1 * @param id */ @Modifying @Transactional @Query(value = "UPDATE Partner SET authentication = 1 ,testresult =1 WHERE id = :id") public void authenticationYRZ(@Param("id") String id); /** * 搜索厂商 * 前台多选搜索(checkbox) * @param partnertype * @return */ /*@Query(value = " FROM Partner WHERE partnertype = :partnertype and intention = 0")*/ /*List<Partner> findByPartnertype(@Param("partnertype")String partnertype);*/ @Query(value = " FROM Partner a WHERE a.partnertype in( :partnertype) and a.intention = 0") Page<Partner> findByPartnertype(@Param("partnertype")List<String> partnertype, Pageable pageable); @Modifying @Transactional @Query(value = "update Partner set intention=1 where id=:id") void updateIntention(@Param("id") String id); }
30.206897
121
0.688356
0e2f76229769c8381bdb1f69440abd94f282d334
1,778
package com.github.ivanshafran.cleanarchsample; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class ExchangeActivity extends AppCompatActivity implements ExchangeView { private Button button; private TextView textView; private EditText editText; private View progressBar; private ExchangePresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { presenter.onButtonClick(editText.getText().toString()); } }); textView = findViewById(R.id.text_view); editText = findViewById(R.id.edit_text); progressBar = findViewById(R.id.progress_bar); presenter = new ExchangePresenter( this, new ExchangeInteractorImpl(new ExchangeRepositoryImpl()) ); } @Override public void showProgress() { progressBar.setVisibility(View.VISIBLE); } @Override public void hideProgress() { progressBar.setVisibility(View.INVISIBLE); } @Override public void showResult(final String result) { textView.setText(result); textView.setTextColor(Color.BLACK); } @Override public void showError(final String result) { textView.setText(result); textView.setTextColor(Color.RED); } }
27.353846
81
0.677728
f48e9a4e7dc36d57480a2ee28ee046b0bb6f91b3
540
package com.vishnus1224.rxjavateamworkclient.client; import java.text.ParseException; /** * Allows for passing the updatedAfterTime param to a query. * Created by Vishnu on 8/27/2016. */ interface UpdatedAfterTime<Type> { /** * Sets the updatedAfterTime query param. * @param timeString time string in HH:MM format. * @return type instance that implements the interface. * @throws ParseException if the time is in the wrong format. */ Type updatedAfterTime(String timeString) throws ParseException; }
28.421053
67
0.727778
ee9468a665e663d36678a3021fb8307cb063b27f
2,625
/* * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.metrics; /** * Generic interface for cloud based metric collectors. * * @author zbettenbuk */ public interface MetricServicePublisher { /** * Method to publish numeric type metrics * * @param metricName Name of the metric * @param metricValue Value of the metric */ public void publishNumericMetric(String metricName, long metricValue); /** * Method to publish string type metrics * * @param metricName Name of the metric * @param metricValue Value of the metric */ public void publishStringMetric(String metricName, String metricValue); /** * Method to publish an incremental metric. Metric value with * <tt>metricName</tt> will be increased by 1. * * @param metricName Name of the metric */ public void publishIncrementalMetric(String metricName); /** * Method to publish an incremental metric. Metric value with * <tt>metricName</tt> will be increased by <tt>metricName</tt>. * * @param metricName Name of the metric * @param increment Value to increase the metric with */ public void publishIncrementalMetric(String metricName, int increment); /** * Records the start of a transaction to have the length published later. * * @param transactionType Type of the transaction (e.g. create conference) * @param transactionId Unique id of the transaction (e.g. conference ID) */ public void startMeasuredTransaction(String transactionType, String transactionId); /** * Records the finish of a transaction and publishes length metric * * @param transactionType Type of the transaction (e.g. create conference) * @param transactionId Unique id of the transaction (e.g. conference ID) */ public void endMeasuredTransaction(String transactionType, String transactionId); public String getName(); }
32.8125
78
0.678476
aab8ee746422b376de9483b54ac3cc7d20819de1
2,881
package edu.miu.cs544.team6.domain; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @Entity public class Reservation { @Id @GeneratedValue private int id; @Temporal(TemporalType.TIMESTAMP) private Date reservationDate; @Enumerated(EnumType.STRING) private ReservationStatus status; @Column(name = "is_reminder_sent") private Integer isReminderSent; @ManyToOne(cascade = CascadeType.ALL) @JsonIgnoreProperties(value="reservation") private User consumer; @ManyToOne(cascade = CascadeType.ALL) @JsonProperty("appointment") @JsonIgnoreProperties(value="reservation") private Appointment appointment; @Transient private Integer userId; @Transient private Integer appointmentId; public Reservation(Date reservationDate, Integer userId, Integer appointmentId) { this.reservationDate = reservationDate; this.userId = userId; this.appointmentId = appointmentId; this.status = ReservationStatus.PENDING; } public Reservation() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public Date getReservationDate() { return reservationDate; } public void setReservationDate(Date reservationDate) { this.reservationDate = reservationDate; } public ReservationStatus getStatus() { return status; } public void setStatus(ReservationStatus status) { this.status = status; } public User getConsumer() { return consumer; } public void setConsumer(User consumer) { this.consumer = consumer; } public Appointment getAppointment() { return appointment; } public void setAppointment(Appointment appointment) { this.appointment = appointment; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getAppointmentId() { return appointmentId; } public void setAppointmentId(Integer appointmentId) { this.appointmentId = appointmentId; } public Integer getIsReminderSent() { return isReminderSent; } public void setIsReminderSent(Integer isReminderSent) { this.isReminderSent = isReminderSent; } @Override public String toString() { return "Reservation [id=" + id + ", reservationDate=" + reservationDate + ", status=" + status + "]"; } }
20.578571
104
0.725443
6a3287fbf7200486169441ea72113669508cb64f
243
/** * create by 陶江航 at 2017/11/5 16:27 * * @version 1.0 * @email [email protected] * @description 代理模式,包括动态代理和静态代理 * <p> * 其中staticpattern存放静态代理,dynamic实现动态代理,cglib是使用cglib实现的动态代理 */ package com.ternence.designpattern.proxy;
24.3
59
0.744856
295fb2a866b40fdf967fc021f33235ae24d3778d
952
package com.cannolicatfish.rankine.init; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; public class RankineSetup { public ItemGroup rankineWorld = new ItemGroup("rankine_world") { @Override public ItemStack createIcon() { return new ItemStack(RankineBlocks.REFRACTORY_BRICKS.get()); } }; public ItemGroup rankineMetals = new ItemGroup("rankine_metallurgy") { @Override public ItemStack createIcon() { return new ItemStack(RankineItems.CINNABAR_ORE.get()); } }; public ItemGroup rankineElements = new ItemGroup("rankine_elements") { @Override public ItemStack createIcon() { return new ItemStack(RankineItems.NIOBIUM_INGOT.get()); } }; public ItemGroup rankineTools = new ItemGroup("rankine_misc") { @Override public ItemStack createIcon() { return new ItemStack(RankineItems.STEEL_SPEAR.get()); } }; }
31.733333
102
0.690126
fa9e3dc85a2173eb93ee16d7160cb3e85f5b84ad
1,220
package ca.bc.gov.open.pssg.rsbc.figaro.ords.client.organization; /** * Represents a Validate Org Party Requests * * @author carolcarpenterjustice */ public class ValidateOrgPartyRequest { String orgCity; String orgPartyId; String orgSubname1; String orgSubname2; String orgSubname3; String orgSubname4; String orgSubname5; public ValidateOrgPartyRequest(String orgCity, String orgPartyId, String orgSubname1, String orgSubname2, String orgSubname3, String orgSubname4, String orgSubname5) { this.orgCity = orgCity; this.orgPartyId = orgPartyId; this.orgSubname1 = orgSubname1; this.orgSubname2 = orgSubname2; this.orgSubname3 = orgSubname3; this.orgSubname4 = orgSubname4; this.orgSubname5 = orgSubname5; } public String getOrgCity() { return orgCity; } public String getOrgPartyId() { return orgPartyId; } public String getOrgSubname1() { return orgSubname1; } public String getOrgSubname2() { return orgSubname2; } public String getOrgSubname3() { return orgSubname3; } public String getOrgSubname4() { return orgSubname4; } public String getOrgSubname5() { return orgSubname5; } }
29.047619
171
0.713115
a70f8829404a90a857c79f5a6373b058cb2f2b29
730
package br.com.juliocnsouza.projects.products.controllers; import br.com.juliocnsouza.projects.products.DataInitializer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * * @author julio */ @Controller public class HomeController { @Autowired private DataInitializer dataInitializer; @RequestMapping( "/" ) @ResponseBody public String home() { final long[] counts = dataInitializer.init(); return "Products REST API. Total of " + counts[0] + " products and " + counts[1] + " images."; } }
27.037037
102
0.738356
1eb2c1662e9306aeb07e8cebc6b53e5943cead66
3,328
package com.frostphyr.avail.math; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.function.ThrowingRunnable; public class MatrixUtilsTest { private final int[] matrix1x3_1 = {1, 2, 3}; private final int[] matrix1x3_2 = {4, 5, 6}; private final int[][] matrix2x3_1 = { {1, 2, 3}, {4, 5, 6} }; private final int[][] matrix2x3_2 = { {7, 8, 9}, {10, 11, 12} }; private final int[][] matrix3x3 = { {7, 8, 9}, {10, 11, 12}, {13, 14, 15} }; private final int[][] matrix3x1 = { {4}, {5}, {6} }; @Test public void testValidateMatrix1d() { assertTrue(MatrixUtils.validateMatrix(matrix1x3_1)); assertFalse(MatrixUtils.validateMatrix((int[]) null)); assertFalse(MatrixUtils.validateMatrix(new int[0])); } @Test public void testValidateMatrix2d() { assertTrue(MatrixUtils.validateMatrix(matrix2x3_1)); assertFalse(MatrixUtils.validateMatrix((int[][]) null)); assertFalse(MatrixUtils.validateMatrix(new int[0][0])); assertFalse(MatrixUtils.validateMatrix(new int[3][0])); assertFalse(MatrixUtils.validateMatrix(new int[0][3])); assertFalse(MatrixUtils.validateMatrix(new int[][] { {1, 2, 3}, {4, 5}, {6, 7, 8} })); } @Test public void testTranspose1d() { assertArrayEquals(new int[][] { {1}, {2}, {3} }, MatrixUtils.transpose(matrix1x3_1)); } @Test public void testTranspose2d() { assertArrayEquals(new int[][] { {1, 4}, {2, 5}, {3, 6} }, MatrixUtils.transpose(matrix2x3_1)); } @Test public void testAdd1d() { assertArrayEquals(new int[] { 5, 7, 9 }, MatrixUtils.add(matrix1x3_1, matrix1x3_2)); } @Test public void testAdd2d() { assertArrayEquals(new int[][] { {8, 10, 12}, {14, 16, 18} }, MatrixUtils.add(matrix2x3_1, matrix2x3_2)); } @Test public void testMultiply1d2d() { assertArrayEquals(new int[] { 66, 72, 78 }, MatrixUtils.multiply(matrix1x3_1, matrix3x3)); assertThrows(IllegalArgumentException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { MatrixUtils.multiply(matrix1x3_1, matrix2x3_1); } }); } @Test public void testMultiply2d1d() { assertArrayEquals(new int[][] { {4, 8, 12}, {5, 10, 15}, {6, 12, 18} }, MatrixUtils.multiply(matrix3x1, matrix1x3_1)); assertThrows(IllegalArgumentException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { MatrixUtils.multiply(matrix3x3, matrix1x3_1); } }); } @Test public void testMultiply2d2d() { assertArrayEquals(new int[][] { {66, 72, 78}, {156, 171, 186} }, MatrixUtils.multiply(matrix2x3_1, matrix3x3)); assertThrows(IllegalArgumentException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { MatrixUtils.multiply(matrix3x3, matrix2x3_1); } }); } @Test public void testMultiplyScalar1d() { assertArrayEquals(new int[] { 2, 4, 6 }, MatrixUtils.multiply(matrix1x3_1, 2)); } @Test public void testMultiplyScalar2d() { assertArrayEquals(new int[][] { {2, 4, 6}, {8, 10, 12} }, MatrixUtils.multiply(matrix2x3_1, 2)); } }
20.930818
71
0.65625
5a0a6c3c27cf2490f341c8e4399fca64ad1ab65c
4,952
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datafactory.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.datafactory.models.Activity; import com.azure.resourcemanager.datafactory.models.Expression; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Until activity properties. */ @Fluent public final class UntilActivityTypeProperties { /* * An expression that would evaluate to Boolean. The loop will continue * until this expression evaluates to true */ @JsonProperty(value = "expression", required = true) private Expression expression; /* * Specifies the timeout for the activity to run. If there is no value * specified, it takes the value of TimeSpan.FromDays(7) which is 1 week as * default. Type: string (or Expression with resultType string), pattern: * ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). Type: string (or * Expression with resultType string), pattern: * ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). */ @JsonProperty(value = "timeout") private Object timeout; /* * List of activities to execute. */ @JsonProperty(value = "activities", required = true) private List<Activity> activities; /** * Get the expression property: An expression that would evaluate to Boolean. The loop will continue until this * expression evaluates to true. * * @return the expression value. */ public Expression expression() { return this.expression; } /** * Set the expression property: An expression that would evaluate to Boolean. The loop will continue until this * expression evaluates to true. * * @param expression the expression value to set. * @return the UntilActivityTypeProperties object itself. */ public UntilActivityTypeProperties withExpression(Expression expression) { this.expression = expression; return this; } /** * Get the timeout property: Specifies the timeout for the activity to run. If there is no value specified, it takes * the value of TimeSpan.FromDays(7) which is 1 week as default. Type: string (or Expression with resultType * string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). Type: string (or Expression with * resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). * * @return the timeout value. */ public Object timeout() { return this.timeout; } /** * Set the timeout property: Specifies the timeout for the activity to run. If there is no value specified, it takes * the value of TimeSpan.FromDays(7) which is 1 week as default. Type: string (or Expression with resultType * string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). Type: string (or Expression with * resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). * * @param timeout the timeout value to set. * @return the UntilActivityTypeProperties object itself. */ public UntilActivityTypeProperties withTimeout(Object timeout) { this.timeout = timeout; return this; } /** * Get the activities property: List of activities to execute. * * @return the activities value. */ public List<Activity> activities() { return this.activities; } /** * Set the activities property: List of activities to execute. * * @param activities the activities value to set. * @return the UntilActivityTypeProperties object itself. */ public UntilActivityTypeProperties withActivities(List<Activity> activities) { this.activities = activities; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (expression() == null) { throw LOGGER .logExceptionAsError( new IllegalArgumentException( "Missing required property expression in model UntilActivityTypeProperties")); } else { expression().validate(); } if (activities() == null) { throw LOGGER .logExceptionAsError( new IllegalArgumentException( "Missing required property activities in model UntilActivityTypeProperties")); } else { activities().forEach(e -> e.validate()); } } private static final ClientLogger LOGGER = new ClientLogger(UntilActivityTypeProperties.class); }
36.681481
120
0.635905
0293cb3fb4c555f66eabcc1d9768aae4ebf697b8
1,167
/* * 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 br.senac.tads.dsw.exemplosspring; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; /** * * @author fernando.tsuda */ @Controller @SessionAttributes("dtRegistro") public class ExemploSessao1Controller { @GetMapping("/exemplo-sessao1") public ModelAndView mostrarTela( @ModelAttribute("dtRegistro") List<LocalDateTime> registrosAcesso) { registrosAcesso.add(LocalDateTime.now()); return new ModelAndView("exemplo-sessao1"); } @ModelAttribute("dtRegistro") public List<LocalDateTime> getListaRegistros() { return new ArrayList<LocalDateTime>(); } }
31.540541
81
0.735219
135c834642908708570af5eaaecd4bb6eb4f2d0d
729
package com.data.big.trying.tryingbigdata.helper; import org.springframework.util.ResourceUtils; import java.io.File; import java.nio.file.Files; public class JsonHelper { public static final String loadTemperatureRequest(String filename) throws Exception { return loadFile("classpath:requests/temperature/" + filename + ".json"); } public static final String loadTemperatureResponse(String filename) throws Exception { return loadFile("classpath:responses/temperature/" + filename + ".json"); } private static String loadFile(String filePath) throws Exception { File file = ResourceUtils.getFile(filePath); return new String(Files.readAllBytes(file.toPath())); } }
31.695652
91
0.73251
34de4e5610dc2f73d25246362dfbfd75311a2a79
6,404
/* * Copyright (c) 2019-2022 Team Galacticraft * * 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 dev.galacticraft.mod.world.gen.carver; import com.mojang.serialization.Codec; import dev.galacticraft.mod.world.gen.carver.config.CraterCarverConfig; import net.minecraft.structure.StructureStart; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.ChunkSectionPos; import net.minecraft.util.math.Direction; import net.minecraft.world.ChunkRegion; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.gen.carver.Carver; import net.minecraft.world.gen.carver.CarverContext; import net.minecraft.world.gen.chunk.AquiferSampler; import net.minecraft.world.gen.feature.StructureFeature; import java.util.BitSet; import java.util.Random; import java.util.function.Function; import java.util.stream.Stream; /** * @author <a href="https://github.com/TeamGalacticraft">TeamGalacticraft</a> */ public class CraterCarver extends Carver<CraterCarverConfig> { public CraterCarver(Codec<CraterCarverConfig> configCodec) { super(configCodec); } @Override public boolean carve(CarverContext context, CraterCarverConfig config, Chunk chunk, Function<BlockPos, Biome> posToBiome, Random random, AquiferSampler aquiferSampler, ChunkPos pos, BitSet carvingMask) { int y = 127;//config.y.get(random, context); //pos = center chunk pos BlockPos craterCenter = pos.getBlockPos(random.nextInt(16), y, random.nextInt(16)); if (!chunk.getStructureReferences(StructureFeature.VILLAGE).isEmpty()) { return false; } BlockPos.Mutable mutable = craterCenter.mutableCopy(); double radius = 8 + (random.nextDouble() * (config.maxRadius - config.minRadius)); if (random.nextBoolean() && radius < (config.minRadius + config.idealRangeOffset) || radius > (config.maxRadius - config.idealRangeOffset)) radius = 8 + (random.nextDouble() * (config.maxRadius - config.minRadius)); double depthMultiplier = 1 - ((random.nextDouble() - 0.5) * 0.3); boolean fresh = random.nextInt(16) == 1; for (int innerChunkX = 0; innerChunkX < 16; innerChunkX++) { //iterate through positions in chunk for (int innerChunkZ = 0; innerChunkZ < 16; innerChunkZ++) { double toDig = 0; double xDev = Math.abs((chunk.getPos().getOffsetX(innerChunkX)) - craterCenter.getX()); double zDev = Math.abs((chunk.getPos().getOffsetZ(innerChunkZ)) - craterCenter.getZ()); if (xDev >= 0 && xDev < 32 && zDev >= 0 && zDev < 32) { if (xDev * xDev + zDev * zDev < radius * radius) { //distance to crater and depth xDev /= radius; zDev /= radius; final double sqrtY = xDev * xDev + zDev * zDev; double yDev = sqrtY * sqrtY * 6; double craterDepth = 5 - yDev; craterDepth *= depthMultiplier; if (craterDepth > 0.0) { toDig = craterDepth; } } if (toDig >= 1) { toDig++; // Increase crater depth, but for sum, not each crater if (fresh) toDig++; // Dig one more block, because we're not replacing the top with turf } BlockPos.Mutable copy = new BlockPos.Mutable(); mutable.set(innerChunkX, y, innerChunkZ); for (int dug = 0; dug < toDig; dug++) { mutable.move(Direction.DOWN); if (!chunk.getBlockState(mutable).isAir() || carvingMask.get(innerChunkX + (innerChunkZ << 4) + ((mutable.getY() + 128) << 8)) || dug > 0) { chunk.setBlockState(mutable, CAVE_AIR, false); if (dug == 0) { carvingMask.set(innerChunkX + (innerChunkZ << 4) + ((mutable.getY() + 128) << 8), true); } if (!fresh && dug + 1 >= toDig && !chunk.getBlockState(copy.set(mutable).move(Direction.DOWN, 2)).isAir()) { chunk.setBlockState(mutable.move(Direction.DOWN), posToBiome.apply(chunk.getPos().getBlockPos(mutable.getX(), mutable.getY(), mutable.getZ())).getGenerationSettings().getSurfaceConfig().getTopMaterial(), false); } } else { dug--; } } } } } return true; } public Stream<? extends StructureStart<?>> getStructuresWithChildren(Chunk chunk, ChunkRegion region, StructureFeature<?> feature) { return chunk.getStructureReferences(feature).stream().map(l -> ChunkSectionPos.from(new ChunkPos(l), chunk.getBottomSectionCoord())).map(posx -> chunk.getStructureStart(feature)).filter(structureStart -> structureStart != null && structureStart.hasChildren()); } @Override public boolean shouldCarve(CraterCarverConfig config, Random random) { return random.nextFloat() <= config.probability; } }
51.645161
268
0.625859
00c3e8aac6fad85bf7eefc6555db21c6d29b271e
4,239
package org.orecruncher.dsurround.effects.blocks.producers; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.block.AbstractFurnaceBlock; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.tag.FluidTags; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import org.orecruncher.dsurround.effects.IBlockEffect; import org.orecruncher.dsurround.effects.IBlockEffectProducer; import org.orecruncher.dsurround.lib.scripting.Script; import org.orecruncher.dsurround.runtime.ConditionEvaluator; import java.util.Optional; import java.util.Random; import java.util.function.Predicate; @Environment(EnvType.CLIENT) public abstract class BlockEffectProducer implements IBlockEffectProducer { protected final Script chance; protected final Script conditions; protected BlockEffectProducer(Script chance, Script conditions) { this.chance = chance; this.conditions = conditions; } protected boolean canTrigger(World world, BlockState state, BlockPos pos, Random rand) { if (ConditionEvaluator.INSTANCE.check(this.conditions)) { var chance = ConditionEvaluator.INSTANCE.eval(this.chance); return chance instanceof Double c && rand.nextDouble() < c; } return false; } @Override public Optional<IBlockEffect> produce(World world, BlockState state, BlockPos pos, Random rand) { if (this.canTrigger(world, state, pos, rand)) { return this.produceImpl(world, state, pos, rand); } return Optional.empty(); } protected abstract Optional<IBlockEffect> produceImpl(World world, BlockState state, BlockPos pos, Random rand); // // Bunch of helper methods for implementations // public static final int MAX_STRENGTH = 10; public static final Predicate<BlockState> FLUID_PREDICATE = (state) -> !state.getFluidState().isEmpty(); public static final Predicate<BlockState> LAVA_PREDICATE = (state) -> state.getFluidState().isIn(FluidTags.LAVA); public static final Predicate<BlockState> WATER_PREDICATE = (state) -> state.getFluidState().isIn(FluidTags.WATER); public static final Predicate<BlockState> SOLID_PREDICATE = (state) -> state.getMaterial().isSolid(); public static final Predicate<BlockState> LIT_FURNACE = (state) -> state.getBlock() instanceof AbstractFurnaceBlock && state.get(AbstractFurnaceBlock.LIT); public static final Predicate<BlockState> HOTBLOCK_PREDICATE = (state) -> LAVA_PREDICATE.test(state) || state.getBlock() == Blocks.MAGMA_BLOCK || LIT_FURNACE.test(state); public static int countVerticalBlocks(final World provider, final BlockPos pos, final Predicate<BlockState> predicate, final int step) { int count = 0; final BlockPos.Mutable mutable = pos.mutableCopy(); for (; count < MAX_STRENGTH && predicate.test(provider.getBlockState(mutable)); count++) mutable.setY(mutable.getY() + step); return MathHelper.clamp(count, 0, MAX_STRENGTH); } public static int countCubeBlocks(final World provider, final BlockPos pos, final Predicate<BlockState> predicate, final boolean fastFirst) { int blockCount = 0; for (int k = -1; k <= 1; k++) for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) { final BlockState state = provider.getBlockState(pos.add(i, j, k)); if (predicate.test(state)) { if (fastFirst) return 1; blockCount++; } } return blockCount; } @Override public String toString() { return this.getClass().getSimpleName() + "{chance: " + this.chance + "; conditions: " + this.conditions + "}"; } }
40.371429
119
0.63765
ac6dbb8aa3dbacdb2e8d02ad3ae9c3413e8f118f
6,337
package ru.easydonate.easypayments.task; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.bukkit.plugin.Plugin; import ru.easydonate.easypayments.EasyPaymentsPlugin; import ru.easydonate.easypayments.cache.ReportCache; import ru.easydonate.easypayments.execution.ExecutionBundle; import ru.easydonate.easypayments.execution.InterceptorFactory; import ru.easydonate.easypayments.sdk.EasyPaymentsSDK; import ru.easydonate.easypayments.sdk.data.model.ProcessPayment; import ru.easydonate.easypayments.sdk.data.model.ProcessPaymentReport; import ru.easydonate.easypayments.sdk.data.model.ProcessPaymentReports; import ru.easydonate.easypayments.sdk.exception.ApiException; import ru.easydonate.easypayments.sdk.exception.ErrorResponseException; import ru.easydonate.easypayments.sdk.exception.UnsuccessfulResponseException; import ru.easydonate.easypayments.sdk.response.AbstractResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; public final class PaymentsQueryTask extends AbstractPluginTask { private final EasyPaymentsSDK sdk; private final InterceptorFactory interceptorFactory; private final ReportCache reportCache; public PaymentsQueryTask(Plugin plugin, EasyPaymentsSDK sdk, InterceptorFactory interceptorFactory, ReportCache reportCache) { super(plugin, 100L); this.sdk = sdk; this.interceptorFactory = interceptorFactory; this.reportCache = reportCache; } @Override protected long getPeriod() { int period = plugin.getConfig().getInt("request-frequency", 1); return period >= 1 ? period * 1200L : 1200L; // >= 1 min. } @Override public void run() { synchronized (sdk) { List<ProcessPaymentReport> uncompetedReports = null; Map<Integer, Boolean> processedReports = null; try { List<ProcessPayment> processPayments = sdk.getProcessPayments(); if(processPayments == null || processPayments.isEmpty()) return; processPayments.removeIf(reportCache::isCached); if(processPayments.isEmpty()) return; ProcessPaymentReports reports = ProcessPaymentReports.empty(); processPayments.parallelStream().forEach(payment -> handlePayment(payment, reports)); if(reports.isEmpty()) return; uncompetedReports = reports.getReports(); reportCache.addToCache(uncompetedReports); Gson gson = new GsonBuilder().setPrettyPrinting().create(); if(EasyPaymentsPlugin.isDebugEnabled()) { plugin.getLogger().info("--- [ Process payments reports ] ---"); plugin.getLogger().info(gson.toJson(reports)); } processedReports = sdk.reportProcessPayments(reports); } catch (ApiException ex) { if(EasyPaymentsPlugin.logQueryTaskErrors() && EasyPaymentsPlugin.isDebugEnabled()) warning("API response: %s", ex.getMessage()); } catch (UnsuccessfulResponseException ex) { AbstractResponse<Map<Integer, Boolean>> response = ex.getResponse(); processedReports = response.getResponseObject(); } catch (ErrorResponseException ex) { if(EasyPaymentsPlugin.logQueryTaskErrors()) { error("HTTP request failed!"); error("Details: " + ex.getMessage()); } } catch (IOException ex) { if(EasyPaymentsPlugin.logQueryTaskErrors()) { error("Cannot connect to the API server!"); error("Details: " + ex.getMessage()); if(EasyPaymentsPlugin.isDebugEnabled()) ex.printStackTrace(); } } if(processedReports != null && uncompetedReports != null) { Map<Integer, Boolean> processed = processedReports; List<ProcessPaymentReport> completed = new ArrayList<>(uncompetedReports); uncompetedReports.removeIf(report -> processed.getOrDefault(report.getPaymentId(), false)); completed.removeAll(uncompetedReports); handleUncompletedReports(uncompetedReports); reportCache.unloadReports(completed); } } } @SuppressWarnings("unchecked") private void handlePayment(ProcessPayment payment, ProcessPaymentReports reports) { List<String> commands = payment.getCommands(); ProcessPaymentReport report = ProcessPaymentReport.create(payment); report.setPayload(payment.getPayload()); reports.addReport(report); if(commands == null || commands.isEmpty()) return; AtomicInteger counter = new AtomicInteger(); CompletableFuture<ExecutionBundle>[] futures = commands.stream() .map(cmd -> new ExecutionBundle(counter.getAndIncrement(), cmd, plugin, interceptorFactory)) .map(ExecutionBundle::executeAsync) .toArray(CompletableFuture[]::new); CompletableFuture.allOf(futures).join(); Arrays.stream(futures) .map(CompletableFuture::join) .forEach(exec -> exec.saveTo(report)); } private void handleUncompletedReports(List<ProcessPaymentReport> reports) { if(reports == null || reports.isEmpty()) return; if(EasyPaymentsPlugin.logQueryTaskErrors()) { error("Failed to send %d report(s) to the server!", reports.size()); error("This report(s) has been cached, the cache worker"); error("will retry to upload that again every 5 minutes."); } reportCache.addToCache(reports); } private void warning(String format, Object... args) { plugin.getLogger().warning(String.format(format, args)); } private void error(String format, Object... args) { plugin.getLogger().severe(String.format(format, args)); } }
41.418301
130
0.647941
40b1d2c08eb5fd53b856951bb1a35b6826250cfa
1,166
package io.github.rbxapi.javablox.api.groups; public interface SocialLink { /** * https://groups.roblox.com/docs#!/SocialLinks/get_v1_groups_groupId_social_links * * @param groupId Group ID * @return Links */ String getLinks(double groupId); /** * https://groups.roblox.com/docs#!/SocialLinks/post_v1_groups_groupId_social_links * * @param groupId Group ID * @param request Link * @return Links */ String postLink(double groupId, String request); /** * https://groups.roblox.com/docs#!/SocialLinks/delete_v1_groups_groupId_social_links_socialLinkId * * @param groupId Group ID * @param socialLinkId Social Link ID * @return Status Code */ String removeLink(double groupId, double socialLinkId); /** * https://groups.roblox.com/docs#!/SocialLinks/patch_v1_groups_groupId_social_links_socialLinkId * * @param groupId Group ID * @param socialLinkId Social Link ID * @param request Updated link info * @return Status Code */ String updateLink(double groupId, double socialLinkId, String request); }
29.15
102
0.665523
ef280501940c2d3a6226c3ade1a9929edc081b85
6,337
/** * Copyright (c) 2014 Baidu, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baidu.rigel.biplatform.ma.resource.utils; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.util.StringUtils; import com.baidu.rigel.biplatform.ac.model.OlapElement; import com.baidu.rigel.biplatform.ac.model.Schema; import com.baidu.rigel.biplatform.ma.report.model.ExtendArea; import com.baidu.rigel.biplatform.ma.report.model.ExtendAreaType; import com.baidu.rigel.biplatform.ma.report.model.Item; import com.baidu.rigel.biplatform.ma.report.model.LiteOlapExtendArea; import com.baidu.rigel.biplatform.ma.report.model.ReportDesignModel; import com.baidu.rigel.biplatform.ma.report.model.TimerAreaLogicModel; import com.baidu.rigel.biplatform.ma.report.utils.ReportDesignModelUtils; import com.baidu.rigel.biplatform.ma.resource.ResponseResult; import com.baidu.rigel.biplatform.ma.resource.view.vo.ExtendAreaViewObject; import com.baidu.rigel.biplatform.ma.resource.view.vo.ItemViewObject; import com.google.common.collect.Lists; /** * REST工具类 * * @author zhongyi * * */ public class ResourceUtils { /** * 构建返回结果 * * @param successMessage * @param errorMessage * @param data * @return */ public static ResponseResult getResult(String successMessage, String errorMessage, Object data) { ResponseResult rs = new ResponseResult(); if (data == null) { rs.setStatus(ResponseResult.FAILED); rs.setStatusInfo(errorMessage); } else { rs.setStatus(ResponseResult.SUCCESS); rs.setStatusInfo(successMessage); rs.setData(data); } return rs; } /** * 构建返回结果 * * @param errorMessage * @param errorCode * @return */ public static ResponseResult getErrorResult(String errorMessage, int errorCode) { ResponseResult rs = new ResponseResult(); rs.setStatus(errorCode); rs.setStatusInfo(errorMessage); return rs; } /** * 构建返回结果 * * @param successMessage * @param data * @return */ public static ResponseResult getCorrectResult(String successMessage, Object data) { ResponseResult rs = new ResponseResult(); rs.setStatus(ResponseResult.SUCCESS); rs.setStatusInfo(successMessage); rs.setData(data); return rs; } /** * 构建扩展区ValueObject * @param model * @param area * @return */ public static ExtendAreaViewObject buildValueObject(ReportDesignModel model, ExtendArea area) { if (area == null) { return new ExtendAreaViewObject(); } ExtendAreaViewObject rs = new ExtendAreaViewObject(); String cubeId = area.getCubeId(); if (!StringUtils.hasText(cubeId)) { return new ExtendAreaViewObject(); } Item[] yAxis = area.getLogicModel().getColumns(); rs.setyAxis(buildItemViewObject(model.getSchema(), cubeId, yAxis, null)); Item[] xAxis = area.getLogicModel().getRows(); rs.setxAxis(buildItemViewObject(model.getSchema(), cubeId, xAxis, null)); Item[] sAxis = area.getLogicModel().getSlices(); rs.setsAxis(buildItemViewObject(model.getSchema(), cubeId, sAxis, null)); if (area.getType() == ExtendAreaType.TIME_COMP) { Map<Item, TimerAreaLogicModel.TimeRange> timeItem = ((TimerAreaLogicModel) area.getLogicModel()) .getTimeDimensions(); rs.setxAxis(buildItemViewObject(model.getSchema(), cubeId, timeItem.keySet().toArray(new Item[0]), null)); } if (area.getType() == ExtendAreaType.LITEOLAP) { LiteOlapExtendArea liteOlapArea = (LiteOlapExtendArea) area; Set<String> usedItemOlapIdSet = area.getAllItems().keySet(); Item[] candDims = liteOlapArea.getCandDims().values().toArray(new Item[0]); rs.setCandDims(buildItemViewObject(model.getSchema(), cubeId, candDims, usedItemOlapIdSet)); Item[] candInds = liteOlapArea.getCandInds().values().toArray(new Item[0]); rs.setCandInds(buildItemViewObject(model.getSchema(), cubeId, candInds, usedItemOlapIdSet)); } return rs; } /** * 构建item value object * @param schema * @param cubeId * @param axisItem * @return */ public static List<ItemViewObject> buildItemViewObject(Schema schema, String cubeId, Item[] axisItem, Set<String> usedItemOlapIdSet) { if (axisItem == null || axisItem.length == 0) { return Lists.newArrayList(); } List<ItemViewObject> rs = Lists.newArrayList(); for (Item item : axisItem) { ItemViewObject obj = new ItemViewObject(); obj.setCubeId(cubeId); obj.setId(item.getId()); obj.setOlapElementId(item.getOlapElementId()); obj.setChartType((String) item.getParams().get("chartType")); if (usedItemOlapIdSet != null) { obj.setUsed(usedItemOlapIdSet.contains(item.getOlapElementId())); } OlapElement olapElement = ReportDesignModelUtils.getDimOrIndDefineWithId(schema, cubeId, item.getOlapElementId()); if (olapElement != null) { obj.setCaption(olapElement.getCaption()); obj.setName(olapElement.getName()); rs.add(obj); } } return rs; } }
37.276471
109
0.6279
db8ef88ea5d8a0e299fc1340738770eee739fa79
5,063
package com.github.ryan.data_structure.concurrent.list; import java.util.Arrays; import java.util.concurrent.locks.ReentrantLock; /** * A thread-safe variant of java.util.ArrayList in which all mutative * operations add, set, and so on are implemented by making a fresh * copy of the underlying array. * * This is ordinarily too costly, but may be more efficient * than alternatives when traversal operations vastly outnumber * mutations, and is useful when you cannot or don't want to * synchronize traversals, yet need to preclude interference among * concurrent threads. The "snapshot" style iterator method uses * a reference to the state of the array at the point that the iterator * was created. This array never changes during the lifetime of the * iterator, so interference is impossible and the iterator is * guaranteed not to throw ConcurrentModificationException. * The iterator will not reflect additions, removals, or changes to * the list since the iterator was created. Element-changing * operations on iterators themselves remove, set, and add are not * supported. These methods throw UnsupportedOperationException. * * All elements are permitted, including null. * * Memory consistency effects: * As with other concurrent collections, actions in a thread prior to * placing an object into a CopyOnWriteArrayList happen-before * actions subsequent to the access or removal of that element from * the CopyOnWriteArrayList in another thread. * * @param <E> the type of elements held in this collection */ public class CopyOnWriteArrayList<E> implements List<E> { // The lock protecting all mutators final transient ReentrantLock lock = new ReentrantLock(); // The array, accessed only via getArray/setArray. private transient volatile Object[] array; // Gets the array. Non-private so as to also be accessible // from CopyOnWriteArraySet class. final Object[] getArray() { return array; } final void setArray(Object[] a) { array = a; } // Creates an empty list. public CopyOnWriteArrayList() { setArray(new Object[0]); } /** * Creates a list holding a copy of the given array. * * @param toCopyIn the array (a copy of this array is used as the internal array) * @throws NullPointerException if the specified array is null */ public CopyOnWriteArrayList(E[] toCopyIn) { setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class)); } public int size() { return getArray().length; } public boolean isEmpty() { return size() == 0; } // public boolean contains(Object o) { // Object[] elements = getArray(); // return indexOf(o, elements, 0, elements.length) >= 0; // } public <T> T[] toArray(T[] a) { Object[] elements = getArray(); int len = elements.length; if (a.length < len) { return (T[]) Arrays.copyOf(elements, len, a.getClass()); } else { System.arraycopy(elements, 0, a, 0, len); if (a.length > len) { a[len] = null; } return a; } } private E get(Object[] a, int index) { return (E) a[index]; } // throws IndexOutOfBoundsException // lock-free public E get(int index) { return get(getArray(), index); } /** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return */ public boolean add(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). Returns the element that was removed from the list. * * @throws IndexOutOfBoundsException * @param index * @return */ public E remove(int index) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; E oldValue = get(elements, index); int numMoved = len - index - 1; if (numMoved == 0) { setArray(Arrays.copyOf(elements, len - 1)); } else { Object[] newElements = new Object[len - 1]; System.arraycopy(elements, 0, newElements, 0, index); System.arraycopy(elements, index + 1, newElements, index, numMoved); setArray(newElements); } return oldValue; } finally { lock.unlock(); } } }
32.044304
85
0.619988
6be2be405d2ee13a9c9b657f16a4138a3940e06e
469
package jv16; import javax.swing.*; import java.awt.*; class CarDrawingPanel extends JPanel { public void paint(Graphics g) { g.clearRect(0, 0, getWidth(), getHeight()); g.drawRect(100, 110, 200, 40); g.drawRect(150, 70, 100, 40); g.setColor(Color.RED); g.fillOval(125, 150, 30, 30); g.setColor(Color.BLACK); g.drawOval(245, 150, 30, 30); g.drawLine(50, 180, 350, 180); } }
24.684211
48
0.552239
35d2f6971e5c023455a309f13cae6d50f30dc559
40,363
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Mon Jun 12 11:00:08 UTC 2017"); System.out.println("Mon Jun 12 11:00:08 UTC 2017"); System.out.println("Making a new Entry at Sat Jun 10 11:00:01 UTC 2017"); System.out.println("Sat Jun 10 11:00:01 UTC 2017"); System.out.println("Making a new Entry at Thu Jun 8 11:00:35 UTC 2017"); System.out.println("Thu Jun 8 11:00:35 UTC 2017"); System.out.println("Making a new Entry at Tue Jun 6 11:00:13 UTC 2017"); System.out.println("Tue Jun 6 11:00:13 UTC 2017"); System.out.println("Making a new Entry at Sun Jun 4 11:00:46 UTC 2017"); System.out.println("Sun Jun 4 11:00:46 UTC 2017"); System.out.println("Making a new Entry at Fri Jun 2 11:00:19 UTC 2017"); System.out.println("Fri Jun 2 11:00:19 UTC 2017"); System.out.println("Making a new Entry at Tue May 30 11:00:28 UTC 2017"); System.out.println("Tue May 30 11:00:28 UTC 2017"); System.out.println("Making a new Entry at Sun May 28 11:00:43 UTC 2017"); System.out.println("Sun May 28 11:00:43 UTC 2017"); System.out.println("Making a new Entry at Fri May 26 11:00:21 UTC 2017"); System.out.println("Fri May 26 11:00:21 UTC 2017"); System.out.println("Making a new Entry at Wed May 24 11:00:02 UTC 2017"); System.out.println("Wed May 24 11:00:02 UTC 2017"); System.out.println("Making a new Entry at Mon May 22 11:00:35 UTC 2017"); System.out.println("Mon May 22 11:00:35 UTC 2017"); System.out.println("Making a new Entry at Sat May 20 11:00:07 UTC 2017"); System.out.println("Sat May 20 11:00:07 UTC 2017"); System.out.println("Making a new Entry at Thu May 18 11:00:40 UTC 2017"); System.out.println("Thu May 18 11:00:40 UTC 2017"); System.out.println("Making a new Entry at Tue May 16 11:00:13 UTC 2017"); System.out.println("Tue May 16 11:00:13 UTC 2017"); System.out.println("Making a new Entry at Sun May 14 11:00:02 UTC 2017"); System.out.println("Sun May 14 11:00:02 UTC 2017"); System.out.println("Making a new Entry at Fri May 12 11:00:48 UTC 2017"); System.out.println("Fri May 12 11:00:48 UTC 2017"); System.out.println("Making a new Entry at Wed May 10 11:00:57 UTC 2017"); System.out.println("Wed May 10 11:00:57 UTC 2017"); System.out.println("Making a new Entry at Mon May 8 11:00:25 UTC 2017"); System.out.println("Mon May 8 11:00:25 UTC 2017"); System.out.println("Making a new Entry at Mon May 8 07:49:35 UTC 2017"); System.out.println("Mon May 8 07:49:35 UTC 2017"); System.out.println("Making a new Entry at Mon May 8 07:44:40 UTC 2017"); System.out.println("Mon May 8 07:44:40 UTC 2017"); System.out.println("Making a new Entry at Sat May 6 11:00:19 UTC 2017"); System.out.println("Sat May 6 11:00:19 UTC 2017"); System.out.println("Making a new Entry at Thu May 4 11:00:04 UTC 2017"); System.out.println("Thu May 4 11:00:04 UTC 2017"); System.out.println("Making a new Entry at Tue May 2 11:00:37 UTC 2017"); System.out.println("Tue May 2 11:00:37 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 30 11:00:10 UTC 2017"); System.out.println("Sun Apr 30 11:00:10 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 28 11:00:19 UTC 2017"); System.out.println("Fri Apr 28 11:00:19 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 26 11:00:52 UTC 2017"); System.out.println("Wed Apr 26 11:00:52 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 20 11:00:52 UTC 2017"); System.out.println("Thu Apr 20 11:00:52 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 18 11:00:36 UTC 2017"); System.out.println("Tue Apr 18 11:00:36 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 16 11:00:39 UTC 2017"); System.out.println("Sun Apr 16 11:00:39 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 14 11:00:25 UTC 2017"); System.out.println("Fri Apr 14 11:00:25 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 12 11:00:22 UTC 2017"); System.out.println("Wed Apr 12 11:00:22 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 11:00:38 UTC 2017"); System.out.println("Mon Apr 10 11:00:38 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:56:35 UTC 2017"); System.out.println("Mon Apr 10 09:56:35 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:55:32 UTC 2017"); System.out.println("Mon Apr 10 09:55:32 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:55:04 UTC 2017"); System.out.println("Mon Apr 10 09:55:04 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:39:32 UTC 2017"); System.out.println("Mon Apr 10 09:39:32 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:38:52 UTC 2017"); System.out.println("Mon Apr 10 09:38:52 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:38:24 UTC 2017"); System.out.println("Mon Apr 10 09:38:24 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:36:01 UTC 2017"); System.out.println("Mon Apr 10 09:36:01 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:34:55 UTC 2017"); System.out.println("Mon Apr 10 09:34:55 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:31:13 UTC 2017"); System.out.println("Mon Apr 10 09:31:13 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:30:30 UTC 2017"); System.out.println("Mon Apr 10 09:30:30 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:29:05 UTC 2017"); System.out.println("Mon Apr 10 09:29:05 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:24:21 UTC 2017"); System.out.println("Mon Apr 10 09:24:21 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:24:04 UTC 2017"); System.out.println("Mon Apr 10 09:24:04 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:22:26 UTC 2017"); System.out.println("Mon Apr 10 09:22:26 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:18:38 UTC 2017"); System.out.println("Mon Apr 10 09:18:38 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 09:17:03 UTC 2017"); System.out.println("Mon Apr 10 09:17:03 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //---------------------------------------------------- //Comment added on date:Fri Dec 2 09:45:31 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //Comment added on date:Fri Dec 2 09:55:14 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Dec 2 11:34:52 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Dec 2 11:35:25 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Dec 2 12:32:47 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Dec 5 05:39:41 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Dec 5 05:41:08 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Dec 5 05:41:14 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Dec 5 06:05:33 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Dec 5 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed Dec 7 05:08:34 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed Dec 7 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Dec 9 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun Dec 11 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Dec 13 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu Dec 15 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat Dec 17 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Dec 19 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed Dec 21 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Dec 23 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun Dec 25 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Dec 27 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu Dec 29 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat Dec 31 11:00:16 UTC 2016 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun Jan 1 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Jan 3 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu Jan 5 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat Jan 7 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Jan 9 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed Jan 11 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Jan 13 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun Jan 15 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Jan 17 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu Jan 19 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat Jan 21 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Jan 23 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed Jan 25 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Jan 27 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun Jan 29 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Jan 31 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed Feb 1 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Feb 3 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun Feb 5 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Feb 7 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu Feb 9 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat Feb 11 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Feb 13 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed Feb 15 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Feb 17 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun Feb 19 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Feb 21 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu Feb 23 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat Feb 25 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Feb 27 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed Mar 1 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Apr 11 06:09:20 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Apr 11 06:09:28 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Apr 11 06:09:34 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Apr 11 06:12:12 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Apr 11 06:15:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Apr 11 11:00:55 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu Apr 13 11:00:41 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat Apr 15 11:00:05 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Apr 17 11:00:08 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed Apr 19 11:00:53 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Apr 21 11:00:36 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun Apr 23 11:00:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue Apr 25 11:00:09 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu Apr 27 11:00:36 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat Apr 29 11:00:26 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon May 1 11:00:54 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed May 3 11:00:21 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri May 5 11:00:36 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun May 7 11:00:49 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue May 9 11:00:15 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu May 11 11:00:17 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat May 13 11:00:19 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon May 15 11:00:46 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed May 17 11:00:56 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri May 19 11:00:23 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun May 21 11:00:50 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Tue May 23 11:00:17 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu May 25 11:00:44 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat May 27 11:01:00 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon May 29 11:00:27 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed May 31 11:00:52 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Thu Jun 1 11:00:35 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sat Jun 3 11:00:02 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Mon Jun 5 11:00:29 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Wed Jun 7 11:00:57 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Fri Jun 9 11:00:19 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //---------------------------------------------------- //---------------------------------------------------- //Comment added on date:Sun Jun 11 11:00:51 UTC 2017 //Author: Andrew Woods, Apoorva Rao //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //----------------------------------------------------
47.88019
73
0.562371
ac948e4ab4b08aa96c093ea8cc85926c52bb5339
2,720
package io.emqtt.emqandroidtoolkit.model; import org.eclipse.paho.client.mqttv3.MqttMessage; import android.os.Parcel; import android.os.Parcelable; import io.emqtt.emqandroidtoolkit.util.StringUtil; /** * ClassName: Publication * Desc: * Created by zhiw on 2017/3/23. */ public class Publication implements Parcelable { private String topic; private String payload; private @QoSConstant.QoS int QoS; private boolean isRetained; private String time; public Publication(String topic, String payload, int qoS, boolean isRetained) { this.topic = topic; this.payload = payload; QoS = qoS; this.isRetained = isRetained; this.time = StringUtil.formatNow(); } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public int getQoS() { return QoS; } public void setQoS(int qoS) { QoS = qoS; } public boolean isRetained() { return isRetained; } public void setRetained(boolean retained) { isRetained = retained; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public void setTime() { this.time = StringUtil.formatNow(); } public MqttMessage getMessage() { MqttMessage message = new MqttMessage(); message.setPayload(payload.getBytes()); message.setQos(QoS); message.setRetained(isRetained()); return message; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.topic); dest.writeString(this.payload); dest.writeInt(this.QoS); dest.writeByte(this.isRetained ? (byte) 1 : (byte) 0); dest.writeString(this.time); } protected Publication(Parcel in) { this.topic = in.readString(); this.payload = in.readString(); this.QoS = in.readInt(); this.isRetained = in.readByte() != 0; this.time = in.readString(); } public static final Parcelable.Creator<Publication> CREATOR = new Parcelable.Creator<Publication>() { @Override public Publication createFromParcel(Parcel source) { return new Publication(source); } @Override public Publication[] newArray(int size) { return new Publication[size]; } }; }
21.085271
105
0.609559
8bf7875e6f51a9213602929edf2b2acd191b3430
1,505
package mage.cards.m; import java.util.UUID; import mage.abilities.effects.common.DestroyTargetEffect; import mage.abilities.effects.common.search.SearchLibraryPutInPlayEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.common.FilterLandCard; import mage.filter.common.FilterLandPermanent; import mage.target.TargetPermanent; import mage.target.common.TargetCardInLibrary; /** * * @author markedagain */ public final class MwonvuliAcidMoss extends CardImpl { private static final FilterLandCard filterForest = new FilterLandCard("Forest card"); static { filterForest.add(SubType.FOREST.getPredicate()); } public MwonvuliAcidMoss(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{2}{G}{G}"); // Destroy target land. Search your library for a Forest card and put that card onto the battlefield tapped. Then shuffle your library. this.getSpellAbility().addEffect(new DestroyTargetEffect()); this.getSpellAbility().addTarget(new TargetPermanent(new FilterLandPermanent())); this.getSpellAbility().addEffect(new SearchLibraryPutInPlayEffect(new TargetCardInLibrary(filterForest), true, true)); } private MwonvuliAcidMoss(final MwonvuliAcidMoss card) { super(card); } @Override public MwonvuliAcidMoss copy() { return new MwonvuliAcidMoss(this); } }
32.717391
143
0.750831
e6a05270b1b4c129600fe1b913006cac917c862b
7,910
package org.motechproject.ivr.it; import org.apache.http.HttpStatus; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.motechproject.ivr.domain.CallDetailRecord; import org.motechproject.ivr.domain.Config; import org.motechproject.ivr.domain.Configs; import org.motechproject.ivr.domain.HttpMethod; import org.motechproject.ivr.exception.ConfigNotFoundException; import org.motechproject.ivr.repository.CallDetailRecordDataService; import org.motechproject.ivr.service.ConfigService; import org.motechproject.ivr.service.OutboundCallService; import org.motechproject.testing.osgi.BasePaxIT; import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory; import org.motechproject.testing.osgi.http.SimpleHttpServer; import org.ops4j.pax.exam.ExamFactory; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerSuite; import javax.inject.Inject; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Verify that the OutboundCallService is present & functional. */ @SuppressWarnings("ALL") @RunWith(PaxExam.class) @ExamReactorStrategy(PerSuite.class) @ExamFactory(MotechNativeTestContainerFactory.class) public class OutboundCallServiceBundleIT extends BasePaxIT { @Inject private OutboundCallService outboundCallService; @Inject private CallDetailRecordDataService callDetailRecordDataService; @Inject private ConfigService configService; private Configs backupConfigs; @Before public void backupConfigs() { getLogger().info("backupConfigs"); backupConfigs = configService.allConfigs(); } @After public void restoreConfigs() throws IOException { getLogger().info("restoreConfigs"); configService.updateConfigs(backupConfigs); } @Before @After public void clearDatabase() { getLogger().info("clearDatabase"); callDetailRecordDataService.deleteAll(); } @Test public void verifyServiceFunctional() throws IOException { getLogger().info("verifyServiceFunctional()"); String httpServerURI = SimpleHttpServer.getInstance().start("foo", HttpStatus.SC_OK, "OK"); getLogger().debug("verifyServiceFunctional - We have a server listening at {}", httpServerURI); //Create a config Config config = new Config("conf123", false, null, null, null, null, null, null, HttpMethod.GET, false, httpServerURI, false, null); Configs configs = new Configs(Arrays.asList(config), "conf123"); configService.updateConfigs(configs); Map<String, String> params = new HashMap<>(); outboundCallService.initiateCall(config.getName(), params); List<CallDetailRecord> callDetailRecords = callDetailRecordDataService.retrieveAll(); assertEquals(1, callDetailRecords.size()); assertEquals("conf123", callDetailRecords.get(0).getConfigName()); } @Test public void shouldHandleInvalidServerResponse() throws IOException { getLogger().info("shouldHandleInvalidServerResponse()"); String httpServerURI = SimpleHttpServer.getInstance().start("bar", HttpStatus.SC_BAD_REQUEST, "Eeek!"); getLogger().debug("shouldHandleInvalidServerResponse - We have a server listening at {}", httpServerURI); //Create a config Config config = new Config("conf456", false, null, null, null, null, null, null, HttpMethod.GET, false, httpServerURI,false, null); Configs configs = new Configs(Arrays.asList(config), "conf456"); getLogger().debug("shouldHandleInvalidServerResponse - We create a config {}", config.toString()); configService.updateConfigs(configs); boolean exceptionThrown = false; Map<String, String> params = new HashMap<>(); try { outboundCallService.initiateCall("conf456", params); } catch (RuntimeException e) { exceptionThrown = true; } // We're expecting an exception to be thrown assertTrue(exceptionThrown); //And we're expecting to see one FAILED CDR in the database List<CallDetailRecord> callDetailRecords = callDetailRecordDataService.retrieveAll(); assertEquals(1, callDetailRecords.size()); assertEquals(CallDetailRecord.CALL_FAILED, callDetailRecords.get(0).getCallStatus()); } @Test public void shouldExecuteJsonRequest() throws IOException { getLogger().info("shouldExecuteJsonRequest()"); String httpServerURI = SimpleHttpServer.getInstance().start("foo", HttpStatus.SC_OK, "OK"); getLogger().debug("shouldExecuteJsonRequest - We have a server listening at {}", httpServerURI); //Create a config Config config = new Config("conf789", false, null, null, null, null, null, null, HttpMethod.POST, true, httpServerURI, false, null); Configs configs = new Configs(Arrays.asList(config), "conf789"); configService.updateConfigs(configs); Map<String, String> params = new HashMap<>(); params.put("api_key", "qwerty123"); params.put("message_id", "123123"); params.put("channel", "ivr"); params.put("status_callback_url", "http://someUrl.com"); params.put("subscribers", "[{\"phone\":\"48700123123\",\"language\":null}]"); outboundCallService.initiateCall(config.getName(), params); List<CallDetailRecord> callDetailRecords = callDetailRecordDataService.retrieveAll(); assertEquals(1, callDetailRecords.size()); assertEquals("conf789", callDetailRecords.get(0).getConfigName()); } @Test public void shouldCreateFileWithParamName() throws IOException, URISyntaxException { Path path = Files.createTempFile("temp", ".tmp"); path.toFile().deleteOnExit(); String fileName = path.getFileName().toString(); String uri = path.toUri().toString().replace(fileName, "[fileName]"); Config config = new Config("conf159", false, null, null, null, null, null, null, HttpMethod.GET, false, uri, false, null); List<Config> configList = Arrays.asList(config); Configs configs = new Configs(configList, "conf159"); configService.updateConfigs(configs); Map<String, String> params = new HashMap<>(); params.put("api_key", "qwerty123"); params.put("message_id", "123123"); params.put("channel", "ivr"); params.put("status_callback_url", "http://someUrl.com"); params.put("subscribers", "[{\"phone\":\"48700123123\",\"language\":null}]"); List<String> result = new ArrayList<>(); for (Map.Entry<String, String> entry : params.entrySet()) { result.add(String.format("%s: %s", entry.getKey(), entry.getValue())); } params.put("fileName", fileName); String fileNameParam = String.format("%s: %s", "fileName", fileName); outboundCallService.initiateCall(config.getName(), params); List<String> fileOutput = Files.readAllLines(path); assertTrue(fileOutput.containsAll(result)); assertTrue(!fileOutput.contains(fileNameParam)); } @Test(expected = ConfigNotFoundException.class) public void shouldThrowConfigNotFoundException() { getLogger().info("shouldThrowConfigNotFoundException"); Configs configs = new Configs(); configService.updateConfigs(configs); Map<String, String> params = new HashMap<>(); outboundCallService.initiateCall(params); } }
39.748744
140
0.701264