text
stringlengths
7
1.01M
/* * 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.cache.expiry; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.CachePeekMode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.failure.StopNodeOrHaltFailureHandler; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; import javax.cache.expiry.CreatedExpiryPolicy; import javax.cache.expiry.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC; import static org.apache.ignite.cache.CacheMode.PARTITIONED; /** * Expiration while writing and rebalancing. */ public class IgniteCacheExpireWhileRebalanceTest extends GridCommonAbstractTest { /** */ private static final int ENTRIES = 100000; /** */ private static final int CLUSTER_SIZE = 4; /** * Finder. */ protected static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); /** * {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); ((TcpDiscoverySpi) cfg.getDiscoverySpi()).setIpFinder(IP_FINDER); cfg.setFailureHandler(new StopNodeOrHaltFailureHandler()); CacheConfiguration<Object, Object> ccfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME); ccfg.setAtomicityMode(ATOMIC); ccfg.setCacheMode(PARTITIONED); ccfg.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 1))); cfg.setCacheConfiguration(ccfg); return cfg; } /** * @throws Exception If failed. */ @Test public void testExpireWhileRebalancing() throws Exception { startGridsMultiThreaded(CLUSTER_SIZE); IgniteCache<Object, Object> cache = ignite(0).cache(DEFAULT_CACHE_NAME); CountDownLatch latch = new CountDownLatch(1); new Thread(() -> { for (int i = 1; i <= ENTRIES; i++) { cache.put(i, i); if (i % (ENTRIES / 10) == 0) System.out.println(">>> Entries put: " + i); } latch.countDown(); }).start(); stopGrid(CLUSTER_SIZE - 1); awaitPartitionMapExchange(); startGrid(CLUSTER_SIZE - 1); latch.await(10, TimeUnit.SECONDS); int resultingSize = cache.size(CachePeekMode.PRIMARY); System.out.println(">>> Resulting size: " + resultingSize); assertTrue(resultingSize > 0); // Eviction started assertTrue(resultingSize < ENTRIES * 10 / 11); } /** * {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); } }
package com.ruoyi.acad.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.ruoyi.acad.domain.BaseInfo; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; import java.util.Map; /** * Description:创建基本信息dao<br/> * CreateTime :2020年3月11日上午10:16:07<br/> * CreateUser:ys<br/> */ @Repository public interface BaseInfoMapper extends BaseMapper<BaseInfo> { /** * Description:获取最后一位ID * CreateTime:2020年3月23日下午3:42:36 * @return * @throws Exception */ Integer selectMaxId() throws Exception; /** * 根据院士姓名模糊查询院士编码列表 * @param name * @return */ @Select("SELECT acad_id FROM acad_base_info WHERE cn_name LIKE '%${name}%' or en_name LIKE '%${name}%' or real_name LIKE '%${name}%' and del_flag = 1;") List<Integer> getAcadListByName(@Param("name") String name); /** * 删除院士信息~删除标记0-已删除,1-未删除 * @param acadId * @param userId * @param deleteTime * @return */ @Update("UPDATE acad_base_info SET del_flag = 0,del_user_id=#{userId},del_datetime=#{deleteTime} WHERE acad_id = #{acadId};") int deleteBaseInfo(@Param("acadId") Integer acadId,@Param("userId") Long userId,@Param("deleteTime") Date deleteTime); @Select("select acad_id as acadId,\n" + "\n" + "case \n" + "\n" + "when real_name is not null and real_name !='' then real_name \n" + "when en_name is not null and en_name !='' then en_name \n" + "when cn_name is not null and cn_name !='' then cn_name\n" + "end acadName\n" + "\n" + "from acad_base_info where acad_id in(${acadId})") List<Map<String,Object>> getAcadNameByAcadList(@Param("acadId") String acadId); }
/* * Copyright (C) 2007 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.example.android.apis.app; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.os.Parcel; import android.util.Log; import android.widget.Toast; // Need the following import to get access to the app resources, since this // class is in a sub-package. import com.example.android.apis.R; /** * This is an example of implementing an application service that runs locally * in the same process as the application. The {@link LocalServiceController} * and {@link LocalServiceBinding} classes show how to interact with the * service. * * <p>Notice the use of the {@link NotificationManager} when interesting things * happen in the service. This is generally how background services should * interact with the user, rather than doing something more disruptive such as * calling startActivity(). */ public class LocalService extends Service { private NotificationManager mNM; /** * Class for clients to access. Because we know this service always * runs in the same process as its clients, we don't need to deal with * IPC. */ public class LocalBinder extends Binder { LocalService getService() { return LocalService.this; } } @Override public void onCreate() { mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); // Display a notification about us starting. We put an icon in the status bar. showNotification(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("LocalService", "Received start id " + startId + ": " + intent); // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } @Override public void onDestroy() { // Cancel the persistent notification. mNM.cancel(R.string.local_service_started); // Tell the user we stopped. Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show(); } @Override public IBinder onBind(Intent intent) { return mBinder; } // This is the object that receives interactions from clients. See // RemoteService for a more complete example. private final IBinder mBinder = new LocalBinder(); /** * Show a notification while this service is running. */ private void showNotification() { // In this sample, we'll use the same text for the ticker and the expanded notification CharSequence text = getText(R.string.local_service_started); // Set the icon, scrolling text and timestamp Notification notification = new Notification(R.drawable.stat_sample, text, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, LocalServiceController.class), 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, getText(R.string.local_service_label), text, contentIntent); // Send the notification. // We use a layout id because it is a unique number. We use it later to cancel. mNM.notify(R.string.local_service_started, notification); } }
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.metrics.impl; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.metrics.MetricOptions; /** * Lines of Code. See the <a href="https://{pmd.website.baseurl}/pmd_java_metrics_index.html">documentation site</a>. * * @author Clément Fournier * @see NcssMetric * @since June 2017 */ public final class LocMetric { public static final class LocOperationMetric extends AbstractJavaOperationMetric { @Override public boolean supports(ASTMethodOrConstructorDeclaration node) { return true; } @Override public double computeFor(ASTMethodOrConstructorDeclaration node, MetricOptions options) { return 1 + node.getEndLine() - node.getBeginLine(); } } public static final class LocClassMetric extends AbstractJavaClassMetric { @Override public boolean supports(ASTAnyTypeDeclaration node) { return true; } @Override public double computeFor(ASTAnyTypeDeclaration node, MetricOptions options) { return 1 + node.getEndLine() - node.getBeginLine(); } } }
package com.tx.base.utils; import lombok.Data; /** * @description: --通用返回类 * @author:Bing * @date:2021/12/2 11:18 * @version:1.0 */ @Data public class CommonResult<T> { private long code; private String message; private T data; public CommonResult(long code, String message, T data) { this.code = code; this.message = message; this.data = data; } /** * 成功返回 * @param <T> * @return */ public static <T> CommonResult<T> success() { return success((T) null); } /** * 成功返回,自定义数据 * @param data * @param <T> * @return */ public static <T> CommonResult<T> success(T data) { return new CommonResult<T>(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMessage(), data); } /** * 成功返回自定义提示信息 * @param message * @param data * @param <T> * @return */ public static <T> CommonResult<T> success(String message, T data) { return new CommonResult<T>(ResultCodeEnum.SUCCESS.getCode(), message, data); } /** * 失败返回 * @param <T> * @return */ public static <T> CommonResult<T> failed() { return failed(ResultCodeEnum.FAILED); } /** * 失败返回自定义枚举 * @param resultCodeEnum * @param <T> * @return */ public static <T> CommonResult<T> failed(ResultCodeEnum resultCodeEnum) { return new CommonResult<T>(resultCodeEnum.getCode(), resultCodeEnum.getMessage(), null); } /** * 失败返回自定义提示信息 * @param message * @param <T> * @return */ public static <T> CommonResult<T> failed(String message) { return new CommonResult<T>(ResultCodeEnum.FAILED.getCode(), message, null); } /** * 失败返回自定义提示信息及返回值 * @param message * @param data * @param <T> * @return */ public static <T> CommonResult<T> failed(String message, T data) { return new CommonResult<T>(ResultCodeEnum.FAILED.getCode(), message, data); } /** * 参数验证失败返回 * @param <T> * @return */ public static <T> CommonResult<T> validateFailed() { return failed(ResultCodeEnum.VALIDATE_FAILED); } /** * 参数验证失败自定义提示信息返回 * @param <T> * @return */ public static <T> CommonResult<T> validateFailed(String message) { return new CommonResult<T>(ResultCodeEnum.VALIDATE_FAILED.getCode(), message, null); } /** * 参数验证失败自定义返回数据 * @param data * @param <T> * @return */ public static <T> CommonResult<T> validateFailed(T data) { return new CommonResult<T>(ResultCodeEnum.VALIDATE_FAILED.getCode(), ResultCodeEnum.VALIDATE_FAILED.getMessage(), data); } /** * 定制化提示,给全局异常用 * @param code * @param message * @param data * @param <T> * @return */ public static <T> CommonResult<T> custom(Long code, String message) { return custom(code, message, null); } /** * 定制化提示,给全局异常用 * @param code * @param message * @param data * @param <T> * @return */ public static <T> CommonResult<T> custom(Long code, String message, T data) { return new CommonResult<T>(code, message, data); } }
package com.xmomen.module.base.entity.mapper; import com.xmomen.framework.mybatis.mapper.MybatisMapper; import com.xmomen.module.base.entity.CdContract; import com.xmomen.module.base.entity.CdContractExample; import org.apache.ibatis.annotations.Param; public interface CdContractMapper extends MybatisMapper { int countByExample(CdContractExample example); int deleteByExample(CdContractExample example); int insertSelective(CdContract record); int updateByExampleSelective(@Param("record") CdContract record, @Param("example") CdContractExample example); }
package com.jetbrains.edu.learning.settings; import com.intellij.openapi.options.UnnamedConfigurable; public interface StudyOptionsProvider extends UnnamedConfigurable { }
/** * 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.contrib.index.example; import java.io.IOException; import org.apache.hadoop.contrib.index.mapred.DocumentAndOp; import org.apache.hadoop.contrib.index.mapred.DocumentID; import org.apache.hadoop.contrib.index.mapred.ILocalAnalysis; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; /** * Identity local analysis maps inputs directly into outputs. */ public class IdentityLocalAnalysis implements ILocalAnalysis<DocumentID, DocumentAndOp> { /* (non-Javadoc) * @see org.apache.hadoop.mapred.Mapper#map(java.lang.Object, java.lang.Object, org.apache.hadoop.mapred.OutputCollector, org.apache.hadoop.mapred.Reporter) */ public void map(DocumentID key, DocumentAndOp value, OutputCollector<DocumentID, DocumentAndOp> output, Reporter reporter) throws IOException { output.collect(key, value); } /* (non-Javadoc) * @see org.apache.hadoop.mapred.JobConfigurable#configure(org.apache.hadoop.mapred.JobConf) */ public void configure(JobConf job) { } /* (non-Javadoc) * @see org.apache.hadoop.io.Closeable#close() */ public void close() throws IOException { } }
package com.atlassian.db.replica.internal.util; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * Copyright (c) 2005 Brian Goetz and Tim Peierls * Released under the Creative Commons Attribution License * (http://creativecommons.org/licenses/by/2.5) * Official home: http://www.jcip.net * * Any republication or derived work distributed in source code form * must include this copyright and license notice. */ /** * The class to which this annotation is applied is thread-safe. This means that * no sequences of accesses (reads and writes to public fields, calls to public methods) * may put the object into an invalid state, regardless of the interleaving of those actions * by the runtime, and without requiring any additional synchronization or coordination on the * part of the caller. */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ThreadSafe { }
/* * MIT License * * Copyright (c) 2021 MASES s.r.l. * * 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. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.windows; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.windows.PropertyMetadata; import system.windows.DependencyProperty; /** * The base .NET class managing System.Windows.DependencyPropertyKey, WindowsBase, Version=5.0.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. Extends {@link NetObject}. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.DependencyPropertyKey" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.DependencyPropertyKey</a> */ public class DependencyPropertyKey extends NetObject { /** * Fully assembly qualified name: WindowsBase, Version=5.0.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 */ public static final String assemblyFullName = "WindowsBase, Version=5.0.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; /** * Assembly name: WindowsBase */ public static final String assemblyShortName = "WindowsBase"; /** * Qualified class name: System.Windows.DependencyPropertyKey */ public static final String className = "System.Windows.DependencyPropertyKey"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } public DependencyPropertyKey(Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link DependencyPropertyKey}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link DependencyPropertyKey} instance * @throws java.lang.Throwable in case of error during cast operation */ public static DependencyPropertyKey cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new DependencyPropertyKey(from.getJCOInstance()); } // Constructors section public DependencyPropertyKey() throws Throwable { } // Methods section public void OverrideMetadata(NetType forType, PropertyMetadata typeMetadata) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.NotSupportedException, system.ObjectDisposedException, system.RankException, system.ArrayTypeMismatchException, system.FormatException, system.MulticastNotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("OverrideMetadata", forType == null ? null : forType.getJCOInstance(), typeMetadata == null ? null : typeMetadata.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Properties section public DependencyProperty getDependencyProperty() throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject val = (JCObject)classInstance.Get("DependencyProperty"); return new DependencyProperty(val); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Instance Events section }
package ru.job4j.todolist.servlets; import org.json.JSONObject; import org.json.JSONArray; import ru.job4j.todolist.logic.Service; import ru.job4j.todolist.logic.ServiceInterface; import ru.job4j.todolist.models.Task; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.List; /** * the servlet processes the loading tasks to the table on the index page. */ public class LoadTableServlet extends HttpServlet { /** * the instance of the Service class. */ private final ServiceInterface service = Service.getInstance(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<Task> tasks = this.service.getAll(); resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); PrintWriter writer = new PrintWriter(resp.getOutputStream()); JSONArray todoTable = new JSONArray(); for (Task task : tasks) { JSONObject json = new JSONObject(); json.put("id", task.getId()); json.put("name", task.getName()); json.put("desc", task.getDesc()); json.put("created", new Date(task.getCreated().getTimeInMillis())); json.put("done", task.isDone()); todoTable.put(json); } writer.append(todoTable.toString()); writer.flush(); } }
/* * Licensed to David Pilato (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Author 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 fr.pilato.elasticsearch.crawler.fs.service; import fr.pilato.elasticsearch.crawler.fs.beans.Doc; public interface FsCrawlerDocumentService extends FsCrawlerService { /** * Create a schema for the dataset. This is called when the service starts * @throws Exception in case of error */ void createSchema() throws Exception; /** * Send a document to the target service * @param index Index name * @param id Document id * @param doc Document to index * @param pipeline Pipeline (can be null) */ void index(String index, String id, Doc doc, String pipeline); /** * Send a Raw Json to the target service * @param index Index name * @param id Document ID * @param json Document to index * @param pipeline Pipeline (can be null) */ void indexRawJson(String index, String id, String json, String pipeline); }
package org.saiku.web.rest.resources; import org.saiku.repository.IRepositoryObject; import java.util.List; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; public interface ISaikuRepository { /** * Get Saved Queries. * @return A list of SavedQuery Objects. */ @GET @Produces({ "application/json" }) List<IRepositoryObject> getRepository( @QueryParam("path") String path, @QueryParam("type") String type); /** * Load a resource. * @param file - The name of the repository file to load. * @return A Repository File Object. */ @GET @Produces({ "text/plain" }) @Path("/resource") Response getResource(@QueryParam("file") String file); /** * Save a resource. * @param file - The name of the repository file to load. * @param content - The content to save. * @return Status */ @POST @Path("/resource") Response saveResource(@FormParam("file") String file, @FormParam("content") String content); /** * Delete a resource. * @param file - The name of the repository file to load. * @return Status */ @DELETE @Path("/resource") Response deleteResource(@QueryParam("file") String file); }
/************************************************************************** * alpha-Forms: self-editable formulars in form of an active document * (originally for the alpha-Flow project) * ============================================== * Copyright (C) 2009-2012 by * - Christoph P. Neumann (http://www.chr15t0ph.de) * - Florian Wagner ************************************************************************** * 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. ************************************************************************** * $Id$ *************************************************************************/ package alpha.forms.form.event; import java.util.ArrayList; import java.util.List; import alpha.forms.form.AlphaForm; import alpha.forms.form.util.AlphaFormProvider; import alpha.forms.widget.model.FormWidget; /** * The Class DefaultEvent. */ public class DefaultEvent implements Event { /** The source. */ protected FormWidget source; /** The form. */ protected AlphaForm form; /** The actions. */ protected List<Action> actions = new ArrayList<Action>(); /** The is propagation stopped. */ protected boolean isPropagationStopped = false; /** * Instantiates a new default event. * * @param source * the source * @param form * the form */ public DefaultEvent(final FormWidget source, final AlphaForm form) { this.source = source; this.form = form; } /* * (non-Javadoc) * * @see alpha.forms.form.event.Event#getSource() */ @Override public FormWidget getSource() { return this.source; } /* * (non-Javadoc) * * @see alpha.forms.form.event.Event#getAlphaForm() */ @Override public AlphaForm getAlphaForm() { return AlphaFormProvider.getForm(); } /* * (non-Javadoc) * * @see alpha.forms.form.event.Event#stopPropagation() */ @Override public void stopPropagation() { this.isPropagationStopped = true; } /* * (non-Javadoc) * * @see * alpha.forms.form.event.Event#addAction(alpha.forms.form.event.Action) */ @Override public void addAction(final Action action) { this.actions.add(action); } /* * (non-Javadoc) * * @see * alpha.forms.form.event.Event#removeAction(alpha.forms.form.event.Action) */ @Override public void removeAction(final Action action) { this.actions.remove(action); } /** * Gets the actions. * * @return the actions */ public List<Action> getActions() { return this.actions; } /* * (non-Javadoc) * * @see alpha.forms.form.event.Event#fire() */ @Override public void fire() { for (final Action a : this.actions) { if (!this.isPropagationStopped) { a.execute(this); } } } /* * (non-Javadoc) * * @see alpha.forms.form.event.Event#createMemento() */ @Override public EventMemento createMemento() { final EventMemento ev = new EventMemento(); for (final Action a : this.actions) { ev.addAction(a.createMemento()); } return ev; } /* * (non-Javadoc) * * @see * alpha.forms.form.event.Event#setMemento(alpha.forms.form.event.EventMemento * ) */ @Override public void setMemento(final EventMemento m) { this.actions.clear(); for (final ActionMemento am : m.getActions()) { final Action a = ActionFactory.getInstance().createScriptedAction(); a.setMemento(am); this.actions.add(a); } } }
package org.batfish.minesweeper.smt; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.microsoft.z3.ArithExpr; import com.microsoft.z3.BitVecExpr; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; import com.microsoft.z3.Solver; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; import org.batfish.datamodel.BgpActivePeerConfig; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.HeaderSpace; import org.batfish.datamodel.Interface; import org.batfish.datamodel.Ip; import org.batfish.datamodel.IpAccessList; import org.batfish.datamodel.IpWildcard; import org.batfish.datamodel.Prefix; import org.batfish.datamodel.PrefixRange; import org.batfish.datamodel.RoutingProtocol; import org.batfish.datamodel.StaticRoute; import org.batfish.datamodel.SubRange; import org.batfish.datamodel.acl.MatchHeaderSpace; import org.batfish.datamodel.questions.smt.BgpDecisionVariable; import org.batfish.datamodel.routing_policy.RoutingPolicy; import org.batfish.datamodel.routing_policy.expr.MatchProtocol; import org.batfish.datamodel.routing_policy.statement.If; import org.batfish.datamodel.routing_policy.statement.Statement; import org.batfish.datamodel.routing_policy.statement.Statements; import org.batfish.minesweeper.CommunityVar; import org.batfish.minesweeper.Graph; import org.batfish.minesweeper.GraphEdge; import org.batfish.minesweeper.OspfType; import org.batfish.minesweeper.Protocol; import org.batfish.minesweeper.collections.Table2; import org.batfish.minesweeper.utils.IpSpaceMayIntersectWildcard; /** * A class responsible for building a symbolic encoding of the network for a particular packet. The * encoding is heavily specialized based on the PolicyQuotient class, and what optimizations it * indicates are possible. * * @author Ryan Beckett */ class EncoderSlice { private static final int BITS = 0; private Encoder _encoder; private String _sliceName; private HeaderSpace _headerSpace; private Optimizations _optimizations; private LogicalGraph _logicalGraph; private SymbolicDecisions _symbolicDecisions; private SymbolicPacket _symbolicPacket; private Map<GraphEdge, BoolExpr> _inboundAcls; private Map<GraphEdge, BoolExpr> _outboundAcls; private Table2<String, GraphEdge, BoolExpr> _forwardsAcross; private List<SymbolicRoute> _allSymbolicRoutes; private Map<String, SymbolicRoute> _ospfRedistributed; private Table2<String, Protocol, Set<Prefix>> _originatedNetworks; /** * Create a new encoding slice * * @param enc The parent encoder object * @param h The packet headerspace of interest * @param graph The network graph * @param sliceName The name of this slice */ EncoderSlice(Encoder enc, HeaderSpace h, Graph graph, String sliceName) { _encoder = enc; _sliceName = sliceName; _headerSpace = h; _allSymbolicRoutes = new ArrayList<>(); _optimizations = new Optimizations(this); _logicalGraph = new LogicalGraph(graph); _symbolicDecisions = new SymbolicDecisions(); _symbolicPacket = new SymbolicPacket(enc.getCtx(), enc.getId(), _sliceName); enc.getAllVariables().put(_symbolicPacket.getDstIp().toString(), _symbolicPacket.getDstIp()); enc.getAllVariables().put(_symbolicPacket.getSrcIp().toString(), _symbolicPacket.getSrcIp()); enc.getAllVariables() .put(_symbolicPacket.getDstPort().toString(), _symbolicPacket.getDstPort()); enc.getAllVariables() .put(_symbolicPacket.getSrcPort().toString(), _symbolicPacket.getSrcPort()); enc.getAllVariables() .put(_symbolicPacket.getIcmpCode().toString(), _symbolicPacket.getIcmpCode()); enc.getAllVariables() .put(_symbolicPacket.getIcmpType().toString(), _symbolicPacket.getIcmpType()); enc.getAllVariables().put(_symbolicPacket.getTcpAck().toString(), _symbolicPacket.getTcpAck()); enc.getAllVariables().put(_symbolicPacket.getTcpCwr().toString(), _symbolicPacket.getTcpCwr()); enc.getAllVariables().put(_symbolicPacket.getTcpEce().toString(), _symbolicPacket.getTcpEce()); enc.getAllVariables().put(_symbolicPacket.getTcpFin().toString(), _symbolicPacket.getTcpFin()); enc.getAllVariables().put(_symbolicPacket.getTcpPsh().toString(), _symbolicPacket.getTcpPsh()); enc.getAllVariables().put(_symbolicPacket.getTcpRst().toString(), _symbolicPacket.getTcpRst()); enc.getAllVariables().put(_symbolicPacket.getTcpSyn().toString(), _symbolicPacket.getTcpSyn()); enc.getAllVariables().put(_symbolicPacket.getTcpUrg().toString(), _symbolicPacket.getTcpUrg()); enc.getAllVariables() .put(_symbolicPacket.getIpProtocol().toString(), _symbolicPacket.getIpProtocol()); _inboundAcls = new HashMap<>(); _outboundAcls = new HashMap<>(); _forwardsAcross = new Table2<>(); _ospfRedistributed = new HashMap<>(); _originatedNetworks = new Table2<>(); initOptimizations(); initOriginatedPrefixes(); initRedistributionProtocols(); initVariables(); initAclFunctions(); initForwardingAcross(); } // Add a variable to the encoding void add(BoolExpr e) { _encoder.add(e); } // Symbolic mkFalse value BoolExpr mkFalse() { return _encoder.mkFalse(); } // Symbolic true value BoolExpr mkTrue() { return _encoder.mkTrue(); } // Create a symbolic boolean BoolExpr mkBool(boolean val) { return _encoder.mkBool(val); } // Symbolic boolean negation BoolExpr mkNot(BoolExpr e) { return _encoder.mkNot(e); } // Symbolic boolean disjunction BoolExpr mkOr(BoolExpr... vals) { return _encoder.mkOr(vals); } // Symbolic boolean implication BoolExpr mkImplies(BoolExpr e1, BoolExpr e2) { return getCtx().mkImplies(e1, e2); } // Symbolic greater than BoolExpr mkGt(Expr e1, Expr e2) { return _encoder.mkGt(e1, e2); } // Symbolic arithmetic subtraction ArithExpr mkSub(ArithExpr e1, ArithExpr e2) { return _encoder.mkSub(e1, e2); } // Symbolic if-then-else for booleans BoolExpr mkIf(BoolExpr cond, BoolExpr case1, BoolExpr case2) { return _encoder.mkIf(cond, case1, case2); } // Symbolic if-then-else for bit vectors BitVecExpr mkIf(BoolExpr cond, BitVecExpr case1, BitVecExpr case2) { return (BitVecExpr) _encoder.getCtx().mkITE(cond, case1, case2); } // Symbolic if-then-else for arithmetic ArithExpr mkIf(BoolExpr cond, ArithExpr case1, ArithExpr case2) { return _encoder.mkIf(cond, case1, case2); } // Symbolic equality BoolExpr mkEq(Expr e1, Expr e2) { return getCtx().mkEq(e1, e2); } // Create a symbolic integer ArithExpr mkInt(long l) { return _encoder.mkInt(l); } // Symbolic boolean conjunction BoolExpr mkAnd(BoolExpr... vals) { return _encoder.mkAnd(vals); } // Symbolic greater than or equal BoolExpr mkGe(Expr e1, Expr e2) { return _encoder.mkGe(e1, e2); } // Symbolic less than or equal BoolExpr mkLe(Expr e1, Expr e2) { return _encoder.mkLe(e1, e2); } // Symbolic less than BoolExpr mkLt(Expr e1, Expr e2) { return _encoder.mkLt(e1, e2); } // Symbolic arithmetic addition ArithExpr mkSum(ArithExpr e1, ArithExpr e2) { return _encoder.mkSum(e1, e2); } // Check equality of expressions with null checking BoolExpr safeEq(Expr x, Expr value) { if (x == null) { return mkTrue(); } return mkEq(x, value); } // Check for equality of symbolic enums after accounting for null <T> BoolExpr safeEqEnum(SymbolicEnum<T> x, T value) { if (x == null) { return mkTrue(); } return x.checkIfValue(value); } // Check for equality of symbolic enums after accounting for null <T> BoolExpr safeEqEnum(SymbolicEnum<T> x, SymbolicEnum<T> y) { if (x == null) { return mkTrue(); } return x.mkEq(y); } /* * Initialize boolean expressions to represent ACLs on each interface. */ private void initAclFunctions() { for (Entry<String, List<GraphEdge>> entry : getGraph().getEdgeMap().entrySet()) { String router = entry.getKey(); List<GraphEdge> edges = entry.getValue(); for (GraphEdge ge : edges) { Interface i = ge.getStart(); IpAccessList outbound = i.getOutgoingFilter(); if (outbound != null) { String outName = String.format( "%d_%s_%s_%s_%s_%s", _encoder.getId(), _sliceName, router, i.getName(), "OUTBOUND", outbound.getName()); BoolExpr outAcl = getCtx().mkBoolConst(outName); BoolExpr outAclFunc = computeACL(outbound); add(mkEq(outAcl, outAclFunc)); _outboundAcls.put(ge, outAcl); } IpAccessList inbound = i.getIncomingFilter(); if (inbound != null) { String inName = String.format( "%d_%s_%s_%s_%s_%s", _encoder.getId(), _sliceName, router, i.getName(), "INBOUND", inbound.getName()); BoolExpr inAcl = getCtx().mkBoolConst(inName); BoolExpr inAclFunc = computeACL(inbound); add(mkEq(inAcl, inAclFunc)); _inboundAcls.put(ge, inAcl); } } } } /* * Initialize boolean expressions to represent that traffic sent along * and edge will reach the other side of the edge. */ private void initForwardingAcross() { _symbolicDecisions .getDataForwarding() .forEach( (router, edge, var) -> { BoolExpr inAcl; if (edge.getEnd() == null) { inAcl = mkTrue(); } else { GraphEdge ge = getGraph().getOtherEnd().get(edge); inAcl = _inboundAcls.get(ge); if (inAcl == null) { inAcl = mkTrue(); } } _forwardsAcross.put(router, edge, mkAnd(var, inAcl)); }); } /* * Initialize the map of redistributed protocols. */ private void initRedistributionProtocols() { for (Entry<String, Configuration> entry : getGraph().getConfigurations().entrySet()) { String router = entry.getKey(); Configuration conf = entry.getValue(); for (Protocol proto : getProtocols().get(router)) { Set<Protocol> redistributed = new HashSet<>(); redistributed.add(proto); _logicalGraph.getRedistributedProtocols().put(router, proto, redistributed); RoutingPolicy pol = Graph.findCommonRoutingPolicy(conf, proto); if (pol != null) { Set<Protocol> ps = getGraph().findRedistributedProtocols(conf, pol, proto); for (Protocol p : ps) { // Make sure there is actually a routing process for the other protocol // For example, it might get sliced away if not relevant boolean isProto = getProtocols().get(router).contains(p); if (isProto) { redistributed.add(p); } } } } } } /* * Returns are relevant logical edges for a given router and protocol. */ private Set<LogicalEdge> collectAllImportLogicalEdges( String router, Configuration conf, Protocol proto) { Set<LogicalEdge> eList = new HashSet<>(); List<ArrayList<LogicalEdge>> les = _logicalGraph.getLogicalEdges().get(router, proto); assert (les != null); for (ArrayList<LogicalEdge> es : les) { for (LogicalEdge le : es) { if (_logicalGraph.isEdgeUsed(conf, proto, le) && le.getEdgeType() == EdgeType.IMPORT) { eList.add(le); } } } return eList; } /* * Converts a list of prefixes into a boolean expression that determines * if they are relevant for the symbolic packet. */ BoolExpr relevantOrigination(Set<Prefix> prefixes) { BoolExpr acc = mkFalse(); for (Prefix p : prefixes) { acc = mkOr(acc, isRelevantFor(p, _symbolicPacket.getDstIp())); } return acc; } /* * Get the added cost out an interface for a given routing protocol. */ private Integer addedCost(Protocol proto, GraphEdge ge) { if (proto.isOspf()) { return ge.getStart().getOspfCost(); } return 1; } /* * Determine if an interface is active for a particular protocol. */ private BoolExpr interfaceActive(Interface iface, Protocol proto) { BoolExpr active = mkBool(iface.getActive()); if (proto.isOspf()) { active = mkAnd(active, mkBool(iface.getOspfEnabled())); } return active; } /* * Checks if a prefix could possible be relevant for encoding */ boolean relevantPrefix(Prefix p) { if (_headerSpace.getDstIps() == null) { return true; } return new IpSpaceMayIntersectWildcard(IpWildcard.create(p), ImmutableMap.of()) .visit(_headerSpace.getDstIps()); } /* * Check if a prefix range match is applicable for the packet destination * Ip address, given the prefix length variable. */ BoolExpr isRelevantFor(ArithExpr prefixLen, PrefixRange range) { Prefix p = range.getPrefix(); SubRange r = range.getLengthRange(); long pfx = p.getStartIp().asLong(); int len = p.getPrefixLength(); int lower = r.getStart(); int upper = r.getEnd(); // well formed prefix assert (p.getPrefixLength() <= lower && lower <= upper); BoolExpr lowerBitsMatch = firstBitsEqual(_symbolicPacket.getDstIp(), pfx, len); if (lower == upper) { BoolExpr equalLen = mkEq(prefixLen, mkInt(lower)); return mkAnd(equalLen, lowerBitsMatch); } else { BoolExpr lengthLowerBound = mkGe(prefixLen, mkInt(lower)); BoolExpr lengthUpperBound = mkLe(prefixLen, mkInt(upper)); return mkAnd(lengthLowerBound, lengthUpperBound, lowerBitsMatch); } } private BoolExpr firstBitsEqual(BitVecExpr x, long y, int n) { assert (n >= 0 && n <= 32); if (n == 0) { return mkTrue(); } int m = 0; for (int i = 0; i < n; i++) { m |= (1 << (31 - i)); } BitVecExpr mask = getCtx().mkBV(m, 32); BitVecExpr val = getCtx().mkBV(y, 32); return mkEq(getCtx().mkBVAND(x, mask), getCtx().mkBVAND(val, mask)); } BoolExpr isRelevantFor(Prefix p, BitVecExpr be) { long pfx = p.getStartIp().asLong(); return firstBitsEqual(be, pfx, p.getPrefixLength()); } @Nullable SymbolicRoute getBestNeighborPerProtocol(String router, Protocol proto) { if (_optimizations.getSliceHasSingleProtocol().contains(router)) { return getSymbolicDecisions().getBestNeighbor().get(router); } else { return getSymbolicDecisions().getBestNeighborPerProtocol().get(router, proto); } } /* * Initializes the logical graph edges for the protocol-centric view */ private void buildEdgeMap() { for (Entry<String, List<Protocol>> entry : getProtocols().entrySet()) { String router = entry.getKey(); for (Protocol p : entry.getValue()) { _logicalGraph.getLogicalEdges().put(router, p, new ArrayList<>()); } } } /* * Initialize variables representing if a router chooses * to use a particular interface for control-plane forwarding */ private void addChoiceVariables() { for (String router : getGraph().getRouters()) { Configuration conf = getGraph().getConfigurations().get(router); Map<Protocol, Map<LogicalEdge, BoolExpr>> map = new HashMap<>(); _symbolicDecisions.getChoiceVariables().put(router, map); for (Protocol proto : getProtocols().get(router)) { Map<LogicalEdge, BoolExpr> edgeMap = new HashMap<>(); map.put(proto, edgeMap); for (LogicalEdge e : collectAllImportLogicalEdges(router, conf, proto)) { String chName = e.getSymbolicRecord().getName() + "_choice"; BoolExpr choiceVar = getCtx().mkBoolConst(chName); getAllVariables().put(choiceVar.toString(), choiceVar); edgeMap.put(e, choiceVar); } } } } /* * Initalizes variables representing the control plane and * data plane final forwarding decisions */ private void addForwardingVariables() { for (Entry<String, List<GraphEdge>> entry : getGraph().getEdgeMap().entrySet()) { String router = entry.getKey(); List<GraphEdge> edges = entry.getValue(); for (GraphEdge edge : edges) { String iface = edge.getStart().getName(); String cName = _encoder.getId() + "_" + _sliceName + "CONTROL-FORWARDING_" + router + "_" + iface; BoolExpr cForward = getCtx().mkBoolConst(cName); getAllVariables().put(cForward.toString(), cForward); _symbolicDecisions.getControlForwarding().put(router, edge, cForward); // Don't add data forwarding variable for abstract edge if (!edge.isAbstract()) { String dName = _encoder.getId() + "_" + _sliceName + "DATA-FORWARDING_" + router + "_" + iface; BoolExpr dForward = getCtx().mkBoolConst(dName); getAllVariables().put(dForward.toString(), dForward); _symbolicDecisions.getDataForwarding().put(router, edge, dForward); } } } } /* * Initialize variables representing the best choice both for * each protocol as well as for the router as a whole */ private void addBestVariables() { for (Entry<String, List<Protocol>> entry : getProtocols().entrySet()) { String router = entry.getKey(); List<Protocol> allProtos = entry.getValue(); // Overall best for (int len = 0; len <= BITS; len++) { String name = String.format( "%d_%s%s_%s_%s_%s", _encoder.getId(), _sliceName, router, "OVERALL", "BEST", "None"); String historyName = name + "_history"; SymbolicEnum<Protocol> h = new SymbolicEnum<>(this, allProtos, historyName); SymbolicRoute evBest = new SymbolicRoute(this, name, router, Protocol.BEST, _optimizations, h, false); getAllSymbolicRecords().add(evBest); _symbolicDecisions.getBestNeighbor().put(router, evBest); } // Best per protocol if (!_optimizations.getSliceHasSingleProtocol().contains(router)) { for (Protocol proto : getProtocols().get(router)) { String name = String.format( "%d_%s%s_%s_%s_%s", _encoder.getId(), _sliceName, router, proto.name(), "BEST", "None"); // String historyName = name + "_history"; // SymbolicEnum<Protocol> h = new SymbolicEnum<>(this, allProtos, historyName); for (int len = 0; len <= BITS; len++) { SymbolicRoute evBest = new SymbolicRoute(this, name, router, proto, _optimizations, null, false); getAllSymbolicRecords().add(evBest); _symbolicDecisions.getBestNeighborPerProtocol().put(router, proto, evBest); } } } } } /* * Initialize all control-plane message symbolic records. * Also maps each logical graph edge to its opposite edge. */ private void addSymbolicRecords() { Map<String, Map<Protocol, Map<GraphEdge, ArrayList<LogicalEdge>>>> importInverseMap = new HashMap<>(); Map<String, Map<Protocol, Map<GraphEdge, ArrayList<LogicalEdge>>>> exportInverseMap = new HashMap<>(); Map<String, Map<Protocol, SymbolicRoute>> singleExportMap = new HashMap<>(); // add edge EXPORT and IMPORT state variables for (Entry<String, List<GraphEdge>> entry : getGraph().getEdgeMap().entrySet()) { String router = entry.getKey(); List<GraphEdge> edges = entry.getValue(); Map<Protocol, SymbolicRoute> singleProtoMap; singleProtoMap = new HashMap<>(); Map<Protocol, Map<GraphEdge, ArrayList<LogicalEdge>>> importEnumMap; importEnumMap = new HashMap<>(); Map<Protocol, Map<GraphEdge, ArrayList<LogicalEdge>>> exportEnumMap; exportEnumMap = new HashMap<>(); singleExportMap.put(router, singleProtoMap); importInverseMap.put(router, importEnumMap); exportInverseMap.put(router, exportEnumMap); for (Protocol proto : getProtocols().get(router)) { // Add redistribution variables Set<Protocol> r = _logicalGraph.getRedistributedProtocols().get(router, proto); assert r != null; Boolean useSingleExport = _optimizations.getSliceCanKeepSingleExportVar().get(router, proto); assert (useSingleExport != null); Map<GraphEdge, ArrayList<LogicalEdge>> importGraphEdgeMap = new HashMap<>(); Map<GraphEdge, ArrayList<LogicalEdge>> exportGraphEdgeMap = new HashMap<>(); importEnumMap.put(proto, importGraphEdgeMap); exportEnumMap.put(proto, exportGraphEdgeMap); for (GraphEdge e : edges) { Configuration conf = getGraph().getConfigurations().get(router); if (getGraph().isEdgeUsed(conf, proto, e)) { ArrayList<LogicalEdge> importEdgeList = new ArrayList<>(); ArrayList<LogicalEdge> exportEdgeList = new ArrayList<>(); importGraphEdgeMap.put(e, importEdgeList); exportGraphEdgeMap.put(e, exportEdgeList); for (int len = 0; len <= BITS; len++) { String ifaceName = e.getStart().getName(); if (!proto.isConnected() && !proto.isStatic()) { // If we use a single set of export variables, then make sure // to reuse the existing variables instead of creating new ones if (useSingleExport) { SymbolicRoute singleVars = singleExportMap.get(router).get(proto); SymbolicRoute ev1; if (singleVars == null) { String name = String.format( "%d_%s%s_%s_%s_%s", _encoder.getId(), _sliceName, router, proto.name(), "SINGLE-EXPORT", ""); ev1 = new SymbolicRoute( this, name, router, proto, _optimizations, null, e.isAbstract()); singleProtoMap.put(proto, ev1); getAllSymbolicRecords().add(ev1); } else { ev1 = singleVars; } LogicalEdge eExport = new LogicalEdge(e, EdgeType.EXPORT, ev1); exportEdgeList.add(eExport); } else { String name = String.format( "%d_%s%s_%s_%s_%s", _encoder.getId(), _sliceName, router, proto.name(), "EXPORT", ifaceName); SymbolicRoute ev1 = new SymbolicRoute( this, name, router, proto, _optimizations, null, e.isAbstract()); LogicalEdge eExport = new LogicalEdge(e, EdgeType.EXPORT, ev1); exportEdgeList.add(eExport); getAllSymbolicRecords().add(ev1); } } boolean notNeeded = _optimizations .getSliceCanCombineImportExportVars() .get(router) .get(proto) .contains(e); Interface i = e.getStart(); Prefix p = i.getConcreteAddress().getPrefix(); boolean doModel = !(proto.isConnected() && !relevantPrefix(p)); // PolicyQuotient: Don't model the connected interfaces that aren't relevant if (doModel) { if (notNeeded) { String name = String.format( "%d_%s%s_%s_%s_%s", _encoder.getId(), _sliceName, router, proto.name(), "IMPORT", ifaceName); SymbolicRoute ev2 = new SymbolicRoute(name, proto); LogicalEdge eImport = new LogicalEdge(e, EdgeType.IMPORT, ev2); importEdgeList.add(eImport); } else { String name = String.format( "%d_%s%s_%s_%s_%s", _encoder.getId(), _sliceName, router, proto.name(), "IMPORT", ifaceName); SymbolicRoute ev2 = new SymbolicRoute( this, name, router, proto, _optimizations, null, e.isAbstract()); LogicalEdge eImport = new LogicalEdge(e, EdgeType.IMPORT, ev2); importEdgeList.add(eImport); getAllSymbolicRecords().add(ev2); } } } List<ArrayList<LogicalEdge>> es = _logicalGraph.getLogicalEdges().get(router, proto); assert (es != null); ArrayList<LogicalEdge> allEdges = new ArrayList<>(); allEdges.addAll(importEdgeList); allEdges.addAll(exportEdgeList); es.add(allEdges); } } if (proto.isOspf() && r.size() > 1 && !exportGraphEdgeMap.isEmpty()) { // Add the ospf redistributed record if needed String rname = String.format( "%d_%s%s_%s_%s", _encoder.getId(), _sliceName, router, proto.name(), "Redistributed"); SymbolicRoute rec = new SymbolicRoute(this, rname, router, proto, _optimizations, null, false); _ospfRedistributed.put(router, rec); getAllSymbolicRecords().add(rec); } } } // Build a map to find the opposite of a given edge _logicalGraph .getLogicalEdges() .forEach( (router, edgeLists) -> { for (Protocol proto : getProtocols().get(router)) { for (ArrayList<LogicalEdge> edgeList : edgeLists.get(proto)) { for (LogicalEdge e : edgeList) { GraphEdge edge = e.getEdge(); Map<GraphEdge, ArrayList<LogicalEdge>> m; // System.out.println("i: " + i); // System.out.println("proto: " + proto.name()); // System.out.println("edge: " + edge + ", " + e.getEdgeType()); if (edge.getPeer() != null) { if (e.getEdgeType() == EdgeType.IMPORT) { m = exportInverseMap.get(edge.getPeer()).get(proto); } else { m = importInverseMap.get(edge.getPeer()).get(proto); } if (m != null) { GraphEdge otherEdge = getGraph().getOtherEnd().get(edge); ArrayList<LogicalEdge> list = m.get(otherEdge); if (list == null) { m.put(otherEdge, new ArrayList<>()); } else if (list.size() > 0) { LogicalEdge other = list.get(0); _logicalGraph.getOtherEnd().put(e, other); } } } } } } }); } /* * Initialize the optimizations object, which computes all * applicable optimizations for the current encoding slice. */ private void initOptimizations() { _optimizations.computeOptimizations(); } private void initOriginatedPrefixes() { for (Entry<String, Configuration> entry : getGraph().getConfigurations().entrySet()) { String router = entry.getKey(); Configuration conf = entry.getValue(); for (Protocol proto : _optimizations.getProtocols().get(router)) { Set<Prefix> prefixes = Graph.getOriginatedNetworks(conf, proto); _originatedNetworks.put(router, proto, prefixes); } } } /* * Check if this is the main slice */ boolean isMainSlice() { return _sliceName.equals("") || _sliceName.equals(Encoder.MAIN_SLICE_NAME); } /* * Initialize all environment symbolic records for BGP. */ private void addEnvironmentVariables() { // If not the main slice, just use the main slice if (!isMainSlice()) { Map<LogicalEdge, SymbolicRoute> envs = _logicalGraph.getEnvironmentVars(); EncoderSlice main = _encoder.getMainSlice(); LogicalGraph lg = main.getLogicalGraph(); Map<LogicalEdge, SymbolicRoute> existing = lg.getEnvironmentVars(); envs.putAll(existing); return; } // Otherwise create it anew for (String router : getGraph().getRouters()) { for (Protocol proto : getProtocols().get(router)) { if (proto.isBgp()) { List<ArrayList<LogicalEdge>> les = _logicalGraph.getLogicalEdges().get(router, proto); assert (les != null); for (ArrayList<LogicalEdge> eList : les) { for (LogicalEdge e : eList) { if (e.getEdgeType() == EdgeType.IMPORT) { GraphEdge ge = e.getEdge(); BgpActivePeerConfig n = getGraph().getEbgpNeighbors().get(ge); if (n != null && ge.getEnd() == null) { if (!isMainSlice()) { LogicalGraph lg = _encoder.getMainSlice().getLogicalGraph(); SymbolicRoute r = lg.getEnvironmentVars().get(e); _logicalGraph.getEnvironmentVars().put(e, r); } else { String address; if (n.getPeerAddress() == null) { address = "null"; } else { address = n.getPeerAddress().toString(); } String ifaceName = "ENV-" + address; String name = String.format( "%d_%s%s_%s_%s_%s", _encoder.getId(), _sliceName, router, proto.name(), "EXPORT", ifaceName); SymbolicRoute vars = new SymbolicRoute( this, name, router, proto, _optimizations, null, ge.isAbstract()); getAllSymbolicRecords().add(vars); _logicalGraph.getEnvironmentVars().put(e, vars); } } } } } } } } } /* * Initialize all symbolic variables for the encoding slice */ private void initVariables() { buildEdgeMap(); addForwardingVariables(); addBestVariables(); addSymbolicRecords(); addChoiceVariables();// directed edge with e&in addEnvironmentVariables(); } /* * Constraint each variable to fall within a valid range. * Metric cost is protocol dependent and need not have an * upper bound, since overflow is modeled. * * dstIp, srcIp: [0,2^32) * dstPort, srcPort: [0,2^16) * icmpType, protocol: [0,2^8) * icmpCode: [0,2^4) * * prefix length: [0,2^32) * admin distance: [0,2^8) * BGP med, local-pref: [0,2^32) * metric cost: [0,2^8) if environment * metric cost: [0,2^16) otherwise */ private void addBoundConstraints() { ArithExpr upperBound4 = mkInt(1L << 4); ArithExpr upperBound8 = mkInt(1L << 8); ArithExpr upperBound16 = mkInt(1L << 16); ArithExpr upperBound32 = mkInt(1L << 32); ArithExpr zero = mkInt(0); // Valid 16 bit integer add(mkGe(_symbolicPacket.getDstPort(), zero)); add(mkGe(_symbolicPacket.getSrcPort(), zero)); add(mkLt(_symbolicPacket.getDstPort(), upperBound16)); add(mkLt(_symbolicPacket.getSrcPort(), upperBound16)); // Valid 8 bit integer add(mkGe(_symbolicPacket.getIcmpType(), zero)); add(mkGe(_symbolicPacket.getIpProtocol(), zero)); add(mkLt(_symbolicPacket.getIcmpType(), upperBound8)); add(mkLe(_symbolicPacket.getIpProtocol(), upperBound8)); // Valid 4 bit integer add(mkGe(_symbolicPacket.getIcmpCode(), zero)); add(mkLt(_symbolicPacket.getIcmpCode(), upperBound4)); for (SymbolicRoute e : getAllSymbolicRecords()) { if (e.getRouterId() != null) { add(mkGe(e.getRouterId(), zero)); } if (e.getAdminDist() != null) { add(mkGe(e.getAdminDist(), zero)); add(mkLt(e.getAdminDist(), upperBound8)); } if (e.getMed() != null) { add(mkGe(e.getMed(), zero)); add(mkLt(e.getMed(), upperBound32)); } if (e.getLocalPref() != null) { add(mkGe(e.getLocalPref(), zero)); add(mkLt(e.getLocalPref(), upperBound32)); } if (e.getMetric() != null) { add(mkGe(e.getMetric(), zero)); if (e.isEnv()) { add(mkLt(e.getMetric(), upperBound8)); } add(mkLt(e.getMetric(), upperBound16)); } if (e.getIgpMetric() != null) { add(mkGe(e.getIgpMetric(), zero)); } if (e.getPrefixLength() != null) { add(mkGe(e.getPrefixLength(), zero)); add(mkLe(e.getPrefixLength(), mkInt(32))); } } } /* * Constraints each community regex match. A regex match * will be true, if either one of its subsumed exact values is * attached to the message, or some other community that matches * the regex is instead: * * c_regex = (c_1 or ... or c_n) or c_other * * where the regex matches c_i. The regex match is determined * ahead of time based on the configuration. */ private void addCommunityConstraints() { for (SymbolicRoute r : getAllSymbolicRecords()) { for (Entry<CommunityVar, BoolExpr> entry : r.getCommunities().entrySet()) { CommunityVar cvar = entry.getKey(); BoolExpr e = entry.getValue(); if (cvar.getType() == CommunityVar.Type.REGEX) { BoolExpr acc = mkFalse(); List<CommunityVar> deps = getGraph().getCommunityDependencies().get(cvar); for (CommunityVar dep : deps) { BoolExpr depExpr = r.getCommunities().get(dep); acc = mkOr(acc, depExpr); } BoolExpr regex = mkEq(acc, e); add(regex); } } } } /* * A collection of default values to fill in missing values for * comparison. These are needed because the optimizations might * remove various attributes from messages when unnecessary. */ ArithExpr defaultAdminDistance(Configuration conf, Protocol proto, SymbolicRoute r) { ArithExpr def = mkInt(defaultAdminDistance(conf, proto)); if (r.getBgpInternal() == null) { return def; } return mkIf(r.getBgpInternal(), mkInt(200), def); } private int defaultAdminDistance(Configuration conf, Protocol proto) { RoutingProtocol rp = Protocol.toRoutingProtocol(proto); return rp.getDefaultAdministrativeCost(conf.getConfigurationFormat()); } int defaultId() { return 0; } int defaultMetric() { return 0; } int defaultMed(Protocol proto) { if (proto.isBgp()) { return 100; } return 0; } int defaultLocalPref() { return 100; } int defaultLength() { return 0; } private int defaultIgpMetric() { return 0; } private BitVecExpr defaultOspfType() { return getCtx().mkBV(0, 2); // OI } /* * Returns the symbolic record for logical edge e. * This method is necessary, because optimizations might * decide that certain records can be merged together. */ private SymbolicRoute correctVars(LogicalEdge e) { SymbolicRoute vars = e.getSymbolicRecord(); if (!vars.getIsUsed()) { return _logicalGraph.getOtherEnd().get(e).getSymbolicRecord(); } return vars; } /* * Creates a symbolic test between a record representing the best * field and another field (vars). If the vars field is missing, * then the value is filled in with the default value. * * An assumption is that if best != null, then vars != null */ private BoolExpr equalHelper(Expr best, Expr vars, Expr defaultVal) { BoolExpr tru = mkTrue(); if (vars == null) { if (best != null) { return mkEq(best, defaultVal); } else { return tru; } } else { return mkEq(best, vars); } } /* * Creates a test to check for equal protocol histories * after accounting for null values introduced by optimizations */ BoolExpr equalHistories(SymbolicRoute best, SymbolicRoute vars) { BoolExpr history; if (best.getProtocolHistory() == null) { history = mkTrue(); } else { if (vars.getProtocolHistory() == null) { history = best.getProtocolHistory().checkIfValue(vars.getProto()); } else { history = best.getProtocolHistory().mkEq(vars.getProtocolHistory()); } } /* if (best.getProtocolHistory() == null || vars.getProtocolHistory() == null) { history = mkTrue(); } else { history = best.getProtocolHistory().mkEq(vars.getProtocolHistory()); } */ return history; } /* * Creates a test to check for equal bgp internal * tags after accounting for null values introduced by optimizations */ private BoolExpr equalBgpInternal(SymbolicRoute best, SymbolicRoute vars) { if (best.getBgpInternal() == null || vars.getBgpInternal() == null) { return mkTrue(); } else { return mkEq(best.getBgpInternal(), vars.getBgpInternal()); } } /* * Creates a test to check for equal bgp client id tags after * accounting for the possibility of null values. */ private BoolExpr equalClientIds(String router, SymbolicRoute best, SymbolicRoute vars) { if (best.getClientId() == null) { return mkTrue(); } else { if (vars.getClientId() == null) { // Lookup the actual originator id Integer i = getGraph().getOriginatorId().get(router); if (i == null) { return best.getClientId().checkIfValue(0); } else { return best.getClientId().checkIfValue(i); } } else { return best.getClientId().mkEq(vars.getClientId()); } } } /* * Creates a test to check for equal ospf areas * tags after accounting for null values introduced by optimizations */ private BoolExpr equalAreas(SymbolicRoute best, SymbolicRoute vars, @Nullable LogicalEdge e) { BoolExpr equalOspfArea; boolean hasBestArea = (best.getOspfArea() != null && best.getOspfArea().getBitVec() != null); boolean hasVarsArea = (vars.getOspfArea() != null && vars.getOspfArea().getBitVec() != null); if (e != null) { if (hasBestArea) { Interface iface = e.getEdge().getStart(); if (hasVarsArea) { equalOspfArea = best.getOspfArea().mkEq(vars.getOspfArea()); } else if (iface.getOspfAreaName() != null) { equalOspfArea = best.getOspfArea().checkIfValue(iface.getOspfAreaName()); } else { equalOspfArea = best.getOspfArea().isDefaultValue(); } } else { equalOspfArea = mkTrue(); } } else { equalOspfArea = mkTrue(); } return equalOspfArea; } /* * Creates a symbolic test to check for equal ospf types (OI, OIA, E1, E2) * after accounting for null values introduced by optimizations */ private BoolExpr equalTypes(SymbolicRoute best, SymbolicRoute vars) { BoolExpr equalOspfType; boolean hasBestType = (best.getOspfType() != null && best.getOspfType().getBitVec() != null); boolean hasVarsType = (vars.getOspfType() != null && vars.getOspfType().getBitVec() != null); if (hasVarsType) { equalOspfType = best.getOspfType().mkEq(vars.getOspfType()); } else if (hasBestType) { equalOspfType = best.getOspfType().isDefaultValue(); } else { equalOspfType = mkTrue(); } return equalOspfType; } /* * Creates a symbolic test to check for equal router IDs * after accounting for null values introduced by optimizations */ private BoolExpr equalIds( SymbolicRoute best, SymbolicRoute vars, Protocol proto, @Nullable LogicalEdge e) { BoolExpr equalId; if (vars.getRouterId() == null) { if (best.getRouterId() == null || e == null) { equalId = mkTrue(); } else { long peerId = getGraph().findRouterId(e.getEdge(), proto); equalId = mkEq(best.getRouterId(), mkInt(peerId)); } } else { equalId = mkEq(best.getRouterId(), vars.getRouterId()); } return equalId; } private BoolExpr equalCommunities(SymbolicRoute best, SymbolicRoute vars) { BoolExpr acc = mkTrue(); for (Map.Entry<CommunityVar, BoolExpr> entry : best.getCommunities().entrySet()) { CommunityVar cvar = entry.getKey(); BoolExpr var = entry.getValue(); BoolExpr other = vars.getCommunities().get(cvar); if (other == null) { acc = mkAnd(acc, mkNot(var)); } else { acc = mkAnd(acc, mkEq(var, other)); } } return acc; } /* * Check for equality of a (best) symbolic record and another * symbolic record (vars). It checks pairwise that all fields * are equal, while filling in values missing due to optimizations * with default values based on the protocol. * If there is no corresponding edge e, then the value null can be used */ public BoolExpr equal( Configuration conf, Protocol proto, SymbolicRoute best, SymbolicRoute vars, @Nullable LogicalEdge e, boolean compareCommunities) { ArithExpr defaultLocal = mkInt(defaultLocalPref()); ArithExpr defaultAdmin = defaultAdminDistance(conf, proto, vars); ArithExpr defaultMet = mkInt(defaultMetric()); ArithExpr defaultMed = mkInt(defaultMed(proto)); ArithExpr defaultLen = mkInt(defaultLength()); ArithExpr defaultIgp = mkInt(defaultIgpMetric()); BoolExpr equalLen; BoolExpr equalAd; BoolExpr equalLp; BoolExpr equalMet; BoolExpr equalMed; BoolExpr equalOspfArea; BoolExpr equalOspfType; BoolExpr equalId; BoolExpr equalHistory; BoolExpr equalBgpInternal; BoolExpr equalClientIds; BoolExpr equalIgpMet; BoolExpr equalCommunities; equalLen = equalHelper(best.getPrefixLength(), vars.getPrefixLength(), defaultLen); equalAd = equalHelper(best.getAdminDist(), vars.getAdminDist(), defaultAdmin); equalLp = equalHelper(best.getLocalPref(), vars.getLocalPref(), defaultLocal); equalMet = equalHelper(best.getMetric(), vars.getMetric(), defaultMet); equalMed = equalHelper(best.getMed(), vars.getMed(), defaultMed); equalIgpMet = equalHelper(best.getIgpMetric(), vars.getIgpMetric(), defaultIgp); equalOspfType = equalTypes(best, vars); equalOspfArea = equalAreas(best, vars, e); equalId = equalIds(best, vars, proto, e); equalHistory = equalHistories(best, vars); equalBgpInternal = equalBgpInternal(best, vars); equalClientIds = equalClientIds(conf.getHostname(), best, vars); equalCommunities = (compareCommunities ? equalCommunities(best, vars) : mkTrue()); return mkAnd( equalLen, equalAd, equalLp, equalMet, equalMed, equalOspfArea, equalOspfType, equalId, equalHistory, equalBgpInternal, equalClientIds, equalIgpMet, equalCommunities); } /* * Helper function to check if one expression is greater than * another accounting for null values introduced by optimizations. */ private BoolExpr geBetterHelper( @Nullable Expr best, @Nullable Expr vars, Expr defaultVal, boolean less) { BoolExpr fal = mkFalse(); if (vars == null) { if (best != null) { if (less) { return mkLt(best, defaultVal); } else { return mkGt(best, defaultVal); } } else { return fal; } } else { assert (best != null); if (less) { return mkLt(best, vars); } else { return mkGt(best, vars); } } } /* * Helper function to check if one expression is equal to * another accounting for null values introduced by optimizations. */ private BoolExpr geEqualHelper(@Nullable Expr best, @Nullable Expr vars, Expr defaultVal) { if (vars == null) { if (best != null) { return mkEq(best, defaultVal); } else { return mkTrue(); } } else { assert (best != null); return mkEq(best, vars); } } /* * Check if a (best) symbolic record is better than another * symbolic record (vars). This is done using a recursive lexicographic * encoding. The encoding is as follows: * * (best.length > vars.length) or * (best.length = vars.length) and ( * (best.adminDist < vars.adminDist) or * (best.adminDist = vars.adminDist) and ( * ... * ) * ) * * This recursive encoding introduces a new variable for each subexpressions, * which ends up being much more efficient than expanding out options. */ private BoolExpr greaterOrEqual( Configuration conf, Protocol proto, SymbolicRoute best, SymbolicRoute vars, @Nullable LogicalEdge e) { ArithExpr defaultLocal = mkInt(defaultLocalPref()); ArithExpr defaultAdmin = defaultAdminDistance(conf, proto, vars); ArithExpr defaultMet = mkInt(defaultMetric()); ArithExpr defaultMed = mkInt(defaultMed(proto)); ArithExpr defaultLen = mkInt(defaultLength()); ArithExpr defaultIgp = mkInt(defaultIgpMetric()); ArithExpr defaultId = mkInt(0); BitVecExpr defaultOspfType = defaultOspfType(); BoolExpr betterLen = geBetterHelper(best.getPrefixLength(), vars.getPrefixLength(), defaultLen, false); BoolExpr equalLen = geEqualHelper(best.getPrefixLength(), vars.getPrefixLength(), defaultLen); BoolExpr betterAd = geBetterHelper(best.getAdminDist(), vars.getAdminDist(), defaultAdmin, true); BoolExpr equalAd = geEqualHelper(best.getAdminDist(), vars.getAdminDist(), defaultAdmin); BoolExpr betterLp = geBetterHelper(best.getLocalPref(), vars.getLocalPref(), defaultLocal, false); BoolExpr equalLp = geEqualHelper(best.getLocalPref(), vars.getLocalPref(), defaultLocal); BoolExpr betterMet = geBetterHelper(best.getMetric(), vars.getMetric(), defaultMet, true); BoolExpr equalMet = geEqualHelper(best.getMetric(), vars.getMetric(), defaultMet); BoolExpr betterMed = geBetterHelper(best.getMed(), vars.getMed(), defaultMed, true); BoolExpr equalMed = geEqualHelper(best.getMed(), vars.getMed(), defaultMed); BitVecExpr bestType = (best.getOspfType() == null ? null : best.getOspfType().getBitVec()); BitVecExpr varsType = (vars.getOspfType() == null ? null : vars.getOspfType().getBitVec()); BoolExpr betterOspfType = geBetterHelper(bestType, varsType, defaultOspfType, true); BoolExpr equalOspfType = geEqualHelper(bestType, varsType, defaultOspfType); BoolExpr betterInternal = geBetterHelper(best.getBgpInternal(), vars.getBgpInternal(), mkFalse(), true); BoolExpr equalInternal = geEqualHelper(best.getBgpInternal(), vars.getBgpInternal(), mkFalse()); BoolExpr betterIgpMet = geBetterHelper(best.getIgpMetric(), vars.getIgpMetric(), defaultIgp, true); BoolExpr equalIgpMet = geEqualHelper(best.getIgpMetric(), vars.getIgpMetric(), defaultIgp); BoolExpr tiebreak; if (vars.getRouterId() != null) { tiebreak = mkLe(best.getRouterId(), vars.getRouterId()); } else if (best.getRouterId() != null) { if (e == null) { tiebreak = mkLe(best.getRouterId(), defaultId); } else { long peerId = getGraph().findRouterId(e.getEdge(), proto); tiebreak = mkLe(best.getRouterId(), mkInt(peerId)); } } else { tiebreak = mkTrue(); } /* This creates two maps bgpRankingBetter and bgpRankingEq that associate each BGP path ranking criterion with an SMT variable that denotes that the best route is better (resp. equal) than another route (vars). To construct the final BoolExpr as described above, we iterate the list (bgpRanks) of BgpDecisionVariable elemnts and only use the SMT variables that are relevant as dictated by the list. */ EnumMap<BgpDecisionVariable, BoolExpr> bgpRankingBetter = new EnumMap<>(BgpDecisionVariable.class); EnumMap<BgpDecisionVariable, BoolExpr> bgpRankingEq = new EnumMap<>(BgpDecisionVariable.class); bgpRankingBetter.put(BgpDecisionVariable.LOCALPREF, betterLp); bgpRankingEq.put(BgpDecisionVariable.LOCALPREF, equalLp); bgpRankingBetter.put(BgpDecisionVariable.PATHLEN, betterMet); bgpRankingEq.put(BgpDecisionVariable.PATHLEN, equalMet); bgpRankingBetter.put(BgpDecisionVariable.MED, betterMed); bgpRankingEq.put(BgpDecisionVariable.MED, equalMed); bgpRankingBetter.put(BgpDecisionVariable.EBGP_PREF_IBGP, betterInternal); bgpRankingEq.put(BgpDecisionVariable.EBGP_PREF_IBGP, equalInternal); bgpRankingBetter.put(BgpDecisionVariable.IGPCOST, betterIgpMet); bgpRankingEq.put(BgpDecisionVariable.IGPCOST, equalIgpMet); BoolExpr b = mkAnd(equalOspfType, tiebreak); b = mkOr(betterOspfType, b); List<BgpDecisionVariable> bgpRanks = new ArrayList<>(_encoder.getQuestion().getBgpRanking()); Collections.reverse(bgpRanks); for (BgpDecisionVariable bgpVar : bgpRanks) { b = mkAnd(bgpRankingEq.get(bgpVar), b); b = mkOr(bgpRankingBetter.get(bgpVar), b); } b = mkAnd(equalAd, b); b = mkOr(betterAd, b); b = mkAnd(equalLen, b); return mkOr(betterLen, b); } /* * Constraints that specify that the best choice is * better than all alternatives, and is at least one of the choices: * * (1) if no options are valid, then best is not valid * (2) if some option is valid, then we have the following: * * (best <= best_prot1) and ... and (best <= best_protn) * (best = best_prot1) or ... or (best = best_protn) */ private void addBestOverallConstraints() { for (Entry<String, Configuration> entry : getGraph().getConfigurations().entrySet()) { String router = entry.getKey(); Configuration conf = entry.getValue(); // These constraints will be added at the protocol-level when a single protocol if (!_optimizations.getSliceHasSingleProtocol().contains(router)) { boolean someProto = false; BoolExpr acc = null; BoolExpr somePermitted = null; SymbolicRoute best = _symbolicDecisions.getBestNeighbor().get(router); for (Protocol proto : getProtocols().get(router)) { someProto = true; SymbolicRoute bestVars = _symbolicDecisions.getBestVars(_optimizations, router, proto); assert (bestVars != null); if (somePermitted == null) { somePermitted = bestVars.getPermitted(); } else { somePermitted = mkOr(somePermitted, bestVars.getPermitted()); } BoolExpr val = mkAnd(bestVars.getPermitted(), equal(conf, proto, best, bestVars, null, true)); if (acc == null) { acc = val; } else { acc = mkOr(acc, val); } add( mkImplies( bestVars.getPermitted(), greaterOrEqual(conf, proto, best, bestVars, null))); } if (someProto) { if (acc != null) { add(mkEq(somePermitted, best.getPermitted())); add(mkImplies(somePermitted, acc)); } } else { add(mkNot(best.getPermitted())); } } } } /* * Constrains each protocol-best record similarly to the overall * best record. It will be better than all choices and equal to * at least one of them. */ private void addBestPerProtocolConstraints() { for (Entry<String, Configuration> entry : getGraph().getConfigurations().entrySet()) { String router = entry.getKey(); Configuration conf = entry.getValue(); for (Protocol proto : getProtocols().get(router)) { SymbolicRoute bestVars = _symbolicDecisions.getBestVars(_optimizations, router, proto); assert (bestVars != null); BoolExpr acc = null; BoolExpr somePermitted = null; for (LogicalEdge e : collectAllImportLogicalEdges(router, conf, proto)) { SymbolicRoute vars = correctVars(e); if (somePermitted == null) { somePermitted = vars.getPermitted(); } else { somePermitted = mkOr(somePermitted, vars.getPermitted()); } BoolExpr v = mkAnd(vars.getPermitted(), equal(conf, proto, bestVars, vars, e, true)); if (acc == null) { acc = v; } else { acc = mkOr(acc, v); } add(mkImplies(vars.getPermitted(), greaterOrEqual(conf, proto, bestVars, vars, e))); } if (acc != null) { add(mkEq(somePermitted, bestVars.getPermitted())); add(mkImplies(somePermitted, acc)); } } } } /* * Constraints that define a choice for a given protocol * to be when a particular import is equal to the best choice. * For example: * * choice_bgp_Serial0 = (import_Serial0 = best_bgp) */ private void addChoicePerProtocolConstraints() { for (Entry<String, Configuration> entry : getGraph().getConfigurations().entrySet()) { String router = entry.getKey(); Configuration conf = entry.getValue(); for (Protocol proto : getProtocols().get(router)) { SymbolicRoute bestVars = _symbolicDecisions.getBestVars(_optimizations, router, proto); assert (bestVars != null); for (LogicalEdge e : collectAllImportLogicalEdges(router, conf, proto)) { SymbolicRoute vars = correctVars(e); BoolExpr choice = _symbolicDecisions.getChoiceVariables().get(router, proto, e); assert (choice != null); BoolExpr isBest = equal(conf, proto, bestVars, vars, e, false); add(mkEq(choice, mkAnd(vars.getPermitted(), isBest))); } } } } /* * Constraints that define control-plane forwarding. * If there is some valid import, then control plane forwarding * will occur out an interface when this is the best choice. * Otherwise, it will not occur. */ private void addControlForwardingConstraints() { for (Entry<String, Configuration> entry : getGraph().getConfigurations().entrySet()) { String router = entry.getKey(); Configuration conf = entry.getValue(); boolean someEdge = false; SymbolicRoute best = _symbolicDecisions.getBestNeighbor().get(router); Map<GraphEdge, BoolExpr> cfExprs = new HashMap<>(); Set<GraphEdge> constrained = new HashSet<>(); for (Protocol proto : getProtocols().get(router)) { for (LogicalEdge e : collectAllImportLogicalEdges(router, conf, proto)) { someEdge = true; constrained.add(e.getEdge()); SymbolicRoute vars = correctVars(e); BoolExpr choice = _symbolicDecisions.getChoiceVariables().get(router, proto, e); BoolExpr isBest = mkAnd(choice, equal(conf, proto, best, vars, e, false)); GraphEdge ge = e.getEdge(); // Connected routes should only forward if not absorbed by interface GraphEdge other = getGraph().getOtherEnd().get(ge); BoolExpr connectedWillSend; if (other == null || getGraph().isHost(ge.getPeer())) { Ip ip = ge.getStart().getConcreteAddress().getIp(); BitVecExpr val = getCtx().mkBV(ip.asLong(), 32); connectedWillSend = mkNot(mkEq(_symbolicPacket.getDstIp(), val)); } else { Ip ip = other.getStart().getConcreteAddress().getIp(); BitVecExpr val = getCtx().mkBV(ip.asLong(), 32); connectedWillSend = mkEq(_symbolicPacket.getDstIp(), val); } BoolExpr canSend = (proto.isConnected() ? connectedWillSend : mkTrue()); BoolExpr sends = mkAnd(canSend, isBest); BoolExpr cForward = _symbolicDecisions.getControlForwarding().get(router, ge); assert (cForward != null); add(mkImplies(sends, cForward)); // record the negation as well cfExprs.merge(ge, sends, (a, b) -> mkOr(a, b)); } } // For edges that are never used, we constraint them to not be forwarded out of for (GraphEdge ge : getGraph().getEdgeMap().get(router)) { if (!constrained.contains(ge)) { BoolExpr cForward = _symbolicDecisions.getControlForwarding().get(router, ge); assert (cForward != null); add(mkNot(cForward)); } } // Handle the case that the router has no protocol running if (!someEdge) { for (GraphEdge ge : getGraph().getEdgeMap().get(router)) { BoolExpr cForward = _symbolicDecisions.getControlForwarding().get(router, ge); assert (cForward != null); add(mkNot(cForward)); } } else { // If no best route, then no forwarding Map<Protocol, List<ArrayList<LogicalEdge>>> map = _logicalGraph.getLogicalEdges().get(router); Set<GraphEdge> seen = new HashSet<>(); for (List<ArrayList<LogicalEdge>> eList : map.values()) { for (ArrayList<LogicalEdge> edges : eList) { for (LogicalEdge le : edges) { GraphEdge ge = le.getEdge(); if (seen.contains(ge)) { continue; } seen.add(ge); BoolExpr expr = cfExprs.get(ge); BoolExpr cForward = _symbolicDecisions.getControlForwarding().get(router, ge); assert (cForward != null); if (expr != null) { add(mkImplies(mkNot(expr), mkNot(cForward))); } else { add(mkNot(cForward)); } } } } } } } /* * Convert an Access Control List (ACL) to a symbolic boolean expression. * The default action in an ACL is to deny all traffic. */ private BoolExpr computeACL(IpAccessList acl) { // Check if there is an ACL first if (acl == null) { return mkTrue(); } return new IpAccessListToBoolExpr(_encoder.getCtx(), _symbolicPacket).toBoolExpr(acl); } private boolean otherSliceHasEdge(EncoderSlice slice, String r, GraphEdge ge) { Map<String, List<GraphEdge>> edgeMap = slice.getGraph().getEdgeMap(); List<GraphEdge> edges = edgeMap.get(r); return edges != null && edges.contains(ge); } /* * Constraints for the final data plane forwarding behavior. * Forwarding occurs in the data plane if the control plane decides * to use an interface, and no ACL blocks the packet: * * data_fwd(iface) = control_fwd(iface) and not acl(iface) */ private void addDataForwardingConstraints() { for (Entry<String, List<GraphEdge>> entry : getGraph().getEdgeMap().entrySet()) { String router = entry.getKey(); List<GraphEdge> edges = entry.getValue(); for (GraphEdge ge : edges) { // setup forwarding for non-abstract edges if (!ge.isAbstract()) { BoolExpr fwd = mkFalse(); BoolExpr cForward = _symbolicDecisions.getControlForwarding().get(router, ge); BoolExpr dForward = _symbolicDecisions.getDataForwarding().get(router, ge); assert (cForward != null); assert (dForward != null); // for each abstract control edge, // if that edge is on and its neighbor slices has next hop forwarding // out the current edge ge, the we use ge. for (GraphEdge ge2 : getGraph().getEdgeMap().get(router)) { if (ge2.isAbstract()) { BoolExpr ctrlFwd = getSymbolicDecisions().getControlForwarding().get(router, ge2); Graph.BgpSendType st = getGraph().peerType(ge2); // If Route reflectors, then next hop based on ID if (st == Graph.BgpSendType.TO_RR) { SymbolicRoute record = getSymbolicDecisions().getBestNeighbor().get(router); // adjust for iBGP in main slice BoolExpr acc = mkFalse(); if (isMainSlice()) { for (Entry<String, Integer> entry2 : getGraph().getOriginatorId().entrySet()) { String r = entry2.getKey(); Integer id = entry2.getValue(); EncoderSlice s = _encoder.getSlice(r); // Make sure if (otherSliceHasEdge(s, router, ge)) { BoolExpr outEdge = s.getSymbolicDecisions().getDataForwarding().get(router, ge); acc = mkOr(acc, mkAnd(record.getClientId().checkIfValue(id), outEdge)); } } } fwd = mkOr(fwd, mkAnd(ctrlFwd, acc)); } else { // Otherwise, we know the next hop statically // adjust for iBGP in main slice if (isMainSlice()) { EncoderSlice s = _encoder.getSlice(ge2.getPeer()); if (otherSliceHasEdge(s, router, ge)) { BoolExpr outEdge = s.getSymbolicDecisions().getDataForwarding().get(router, ge); fwd = mkOr(fwd, mkAnd(ctrlFwd, outEdge)); } } } } } fwd = mkOr(fwd, cForward); BoolExpr acl = _outboundAcls.get(ge); if (acl == null) { acl = mkTrue(); } BoolExpr notBlocked = mkAnd(fwd, acl); add(mkEq(notBlocked, dForward)); } } } } /* * Creates the transfer function to represent import filters * between two symbolic records. The import filter depends * heavily on the protocol. */ private void addImportConstraint( LogicalEdge e, SymbolicRoute varsOther, Configuration conf, Protocol proto, GraphEdge ge, String router) { SymbolicRoute vars = e.getSymbolicRecord(); Interface iface = ge.getStart(); ArithExpr failed = getSymbolicFailures().getFailedVariable(e.getEdge()); assert (failed != null); BoolExpr notFailed = mkEq(failed, mkInt(0)); ArithExpr failedNode = getSymbolicFailures().getFailedStartVariable(e.getEdge()); assert (failed != null); BoolExpr notFailedNode = mkEq(failedNode, mkInt(0)); if (vars.getIsUsed()) { if (proto.isConnected()) { Prefix p = iface.getConcreteAddress().getPrefix(); BoolExpr relevant = mkAnd( interfaceActive(iface, proto), isRelevantFor(p, _symbolicPacket.getDstIp()), notFailed, notFailedNode); BoolExpr per = vars.getPermitted(); BoolExpr len = safeEq(vars.getPrefixLength(), mkInt(p.getPrefixLength())); BoolExpr ad = safeEq(vars.getAdminDist(), mkInt(1)); BoolExpr lp = safeEq(vars.getLocalPref(), mkInt(0)); BoolExpr met = safeEq(vars.getMetric(), mkInt(0)); BoolExpr values = mkAnd(per, len, ad, lp, met); add(mkIf(relevant, values, mkNot(vars.getPermitted()))); } if (proto.isStatic()) { List<StaticRoute> srs = getGraph().getStaticRoutes().get(router, iface.getName()); assert (srs != null); BoolExpr acc = mkNot(vars.getPermitted()); for (StaticRoute sr : srs) { Prefix p = sr.getNetwork(); BoolExpr relevant = mkAnd( interfaceActive(iface, proto), isRelevantFor(p, _symbolicPacket.getDstIp()), notFailed, notFailedNode); BoolExpr per = vars.getPermitted(); BoolExpr len = safeEq(vars.getPrefixLength(), mkInt(p.getPrefixLength())); BoolExpr ad = safeEq(vars.getAdminDist(), mkInt(sr.getAdministrativeCost())); BoolExpr lp = safeEq(vars.getLocalPref(), mkInt(0)); BoolExpr met = safeEq(vars.getMetric(), mkInt(0)); BoolExpr values = mkAnd(per, len, ad, lp, met); acc = mkIf(relevant, values, acc); } add(acc); } if (proto.isOspf() || proto.isBgp()) { BoolExpr val = mkNot(vars.getPermitted()); if (varsOther != null) { // BoolExpr isRoot = relevantOrigination(originations); BoolExpr active = interfaceActive(iface, proto); // Handle iBGP by checking reachability to the next hop to send messages boolean isNonClient = (proto.isBgp()) && (getGraph().peerType(ge) != Graph.BgpSendType.TO_EBGP); boolean isClient = (proto.isBgp()) && (getGraph().peerType(ge) == Graph.BgpSendType.TO_RR); BoolExpr receiveMessage; String currentRouter = ge.getRouter(); String peerRouter = ge.getPeer(); if (_encoder.getModelIgp() && isNonClient) { // Lookup reachabilty based on peer next-hop receiveMessage = _encoder.getSliceReachability().get(currentRouter).get(peerRouter); /* EncoderSlice peerSlice = _encoder.getSlice(peerRouter); BoolExpr srcPort = mkEq(peerSlice.getSymbolicPacket().getSrcPort(), mkInt(179)); BoolExpr srcIp = mkEq(peerSlice.getSymbolicPacket().getSrcIp(), mkInt(0)); BoolExpr tcpAck = mkEq(peerSlice.getSymbolicPacket().getTcpAck(), mkFalse()); BoolExpr tcpCwr = mkEq(peerSlice.getSymbolicPacket().getTcpCwr(), mkFalse()); BoolExpr tcpEce = mkEq(peerSlice.getSymbolicPacket().getTcpEce(), mkFalse()); BoolExpr tcpFin = mkEq(peerSlice.getSymbolicPacket().getTcpFin(), mkFalse()); BoolExpr tcpPsh = mkEq(peerSlice.getSymbolicPacket().getTcpPsh(), mkFalse()); BoolExpr tcpRst = mkEq(peerSlice.getSymbolicPacket().getTcpRst(), mkFalse()); BoolExpr tcpSyn = mkEq(peerSlice.getSymbolicPacket().getTcpSyn(), mkFalse()); BoolExpr tcpUrg = mkEq(peerSlice.getSymbolicPacket().getTcpUrg(), mkFalse()); BoolExpr icmpCode = mkEq(peerSlice.getSymbolicPacket().getIcmpCode(), mkInt(0)); BoolExpr icmpType = mkEq(peerSlice.getSymbolicPacket().getIcmpType(), mkInt(0)); BoolExpr all = mkAnd(srcPort, srcIp, tcpAck, tcpCwr, tcpEce, tcpFin, tcpPsh, tcpRst, tcpSyn, tcpUrg, icmpCode, icmpType); receiveMessage = mkImplies(all, receiveMessage); */ } else if (_encoder.getModelIgp() && isClient) { // Lookup reachability based on client id tag to find next hop BoolExpr acc = mkTrue(); for (Map.Entry<String, Integer> entry : getGraph().getOriginatorId().entrySet()) { String r = entry.getKey(); Integer id = entry.getValue(); if (!r.equals(currentRouter)) { BoolExpr reach = _encoder.getSliceReachability().get(currentRouter).get(r); /* EncoderSlice peerSlice = _encoder.getSlice(r); BoolExpr srcPort = mkEq(peerSlice.getSymbolicPacket().getSrcPort(), mkInt(179)); BoolExpr srcIp = mkEq(peerSlice.getSymbolicPacket().getSrcIp(), mkInt(0)); BoolExpr tcpAck = mkEq(peerSlice.getSymbolicPacket().getTcpAck(), mkFalse()); BoolExpr tcpCwr = mkEq(peerSlice.getSymbolicPacket().getTcpCwr(), mkFalse()); BoolExpr tcpEce = mkEq(peerSlice.getSymbolicPacket().getTcpEce(), mkFalse()); BoolExpr tcpFin = mkEq(peerSlice.getSymbolicPacket().getTcpFin(), mkFalse()); BoolExpr tcpPsh = mkEq(peerSlice.getSymbolicPacket().getTcpPsh(), mkFalse()); BoolExpr tcpRst = mkEq(peerSlice.getSymbolicPacket().getTcpRst(), mkFalse()); BoolExpr tcpSyn = mkEq(peerSlice.getSymbolicPacket().getTcpSyn(), mkFalse()); BoolExpr tcpUrg = mkEq(peerSlice.getSymbolicPacket().getTcpUrg(), mkFalse()); BoolExpr icmpCode = mkEq(peerSlice.getSymbolicPacket().getIcmpCode(), mkInt(0)); BoolExpr icmpType = mkEq(peerSlice.getSymbolicPacket().getIcmpType(), mkInt(0)); BoolExpr all = mkAnd(srcPort, srcIp, tcpAck, tcpCwr, tcpEce, tcpFin, tcpPsh, tcpRst, tcpSyn, tcpUrg, icmpCode, icmpType); reach = mkImplies(all, reach); */ acc = mkAnd(acc, mkImplies(varsOther.getClientId().checkIfValue(id), reach)); } } receiveMessage = acc; // Just check if the link is failed } else { receiveMessage = notFailed; } // Take into account BGP loop prevention // The path length will prevent any isolated loops BoolExpr loop = mkFalse(); if (proto.isBgp() && ge.getPeer() != null) { String peer = ge.getPeer(); GraphEdge gePeer = getGraph().getOtherEnd().get(ge); loop = getSymbolicDecisions().getControlForwarding().get(peer, gePeer); } assert (loop != null); BoolExpr usable = mkAnd(mkNot(loop), active, varsOther.getPermitted(), receiveMessage, notFailedNode); BoolExpr importFunction; RoutingPolicy pol = getGraph().findImportRoutingPolicy(router, proto, e.getEdge()); if (Encoder.ENABLE_DEBUGGING && pol != null) { System.out.println("Import Policy: " + pol.getName()); } List<Statement> statements; if (pol == null) { Statements.StaticStatement s = new Statements.StaticStatement(Statements.ExitAccept); statements = Collections.singletonList(s); } else { statements = pol.getStatements(); } // OSPF cost calculated based on incoming interface Integer cost = proto.isOspf() ? addedCost(proto, ge) : 0; TransferSSA f = new TransferSSA(this, conf, varsOther, vars, proto, statements, cost, ge, false); importFunction = f.compute(); BoolExpr acc = mkIf(usable, importFunction, val); if (Encoder.ENABLE_DEBUGGING) { System.out.println("IMPORT FUNCTION: " + router + " " + varsOther.getName()); System.out.println(importFunction.simplify()); System.out.println("\n\n"); } add(acc); } else { add(val); } } } } /* * Creates the transfer function to represent export filters * between two symbolic records. The import filter depends * heavily on the protocol. */ private void addExportConstraint( LogicalEdge e, SymbolicRoute varsOther, @Nullable SymbolicRoute ospfRedistribVars, @Nullable SymbolicRoute overallBest, Configuration conf, Protocol proto, GraphEdge ge, String router, boolean usedExport, Set<Prefix> originations) { SymbolicRoute vars = e.getSymbolicRecord(); Interface iface = ge.getStart(); ArithExpr failed = getSymbolicFailures().getFailedVariable(e.getEdge()); assert (failed != null); BoolExpr notFailed = mkEq(failed, mkInt(0)); BoolExpr notFailedNode = getSymbolicFailures() .getFailedPeerVariable(e.getEdge()) .map((ArithExpr failedNode) -> mkEq(failedNode, mkInt(0))) .orElse(mkTrue()); // only add constraints once when using a single copy of export variables if (!_optimizations.getSliceCanKeepSingleExportVar().get(router).get(proto) || !usedExport) { if (proto.isConnected()) { BoolExpr val = mkNot(vars.getPermitted()); add(val); } if (proto.isStatic()) { BoolExpr val = mkNot(vars.getPermitted()); add(val); } if (proto.isOspf() || proto.isBgp()) { // BGP cost based on export int cost = proto.isBgp() ? addedCost(proto, ge) : 0; BoolExpr val = mkNot(vars.getPermitted()); BoolExpr active = interfaceActive(iface, proto); // Apply BGP export policy and cost based on peer type // (1) EBGP --> ALL // (2) CLIENT --> ALL // (3) NONCLIENT --> EBGP, CLIENT boolean isNonClientEdge = proto.isBgp() && getGraph().peerType(ge) != Graph.BgpSendType.TO_EBGP; boolean isClientEdge = proto.isBgp() && getGraph().peerType(ge) == Graph.BgpSendType.TO_CLIENT; boolean isInternalExport = varsOther.isBest() && _optimizations.getNeedBgpInternal().contains(router); BoolExpr doExport = mkTrue(); if (isInternalExport && proto.isBgp() && isNonClientEdge) { if (isClientEdge) { cost = 0; } else { // Lookup if we learned from iBGP, and if so, don't export the route SymbolicRoute other = getBestNeighborPerProtocol(router, proto); assert other != null; assert other.getBgpInternal() != null; if (other.getBgpInternal() != null) { doExport = mkNot(other.getBgpInternal()); cost = 0; } } } BoolExpr acc; RoutingPolicy pol = getGraph().findExportRoutingPolicy(router, proto, e.getEdge()); if (Encoder.ENABLE_DEBUGGING && pol != null) { System.out.println("Export policy (" + _sliceName + "," + ge + "): " + pol.getName()); } // We have to wrap this with the right thing for some reason List<Statement> statements; if (proto.isOspf()) { If i = new If( new MatchProtocol(RoutingProtocol.OSPF), ImmutableList.of(Statements.ExitAccept.toStaticStatement()), pol != null ? pol.getStatements() : ImmutableList.of(new Statements.StaticStatement(Statements.ExitReject))); statements = Collections.singletonList(i); } else { statements = (pol == null ? Collections.singletonList(new Statements.StaticStatement(Statements.ExitAccept)) : pol.getStatements()); } TransferSSA f = new TransferSSA(this, conf, varsOther, vars, proto, statements, cost, ge, true); acc = f.compute(); BoolExpr usable = mkAnd(active, doExport, varsOther.getPermitted(), notFailed, notFailedNode); // OSPF is complicated because it can have routes redistributed into it // from the FIB, but also needs to know about other routes in OSPF as well. // We model the export here as being the better of the redistributed route // and the OSPF exported route. This should work since every other router // will maintain the same preference when adding to the cost. if (ospfRedistribVars != null) { assert overallBest != null; f = new TransferSSA( this, conf, overallBest, ospfRedistribVars, proto, statements, cost, ge, true); BoolExpr acc2 = f.compute(); // System.out.println("ADDING: \n" + acc2.simplify()); add(acc2); BoolExpr usable2 = mkAnd(active, doExport, ospfRedistribVars.getPermitted(), notFailed, notFailedNode); BoolExpr geq = greaterOrEqual(conf, proto, ospfRedistribVars, varsOther, e); BoolExpr isBetter = mkNot(mkAnd(ospfRedistribVars.getPermitted(), geq)); BoolExpr usesOspf = mkAnd(varsOther.getPermitted(), isBetter); BoolExpr eq = equal(conf, proto, ospfRedistribVars, vars, e, false); BoolExpr eqPer = mkEq(ospfRedistribVars.getPermitted(), vars.getPermitted()); acc = mkIf(usesOspf, mkIf(usable, acc, val), mkIf(usable2, mkAnd(eq, eqPer), val)); } else { acc = mkIf(usable, acc, val); } for (Prefix p : originations) { // For OSPF, we need to explicitly initiate a route if (proto.isOspf()) { BoolExpr ifaceUp = interfaceActive(iface, proto); BoolExpr relevantPrefix = isRelevantFor(p, _symbolicPacket.getDstIp()); BoolExpr relevant = mkAnd(ifaceUp, relevantPrefix); int adminDistance = defaultAdminDistance(conf, proto); int prefixLength = p.getPrefixLength(); BoolExpr per = vars.getPermitted(); BoolExpr lp = safeEq(vars.getLocalPref(), mkInt(0)); BoolExpr ad = safeEq(vars.getAdminDist(), mkInt(adminDistance)); BoolExpr met = safeEq(vars.getMetric(), mkInt(cost)); BoolExpr med = safeEq(vars.getMed(), mkInt(100)); BoolExpr len = safeEq(vars.getPrefixLength(), mkInt(prefixLength)); BoolExpr type = safeEqEnum(vars.getOspfType(), OspfType.O); BoolExpr area = safeEqEnum(vars.getOspfArea(), iface.getOspfAreaName()); BoolExpr internal = safeEq(vars.getBgpInternal(), mkFalse()); BoolExpr igpMet = safeEq(vars.getIgpMetric(), mkInt(0)); BoolExpr comms = mkTrue(); for (Map.Entry<CommunityVar, BoolExpr> entry : vars.getCommunities().entrySet()) { comms = mkAnd(comms, mkNot(entry.getValue())); } BoolExpr values = mkAnd(per, lp, ad, met, med, len, type, area, internal, igpMet, comms); // Don't originate OSPF route when there is a better redistributed route if (ospfRedistribVars != null) { BoolExpr betterLen = mkGt(ospfRedistribVars.getPrefixLength(), mkInt(prefixLength)); BoolExpr equalLen = mkEq(ospfRedistribVars.getPrefixLength(), mkInt(prefixLength)); BoolExpr betterAd = mkLt(ospfRedistribVars.getAdminDist(), mkInt(110)); BoolExpr better = mkOr(betterLen, mkAnd(equalLen, betterAd)); BoolExpr betterRedistributed = mkAnd(ospfRedistribVars.getPermitted(), better); relevant = mkAnd(relevant, mkNot(betterRedistributed)); } acc = mkIf(relevant, values, acc); } } add(acc); if (Encoder.ENABLE_DEBUGGING) { System.out.println("EXPORT: " + router + " " + varsOther.getName() + " " + ge); System.out.println(acc.simplify()); System.out.println("\n\n"); } } } } /* * Constraints that define relationships between various messages * in the network. The same transfer function abstraction is used * for both import and export constraints by relating different collections * of variables. */ private void addTransferFunction() { for (Entry<String, Configuration> entry : getGraph().getConfigurations().entrySet()) { String router = entry.getKey(); Configuration conf = entry.getValue(); for (Protocol proto : getProtocols().get(router)) { boolean usedExport = false; boolean hasEdge = false; List<ArrayList<LogicalEdge>> les = _logicalGraph.getLogicalEdges().get(router, proto); assert (les != null); for (ArrayList<LogicalEdge> eList : les) { for (LogicalEdge e : eList) { GraphEdge ge = e.getEdge(); if (!getGraph().isEdgeUsed(conf, proto, ge)) { continue; } hasEdge = true; SymbolicRoute varsOther; switch (e.getEdgeType()) { case IMPORT: varsOther = _logicalGraph.findOtherVars(e); addImportConstraint(e, varsOther, conf, proto, ge, router); break; case EXPORT: // OSPF export is tricky because it does not depend on being // in the FIB. So it can come from either a redistributed route // or another OSPF route. We always take the direct OSPF SymbolicRoute ospfRedistribVars = null; SymbolicRoute overallBest = null; if (proto.isOspf()) { varsOther = getBestNeighborPerProtocol(router, proto); if (_ospfRedistributed.containsKey(router)) { ospfRedistribVars = _ospfRedistributed.get(router); overallBest = _symbolicDecisions.getBestNeighbor().get(router); } } else { varsOther = _symbolicDecisions.getBestNeighbor().get(router); } Set<Prefix> originations = _originatedNetworks.get(router, proto); assert varsOther != null; assert originations != null; addExportConstraint( e, varsOther, ospfRedistribVars, overallBest, conf, proto, ge, router, usedExport, originations); usedExport = true; break; default: break; } } } // If no edge used, then just set the best record to be false for that protocol if (!hasEdge) { SymbolicRoute protoBest; if (_optimizations.getSliceHasSingleProtocol().contains(router)) { protoBest = _symbolicDecisions.getBestNeighbor().get(router); } else { protoBest = _symbolicDecisions.getBestNeighborPerProtocol().get(router, proto); } assert protoBest != null; add(mkNot(protoBest.getPermitted())); } } } } /* * Constraints that ensure the protocol choosen by the best choice is accurate. * This is important because redistribution depends on the protocol used * in the actual FIB. */ private void addHistoryConstraints() { for (Entry<String, SymbolicRoute> entry : _symbolicDecisions.getBestNeighbor().entrySet()) { String router = entry.getKey(); SymbolicRoute vars = entry.getValue(); if (_optimizations.getSliceHasSingleProtocol().contains(router)) { Protocol proto = getProtocols().get(router).get(0); add(mkImplies(vars.getPermitted(), vars.getProtocolHistory().checkIfValue(proto))); } } } /* * For performance reasons, we add constraints that if a message is not * valid, then the other variables will use default values. This speeds * up the solver significantly. */ private void addUnusedDefaultValueConstraints() { for (SymbolicRoute vars : getAllSymbolicRecords()) { BoolExpr notPermitted = mkNot(vars.getPermitted()); ArithExpr zero = mkInt(0); if (vars.getAdminDist() != null) { add(mkImplies(notPermitted, mkEq(vars.getAdminDist(), zero))); } if (vars.getMed() != null) { add(mkImplies(notPermitted, mkEq(vars.getMed(), zero))); } if (vars.getLocalPref() != null) { add(mkImplies(notPermitted, mkEq(vars.getLocalPref(), zero))); } if (vars.getPrefixLength() != null) { add(mkImplies(notPermitted, mkEq(vars.getPrefixLength(), zero))); } if (vars.getMetric() != null) { add(mkImplies(notPermitted, mkEq(vars.getMetric(), zero))); } if (vars.getOspfArea() != null) { add(mkImplies(notPermitted, vars.getOspfArea().isDefaultValue())); } if (vars.getOspfType() != null) { add(mkImplies(notPermitted, vars.getOspfType().isDefaultValue())); } if (vars.getProtocolHistory() != null) { add(mkImplies(notPermitted, vars.getProtocolHistory().isDefaultValue())); } if (vars.getBgpInternal() != null) { add(mkImplies(notPermitted, mkNot(vars.getBgpInternal()))); } if (vars.getClientId() != null) { add(mkImplies(notPermitted, vars.getClientId().isDefaultValue())); } if (vars.getIgpMetric() != null) { add(mkImplies(notPermitted, mkEq(vars.getIgpMetric(), zero))); } if (vars.getRouterId() != null) { add(mkImplies(notPermitted, mkEq(vars.getRouterId(), zero))); } vars.getCommunities().forEach((cvar, e) -> add(mkImplies(notPermitted, mkNot(e)))); } } /* * Add constraints for the type of packets we will consider in the model. * This can include restrictions on any packet field such as dstIp, protocol etc. */ private void addHeaderSpaceConstraint() { @SuppressWarnings("PMD.CloseResource") Context ctx = _encoder.getCtx(); add( new IpAccessListToBoolExpr(ctx, _symbolicPacket) .visitMatchHeaderSpace(new MatchHeaderSpace(_headerSpace))); } /* * Add various constraints for well-formed environments */ private void addEnvironmentConstraints() { for (SymbolicRoute vars : getLogicalGraph().getEnvironmentVars().values()) { // Environment messages are not internal if (vars.getBgpInternal() != null) { add(mkNot(vars.getBgpInternal())); } // Environment messages have 0 value for client id if (vars.getClientId() != null) { add(vars.getClientId().isNotFromClient()); } } } /* * Compute the network encoding by adding all the * relevant constraints. */ void computeEncoding() { addBoundConstraints(); addCommunityConstraints(); addTransferFunction(); addHistoryConstraints(); addBestPerProtocolConstraints(); addChoicePerProtocolConstraints(); addBestOverallConstraints(); addControlForwardingConstraints(); addDataForwardingConstraints(); addUnusedDefaultValueConstraints(); addHeaderSpaceConstraint(); if (isMainSlice()) { addEnvironmentConstraints(); } } /* * Getters and Setters */ Graph getGraph() { return _logicalGraph.getGraph(); } Encoder getEncoder() { return _encoder; } Map<String, List<Protocol>> getProtocols() { return _optimizations.getProtocols(); } String getSliceName() { return _sliceName; } Context getCtx() { return _encoder.getCtx(); } Solver getSolver() { return _encoder.getSolver(); } Map<String, Expr> getAllVariables() { return _encoder.getAllVariables(); } Optimizations getOptimizations() { return _optimizations; } LogicalGraph getLogicalGraph() { return _logicalGraph; } SymbolicDecisions getSymbolicDecisions() { return _symbolicDecisions; } SymbolicPacket getSymbolicPacket() { return _symbolicPacket; } Map<GraphEdge, BoolExpr> getIncomingAcls() { return _inboundAcls; } Table2<String, GraphEdge, BoolExpr> getForwardsAcross() { return _forwardsAcross; } Set<CommunityVar> getAllCommunities() { return getGraph().getAllCommunities(); } Map<String, String> getNamedCommunities() { return getGraph().getNamedCommunities(); } UnsatCore getUnsatCore() { return _encoder.getUnsatCore(); } private List<SymbolicRoute> getAllSymbolicRecords() { return _allSymbolicRoutes; } private SymbolicFailures getSymbolicFailures() { return _encoder.getSymbolicFailures(); } Map<CommunityVar, List<CommunityVar>> getCommunityDependencies() { return getGraph().getCommunityDependencies(); } Table2<String, Protocol, Set<Prefix>> getOriginatedNetworks() { return _originatedNetworks; } }
package com.flink.streaming.web.controller.api; import com.flink.streaming.web.common.RestResult; import com.flink.streaming.web.common.exceptions.BizException; import com.flink.streaming.web.controller.web.BaseController; import com.flink.streaming.web.service.SystemConfigService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @author zhuhuipei * @Description: * @date 2020-07-07 * @time 22:00 */ @RestController @RequestMapping("/api") @Slf4j public class ConfigApiController extends BaseController { @Autowired private SystemConfigService systemConfigService; @RequestMapping(value = "/upsertSynConfig", method = RequestMethod.POST) public RestResult upsertSynConfig(String key, String val) { try { systemConfigService.addOrUpdateConfigByKey(key, val.trim()); } catch (BizException biz) { log.warn("upsertSynConfig is error ", biz); return RestResult.error(biz.getMessage()); } catch (Exception e) { log.error("upsertSynConfig is error", e); return RestResult.error(e.getMessage()); } return RestResult.success(); } @RequestMapping(value = "/deleteConfig", method = RequestMethod.POST) public RestResult deleteConfig(String key) { try { systemConfigService.deleteConfigByKey(key); } catch (BizException biz) { log.warn("upsertSynConfig is error ", biz); return RestResult.error(biz.getMessage()); } catch (Exception e) { log.error("upsertSynConfig is error", e); return RestResult.error(e.getMessage()); } return RestResult.success(); } }
package org.n3r.eql.joor; import org.n3r.eql.util.Ob; import java.lang.reflect.*; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; /** * A wrapper for an {@link Object} or {@link Class} upon which reflective calls * can be made. * An example of using <code>Reflect</code> is <code> * // Static import all reflection methods to decrease verbosity * // Wrap an Object / Class / class name with the on() method: * on("java.lang.String") * // Invoke constructors using the create() method: * .create("Hello World") * // Invoke methods using the call() method: * .call("toString") * // Retrieve the wrapped object * </code> * * @author Lukas Eder */ @SuppressWarnings("unchecked") public class Reflect { // --------------------------------------------------------------------- // Static API used as entrance points to the fluent API // --------------------------------------------------------------------- /** * Wrap a class name. * This is the same as calling <code>on(Class.forName(name))</code> * * @param name A fully qualified class name * @return A wrapped class object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #on(Class) */ public static Reflect on(String name) throws ReflectException { return on(forName(name)); } /** * Wrap a class. * Use this when you want to access static fields and methods on a * {@link Class} object, or as a basis for constructing objects of that * class using {@link #create(Object...)} * * @param clazz The class to be wrapped * @return A wrapped class object, to be used for further reflection. */ public static Reflect on(Class<?> clazz) { return new Reflect(clazz); } /** * Wrap an object. * Use this when you want to access instance fields and methods on any * {@link Object} * * @param object The object to be wrapped * @return A wrapped object, to be used for further reflection. */ public static Reflect on(Object object) { return new Reflect(object); } /* * Conveniently render an {@link java.lang.reflect.AccessibleObject} accessible * * @param accessible The object to render accessible * @return The argument object rendered accessible */ public static <T extends AccessibleObject> T accessible(T accessible) { if (accessible == null) { return null; } if (!accessible.isAccessible()) { accessible.setAccessible(true); } return accessible; } // --------------------------------------------------------------------- // Members // --------------------------------------------------------------------- /** * The wrapped object */ private final Object object; /** * A flag indicating whether the wrapped object is a {@link Class} (for * accessing static fields and methods), or any other type of {@link Object} * (for accessing instance fields and methods). */ private final boolean isClass; // --------------------------------------------------------------------- // Constructors // --------------------------------------------------------------------- private Reflect(Class<?> type) { this.object = type; this.isClass = true; } private Reflect(Object object) { this.object = object; this.isClass = false; } // --------------------------------------------------------------------- // Fluent Reflection API // --------------------------------------------------------------------- /* * Get the wrapped object * * @param <T> A convenience generic parameter for automatic unsafe casting */ @SuppressWarnings("unchecked") public <T> T get() { return (T) object; } /** * Set a field value. * This is roughly equivalent to {@link java.lang.reflect.Field#set(Object, Object)}. If the * wrapped object is a {@link Class}, then this will set a value to a static * member field. If the wrapped object is any other {@link Object}, then * this will set a value to an instance member field. * * @param name The field name * @param value The new field value * @return The same wrapped object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect set(String name, Object value) throws ReflectException { Object unwrapValue = unwrap(value); try { // Try setting a public field Field field = type().getField(name); field.set(object, convertValue(field, unwrapValue)); return this; } catch (Exception e1) { // Try again, setting a non-public field try { Field field = type().getDeclaredField(name); accessible(field).set(object, convertValue(field, unwrapValue)); return this; } catch (Exception e2) { throw new ReflectException(e2); } } } private Object convertValue(Field field, Object unwrapValue) { if (field.getType().isEnum()) { Class<?> type = field.getType(); if (unwrapValue instanceof String) { return Enum.valueOf((Class<Enum>) type, (String) unwrapValue); } } return unwrapValue; } /* * Get a field value. * This is roughly equivalent to {@link java.lang.reflect.Field#get(Object)}. If the wrapped * object is a {@link Class}, then this will get a value from a static * member field. If the wrapped object is any other {@link Object}, then * this will get a value from an instance member field. * If you want to "navigate" to a wrapped version of the field, use * {@link #field(String)} instead. * * @param name The field name * @return The field value * @throws ReflectException If any reflection exception occurred. * @see #field(String) */ public <T> T get(String name) throws ReflectException { return field(name).get(); } /** * Get a wrapped field. * This is roughly equivalent to {@link java.lang.reflect.Field#get(Object)}. If the wrapped * object is a {@link Class}, then this will wrap a static member field. If * the wrapped object is any other {@link Object}, then this wrap an * instance member field. * * @param name The field name * @return The wrapped field * @throws ReflectException If any reflection exception occurred. */ public Reflect field(String name) throws ReflectException { try { // Try getting a public field Field field = type().getField(name); return on(field.get(object)); } catch (Exception e1) { // Try again, getting a non-public field try { return on(accessible(type().getDeclaredField(name)).get(object)); } catch (Exception e2) { throw new ReflectException(e2); } } } /** * Get a Map containing field names and wrapped values for the fields' * values. * If the wrapped object is a {@link Class}, then this will return static * fields. If the wrapped object is any other {@link Object}, then this will * return instance fields. * These two calls are equivalent <code> * on(object).field("myField"); * on(object).fields().get("myField"); * </code> * * @return A map containing field names and wrapped values. */ public Map<String, Reflect> fields() { Map<String, Reflect> result = new LinkedHashMap<>(); for (Field field : type().getFields()) { if (!isClass ^ Modifier.isStatic(field.getModifiers())) { String name = field.getName(); result.put(name, field(name)); } } return result; } /** * Call a method by its name. * This is a convenience method for calling * <code>call(name, new Object[0])</code> * * @param name The method name * @return The wrapped method result or the same wrapped object if the * method returns <code>void</code>, to be used for further * reflection. * @throws ReflectException If any reflection exception occurred. * @see #call(String, Object...) */ public Reflect call(String name) throws ReflectException { return call(name, new Object[0]); } /** * Call a method by its name. * This is roughly equivalent to {@link java.lang.reflect.Method#invoke(Object, Object...)}. * If the wrapped object is a {@link Class}, then this will invoke a static * method. If the wrapped object is any other {@link Object}, then this will * invoke an instance method. * Just like {@link java.lang.reflect.Method#invoke(Object, Object...)}, this will try to wrap * primitive types or unwrap primitive type wrappers if applicable. If * several methods are applicable, by that rule, the first one encountered * is called. i.e. when calling <code> * on(...).call("method", 1, 1); * </code> The first of the following methods will be called: * <code> * public void method(int param1, Integer param2); * public void method(Integer param1, int param2); * public void method(Number param1, Number param2); * public void method(Number param1, Object param2); * public void method(int param1, Object param2); * </code> * The best matching method is searched for with the following strategy: * <ol> * <li>public method with exact signature match in class hierarchy</li> * <li>non-public method with exact signature match on declaring class</li> * <li>public method with similar signature in class hierarchy</li> * <li>non-public method with similar signature on declaring class</li> * </ol> * * @param name The method name * @param args The method arguments * @return The wrapped method result or the same wrapped object if the * method returns <code>void</code>, to be used for further * reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect call(String name, Object... args) throws ReflectException { Class<?>[] types = types(args); // Try invoking the "canonical" method, i.e. the one with exact // matching argument types try { Method method = exactMethod(name, types); return on(method, object, args); } // If there is no exact match, try to find a method that has a "similar" // signature if primitive argument types are converted to their wrappers catch (NoSuchMethodException e) { try { Method method = similarMethod(name, types); return on(method, object, args); } catch (NoSuchMethodException e1) { throw new ReflectException(e1); } } } /** * Searches a method with the exact same signature as desired. * <p/> * If a public method is found in the class hierarchy, this method is returned. * Otherwise a private method with the exact same signature is returned. * If no exact match could be found, we let the {@code NoSuchMethodException} pass through. */ private Method exactMethod(String name, Class<?>[] types) throws NoSuchMethodException { final Class<?> type = type(); // first priority: find a public method with exact signature match in class hierarchy try { return type.getMethod(name, types); } // second priority: find a private method with exact signature match on declaring class catch (NoSuchMethodException e) { return type.getDeclaredMethod(name, types); } } /** * Searches a method with a similar signature as desired using * {@link #isSimilarSignature(java.lang.reflect.Method, String, Class[])}. * <p/> * First public methods are searched in the class hierarchy, then private * methods on the declaring class. If a method could be found, it is * returned, otherwise a {@code NoSuchMethodException} is thrown. */ private Method similarMethod(String name, Class<?>[] types) throws NoSuchMethodException { final Class<?> type = type(); // first priority: find a public method with a "similar" signature in class hierarchy // similar interpreted in when primitive argument types are converted to their wrappers for (Method method : type.getMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } // second priority: find a non-public method with a "similar" signature on declaring class for (Method method : type.getDeclaredMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } throw new NoSuchMethodException("No similar method " + name + " with params " + Arrays.toString(types) + " could be found on type " + type() + "."); } /** * Determines if a method has a "similar" signature, especially if wrapping * primitive argument types would result in an exactly matching signature. */ private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class<?>[] desiredParamTypes) { return possiblyMatchingMethod.getName().equals(desiredMethodName) && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes); } /** * Call a constructor. * This is a convenience method for calling * <code>create(new Object[0])</code> * * @return The wrapped new object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #create(Object...) */ public Reflect create() throws ReflectException { return create(new Object[0]); } /** * Call a constructor. * This is roughly equivalent to {@link java.lang.reflect.Constructor#newInstance(Object...)}. * If the wrapped object is a {@link Class}, then this will create a new * object of that class. If the wrapped object is any other {@link Object}, * then this will create a new object of the same type. * Just like {@link java.lang.reflect.Constructor#newInstance(Object...)}, this will try to * wrap primitive types or unwrap primitive type wrappers if applicable. If * several constructors are applicable, by that rule, the first one * encountered is called. i.e. when calling <code> * on(C.class).create(1, 1); * </code> The first of the following constructors will be applied: * <code> * public C(int param1, Integer param2); * public C(Integer param1, int param2); * public C(Number param1, Number param2); * public C(Number param1, Object param2); * public C(int param1, Object param2); * </code> * * @param args The constructor arguments * @return The wrapped new object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect create(Object... args) throws ReflectException { Class<?>[] types = types(args); // Try invoking the "canonical" constructor, i.e. the one with exact // matching argument types try { Constructor<?> constructor = type().getDeclaredConstructor(types); return on(constructor, args); } // If there is no exact match, try to find one that has a "similar" // signature if primitive argument types are converted to their wrappers catch (NoSuchMethodException e) { for (Constructor<?> constructor : type().getConstructors()) { if (match(constructor.getParameterTypes(), types)) { return on(constructor, args); } } Class<?> type = type(); try { Object o = Ob.createInstance(type); if (o != null) return on(o); } catch (NoClassDefFoundError e1) { // java.lang.NoClassDefFoundError: org/objenesis/Objenesis } throw new ReflectException("unable to create bean for " + type()); } } /* * Create a proxy for the wrapped object allowing to typesafely invoke * methods on it using a custom interface * * @param proxyType The interface type that is implemented by the proxy * @return A proxy for the wrapped object */ @SuppressWarnings("unchecked") public <P> P as(Class<P> proxyType) { final boolean isMap = (object instanceof Map); final InvocationHandler handler = new InvocationHandler() { @SuppressWarnings("null") @Override public Object invoke(Object proxy, Method method, Object[] args) { String name = method.getName(); // Actual method name matches always come first try { return on(object).call(name, args).get(); } // [#14] Simulate POJO behaviour on wrapped map objects catch (ReflectException e) { if (isMap) { Map<String, Object> map = (Map<String, Object>) object; int length = (args == null ? 0 : args.length); if (length == 0 && name.startsWith("get")) { return map.get(property(name.substring(3))); } else if (length == 0 && name.startsWith("is")) { return map.get(property(name.substring(2))); } else if (length == 1 && name.startsWith("set")) { map.put(property(name.substring(3)), args[0]); return null; } } throw e; } } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[]{proxyType}, handler); } /** * Get the POJO property name of an getter/setter */ private static String property(String string) { int length = string.length(); if (length == 0) { return ""; } else if (length == 1) { return string.toLowerCase(); } else { return string.substring(0, 1).toLowerCase() + string.substring(1); } } // --------------------------------------------------------------------- // Object API // --------------------------------------------------------------------- /** * Check whether two arrays of types match, converting primitive types to * their corresponding wrappers. */ private boolean match(Class<?>[] declaredTypes, Class<?>[] actualTypes) { if (declaredTypes.length == actualTypes.length) { for (int i = 0; i < actualTypes.length; i++) { if (!wrapper(declaredTypes[i]).isAssignableFrom(wrapper(actualTypes[i]))) { return false; } } return true; } else { return false; } } /** * {@inheritDoc} */ @Override public int hashCode() { return object.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj instanceof Reflect) { return object.equals(((Reflect) obj).get()); } return false; } /** * {@inheritDoc} */ @Override public String toString() { return object.toString(); } // --------------------------------------------------------------------- // Utility methods // --------------------------------------------------------------------- /* * Wrap an object created from a constructor */ private static Reflect on(Constructor<?> constructor, Object... args) throws ReflectException { try { return on(accessible(constructor).newInstance(args)); } catch (Exception e) { throw new ReflectException(e); } } /* * Wrap an object returned from a method */ private static Reflect on(Method method, Object object, Object... args) throws ReflectException { try { accessible(method); if (method.getReturnType() == void.class) { method.invoke(object, args); return on(object); } else { return on(method.invoke(object, args)); } } catch (Exception e) { throw new ReflectException(e); } } private static Object unwrap(Object object) { if (object instanceof Reflect) { return ((Reflect) object).get(); } return object; } /* * Get an array of types for an array of objects * * @see Object#getClass() */ private static Class<?>[] types(Object... values) { if (values == null) { return new Class[0]; } Class<?>[] result = new Class[values.length]; for (int i = 0; i < values.length; i++) { Object value = values[i]; result[i] = value == null ? Object.class : value.getClass(); } return result; } /* * Load a class * * @see Class#forName(String) */ private static Class<?> forName(String name) throws ReflectException { try { return Class.forName(name); } catch (Exception e) { throw new ReflectException(e); } } /* * Get the type of the wrapped object. * * @see Object#getClass() */ public Class<?> type() { if (isClass) { return (Class<?>) object; } else { return object.getClass(); } } /* * Get a wrapper type for a primitive type, or the argument type itself, if * it is not a primitive type. */ public static Class<?> wrapper(Class<?> type) { if (type == null) { return null; } else if (type.isPrimitive()) { if (boolean.class == type) { return Boolean.class; } else if (int.class == type) { return Integer.class; } else if (long.class == type) { return Long.class; } else if (short.class == type) { return Short.class; } else if (byte.class == type) { return Byte.class; } else if (double.class == type) { return Double.class; } else if (float.class == type) { return Float.class; } else if (char.class == type) { return Character.class; } else if (void.class == type) { return Void.class; } } return type; } }
package io.syndesis.qe.utils; import static org.assertj.core.api.Assertions.fail; import org.apache.commons.io.IOUtils; import org.apache.commons.net.ftp.FTPClient; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; @Slf4j public class FtpUtils implements FileTransferUtils { private FtpClientManager manager = new FtpClientManager(); private FTPClient ftpClient = manager.getClient(); @Override public void deleteFile(String path) { checkConnection(); log.info("Deleting " + path + " from FTP server"); try { ftpClient.deleteFile(path); } catch (IOException e) { fail("Unable to delete file", path); } } @Override public boolean isFileThere(String directory, String fileName) { checkConnection(); try { return Arrays.stream(ftpClient.listFiles(directory)).filter(file -> file.getName().equals(fileName)).count() == 1; } catch (IOException ex) { fail("Unable to list files in FTP", ex); } return false; } @Override public void uploadTestFile(String testFileName, String text, String remoteDirectory) { checkConnection(); log.info("Uploading file " + testFileName + " with content " + text + " to directory " + remoteDirectory + ". This may take some time"); try (InputStream is = IOUtils.toInputStream(text, "UTF-8")) { ftpClient.storeFile("/" + remoteDirectory + "/" + testFileName, is); } catch (IOException ex) { fail("Unable to upload test file: ", ex); } } @Override public String getFileContent(String directory, String fileName) { try { return IOUtils.toString(ftpClient.retrieveFileStream(directory + "/" + fileName), "utf-8"); } catch (Exception ex) { fail("Unable to read FTP file " + directory + "/" + fileName); } return null; } /** * Sometimes the Connections ends with "FTPConnectionClosedException: Connection closed without indication". */ private void checkConnection() { try { ftpClient.listFiles(); } catch (IOException ex) { ftpClient = manager.getClient(); } } }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa; import com.yahoo.collections.Pair; import com.yahoo.document.ArrayDataType; import com.yahoo.document.CollectionDataType; import com.yahoo.document.DataType; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.ReferenceDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.StructuredDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.annotation.AnnotationReferenceDataType; import com.yahoo.document.annotation.AnnotationType; import com.yahoo.documentmodel.NewDocumentType; import com.yahoo.documentmodel.VespaDocumentType; import com.yahoo.searchdefinition.Schema; import com.yahoo.searchdefinition.SchemaBuilder; import com.yahoo.searchdefinition.document.FieldSet; import com.yahoo.searchdefinition.parser.ParseException; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Generates Vespa document classes from schema files. * * @author Vegard Balgaard Havdal */ @Mojo(name = "document-gen", defaultPhase = LifecyclePhase.GENERATE_SOURCES) public class DocumentGenMojo extends AbstractMojo { private long newestModifiedTime = 0; private static final int STD_INDENT = 4; @Component private MavenProject project; /** * Directory containing the searchdefinition files * @deprecated use {@link #schemasDirectory} instead */ // TODO: Remove in Vespa 8 @Deprecated @Parameter(defaultValue = ".", required = false) private File sdDirectory; /** * Directory containing the schema files */ // TODO: Make this required and with defaultValue "." when sdDirectory is removed in Vespa 8 @Parameter private File schemasDirectory; /** * Java package for generated classes */ @Parameter(defaultValue = "com.yahoo.vespa.document", required = true) private String packageName; /** * User provided annotation types that the plugin should not generate types for. They should however be included in * ConcreteDocumentFactory. */ @Parameter private List<Annotation> provided = new ArrayList<Annotation>(); /** * Annotation types for which the generated class should be abstract */ @Parameter private List<Annotation> abztract = new ArrayList<Annotation>(); /** * Generate source to here. */ @Parameter( property = "plugin.configuration.outputDirectory", defaultValue="${project.build.directory}/generated-sources/vespa-documentgen-plugin/", required = true) private File outputDirectory; private Map<String, Schema> searches; private Map<String, String> docTypes; private Map<String, String> structTypes; private Map<String, String> annotationTypes; void execute(File schemasDir, File outputDir, String packageName) { if ("".equals(packageName)) throw new IllegalArgumentException("You may not use empty package for generated types."); searches = new HashMap<>(); docTypes = new HashMap<>(); structTypes = new HashMap<>(); annotationTypes = new HashMap<>(); outputDir.mkdirs(); SchemaBuilder builder = buildSearches(schemasDir); boolean annotationsExported=false; for (NewDocumentType docType : builder.getModel().getDocumentManager().getTypes()) { if ( docType != VespaDocumentType.INSTANCE) { exportDocumentSources(outputDir, docType, packageName); for (AnnotationType annotationType : docType.getAllAnnotations()) { if (provided(annotationType.getName())!=null) continue; annotationsExported=true; exportAnnotationSources(outputDir, annotationType, docType, packageName); } } } exportPackageInfo(outputDir, packageName); if (annotationsExported) exportPackageInfo(outputDir, packageName+".annotation"); exportDocFactory(outputDir, packageName); if (project!=null) project.addCompileSourceRoot(outputDirectory.toString()); } private SchemaBuilder buildSearches(File sdDir) { File[] sdFiles = sdDir.listFiles((dir, name) -> name.endsWith(".sd")); SchemaBuilder builder = new SchemaBuilder(true); for (File f : sdFiles) { try { long modTime = f.lastModified(); if (modTime > newestModifiedTime) { newestModifiedTime = modTime; } builder.importFile(f.getAbsolutePath()); } catch (ParseException | IOException e) { throw new IllegalArgumentException(e); } } builder.build(); for (Schema schema : builder.getSchemaList() ) { this.searches.put(schema.getName(), schema); } return builder; } /** * Creates package-info.java, so that the package of the concrete doc types get exported from user's bundle. */ private void exportPackageInfo(File outputDir, String packageName) { File dirForSources = new File(outputDir, packageName.replaceAll("\\.", "/")); dirForSources.mkdirs(); File target = new File(dirForSources, "package-info.java"); if (target.lastModified() > newestModifiedTime) { getLog().debug("No changes, not updating "+target); return; } try (Writer out = new FileWriter(target)) { out.write("@ExportPackage\n" + "package "+packageName+";\n\n" + "import com.yahoo.osgi.annotation.ExportPackage;\n"); } catch (IOException e) { throw new RuntimeException(e); } } /** * The class for this type if provided, otherwise null */ private String provided(String annotationType) { if (provided==null) return null; for (Annotation a : provided) { if (a.type.equals(annotationType)) return a.clazz; } return null; } private boolean isAbstract(String annotationType) { if (abztract==null) return false; for (Annotation a : abztract) { if (a.type.equals(annotationType)) return true; } return false; } private void exportDocFactory(File outputDir, String packageName) { File dirForSources = new File(outputDir, packageName.replaceAll("\\.", "/")); dirForSources.mkdirs(); File target = new File(dirForSources, "ConcreteDocumentFactory.java"); if (target.lastModified() > newestModifiedTime) { getLog().debug("No changes, not updating "+target); return; } try (Writer out = new FileWriter(target)) { out.write("package "+packageName+";\n\n" + "/**\n" + " * Registry of generated concrete document, struct and annotation types.\n" + " *\n" + " * Generated by vespa-documentgen-plugin, do not edit.\n" + " * Date: "+new Date()+"\n" + " */\n"); out.write("@com.yahoo.document.Generated\npublic class ConcreteDocumentFactory extends com.yahoo.docproc.AbstractConcreteDocumentFactory {\n"); out.write(ind()+"private static java.util.Map<java.lang.String, java.lang.Class<? extends com.yahoo.document.Document>> dTypes = new java.util.HashMap<java.lang.String, java.lang.Class<? extends com.yahoo.document.Document>>();\n"); out.write(ind()+"private static java.util.Map<java.lang.String, com.yahoo.document.DocumentType> docTypes = new java.util.HashMap<>();\n"); out.write(ind()+"private static java.util.Map<java.lang.String, java.lang.Class<? extends com.yahoo.document.datatypes.Struct>> sTypes = new java.util.HashMap<java.lang.String, java.lang.Class<? extends com.yahoo.document.datatypes.Struct>>();\n"); out.write(ind()+"private static java.util.Map<java.lang.String, java.lang.Class<? extends com.yahoo.document.annotation.Annotation>> aTypes = new java.util.HashMap<java.lang.String, java.lang.Class<? extends com.yahoo.document.annotation.Annotation>>();\n"); out.write(ind()+"static {\n"); for (Map.Entry<String, String> e : docTypes.entrySet()) { String docTypeName = e.getKey(); String fullClassName = e.getValue(); out.write(ind(2)+"dTypes.put(\""+docTypeName+"\","+fullClassName+".class);\n"); } for (Map.Entry<String, String> e : docTypes.entrySet()) { String docTypeName = e.getKey(); String fullClassName = e.getValue(); out.write(ind(2)+"docTypes.put(\""+docTypeName+"\","+fullClassName+".type);\n"); } for (Map.Entry<String, String> e : structTypes.entrySet()) { String structTypeName = e.getKey(); String fullClassName = e.getValue(); out.write(ind(2)+"sTypes.put(\""+structTypeName+"\","+fullClassName+".class);\n"); } for (Map.Entry<String, String> e : annotationTypes.entrySet()) { String annotationTypeName = e.getKey(); String fullClassName = e.getValue(); out.write(ind(2)+"aTypes.put(\""+annotationTypeName+"\","+fullClassName+".class);\n"); } for (Annotation a : provided) { out.write(ind(2)+"aTypes.put(\""+a.type+"\","+a.clazz+".class);\n"); } out.write(ind()+"}\n\n"); out.write( ind()+"public static final java.util.Map<java.lang.String, java.lang.Class<? extends com.yahoo.document.Document>> documentTypes = java.util.Collections.unmodifiableMap(dTypes);\n" + ind()+"public static final java.util.Map<java.lang.String, com.yahoo.document.DocumentType> documentTypeObjects = java.util.Collections.unmodifiableMap(docTypes);\n" + ind()+"public static final java.util.Map<java.lang.String, java.lang.Class<? extends com.yahoo.document.datatypes.Struct>> structTypes = java.util.Collections.unmodifiableMap(sTypes);\n" + ind()+"public static final java.util.Map<java.lang.String, java.lang.Class<? extends com.yahoo.document.annotation.Annotation>> annotationTypes = java.util.Collections.unmodifiableMap(aTypes);\n\n"); out.write( ind()+"@Override public java.util.Map<java.lang.String, java.lang.Class<? extends com.yahoo.document.Document>> documentTypes() { return ConcreteDocumentFactory.documentTypes; }\n" + ind()+"@Override public java.util.Map<java.lang.String, java.lang.Class<? extends com.yahoo.document.datatypes.Struct>> structTypes() { return ConcreteDocumentFactory.structTypes; }\n" + ind()+"@Override public java.util.Map<java.lang.String, java.lang.Class<? extends com.yahoo.document.annotation.Annotation>> annotationTypes() { return ConcreteDocumentFactory.annotationTypes; }\n\n"); out.write( ind()+"/**\n" + ind()+" * Returns a new Document which will be of the correct concrete type and a copy of the given StructFieldValue.\n" + ind()+" */\n" + ind()+"@Override public com.yahoo.document.Document getDocumentCopy(java.lang.String type, com.yahoo.document.datatypes.StructuredFieldValue src, com.yahoo.document.DocumentId id) {\n"); for (Map.Entry<String, String> e : docTypes.entrySet()) { out.write(ind(2)+"if (\""+e.getKey()+"\".equals(type)) return new "+e.getValue()+"(src, id);\n"); } out.write(ind(2)+"throw new java.lang.IllegalArgumentException(\"No such concrete document type: \"+type);\n"); out.write(ind()+"}\n\n"); // delete, bad to use reflection? out.write( ind()+"/**\n" + ind()+" * Returns a new Document which will be of the correct concrete type.\n" + ind()+" */\n" + ind()+"public static com.yahoo.document.Document getDocument(java.lang.String type, com.yahoo.document.DocumentId id) {\n" + ind(2)+"if (!ConcreteDocumentFactory.documentTypes.containsKey(type)) throw new java.lang.IllegalArgumentException(\"No such concrete document type: \"+type);\n" + ind(2)+"try {\n" + ind(3)+"return ConcreteDocumentFactory.documentTypes.get(type).getConstructor(com.yahoo.document.DocumentId.class).newInstance(id);\n" + ind(2)+"} catch (java.lang.Exception ex) { throw new java.lang.RuntimeException(ex); }\n" + ind()+"}\n\n"); // delete, bad to use reflection? out.write( ind()+"/**\n" + ind()+" * Returns a new Struct which will be of the correct concrete type.\n" + ind()+" */\n" + ind()+"public static com.yahoo.document.datatypes.Struct getStruct(java.lang.String type) {\n" + ind(2)+"if (!ConcreteDocumentFactory.structTypes.containsKey(type)) throw new java.lang.IllegalArgumentException(\"No such concrete struct type: \"+type);\n" + ind(2)+"try {\n" + ind(3)+"return ConcreteDocumentFactory.structTypes.get(type).getConstructor().newInstance();\n" + ind(2)+"} catch (java.lang.Exception ex) { throw new java.lang.RuntimeException(ex); }\n" + ind()+"}\n\n"); // delete, bad to use reflection? out.write( ind()+"/**\n" + ind()+" * Returns a new Annotation which will be of the correct concrete type.\n" + ind()+" */\n" + ind()+"public static com.yahoo.document.annotation.Annotation getAnnotation(java.lang.String type) {\n" + ind(2)+"if (!ConcreteDocumentFactory.annotationTypes.containsKey(type)) throw new java.lang.IllegalArgumentException(\"No such concrete annotation type: \"+type);\n" + ind(2)+"try {\n" + ind(3)+"return ConcreteDocumentFactory.annotationTypes.get(type).getConstructor().newInstance();\n" + ind(2)+"} catch (java.lang.Exception ex) { throw new java.lang.RuntimeException(ex); }\n" + ind()+"}\n\n"); out.write("}\n"); } catch (IOException e) { throw new RuntimeException(e); } } private void exportAnnotationSources(File outputDir, AnnotationType annType, NewDocumentType docType, String packageName) { File dirForSources = new File(outputDir, packageName.replaceAll("\\.", "/")+"/annotation/"); dirForSources.mkdirs(); String className = className(annType.getName()); File target = new File(dirForSources, className+".java"); if (target.lastModified() > newestModifiedTime) { getLog().debug("No changes, not updating "+target); return; } try (Writer out = new FileWriter(target)) { out.write("package "+packageName+".annotation;\n\n" + "import "+packageName+".ConcreteDocumentFactory;\n" + exportInnerImportsFromDocAndSuperTypes(docType, packageName) + exportImportProvidedAnnotationRefs(annType) + "/**\n" + " * Generated by vespa-documentgen-plugin, do not edit.\n" + " * Input annotation type: "+annType.getName()+"\n" + " * Date: "+new Date()+"\n" + " */\n" + "@com.yahoo.document.Generated\npublic "+annTypeModifier(annType)+"class "+className+" extends "+getParentAnnotationType(annType)+" {\n\n"); if (annType.getDataType() instanceof StructDataType) { out.write(ind() + "public "+className+"() {\n" + ind(2) + "setType(new com.yahoo.document.annotation.AnnotationType(\""+annType.getName()+"\", Fields.type));\n" + ind()+"}\n\n"); StructDataType annStruct = (StructDataType)annType.getDataType(); StructDataType annStructTmp = new StructDataType("fields"); // Change the type name annStructTmp.assign(annStruct); Collection<DataType> tmpList = new ArrayList<>(); tmpList.add(annStructTmp); exportStructTypes(tmpList, out, 1, null); exportFieldsAndAccessors(className, annStruct.getFieldsThisTypeOnly(), out, 1, false); out.write(ind()+"@Override public boolean hasFieldValue() { return true; }\n\n"); out.write(ind()+"@Override public com.yahoo.document.datatypes.FieldValue getFieldValue() {\n"); out.write(ind(2)+"com.yahoo.document.datatypes.Struct ret = new Fields();\n"); for (Field f : annStruct.getFields()) { out.write( ind(2)+"if ("+getter(f.getName()) +"()!=null) {\n" + ind(3)+"com.yahoo.document.Field f = ret.getField(\"" + f.getName() + "\");\n" + ind(3)+"com.yahoo.document.datatypes.FieldValue fv = f.getDataType().createFieldValue(" + getter(f.getName()) + "());\n" + ind(3)+"ret.setFieldValue(f, fv);\n" + ind(2)+"}\n"); } out.write(ind(2)+"return ret;\n"); out.write(ind()+"}\n\n"); } else { out.write(ind() + "public "+className+"() { setType(new com.yahoo.document.annotation.AnnotationType(\""+annType.getName()+"\")); } \n\n"); out.write(ind()+"@Override public boolean hasFieldValue() { return false; }\n\n"); out.write(ind()+"@Override public com.yahoo.document.datatypes.FieldValue getFieldValue() { return null; }\n\n"); } out.write("}\n"); annotationTypes.put(annType.getName(), packageName+".annotation."+className); } catch (IOException e) { throw new RuntimeException("Could not export sources for annotation type '"+annType.getName()+"'", e); } } /** * Handle the case of an annotation reference with a type that is user provided, we need to know the class name then */ private String exportImportProvidedAnnotationRefs(AnnotationType annType) { if (annType.getDataType()==null) return ""; StringBuilder ret = new StringBuilder(); for (Field f : ((StructDataType)annType.getDataType()).getFields()) { if (f.getDataType() instanceof AnnotationReferenceDataType) { AnnotationReferenceDataType refType = (AnnotationReferenceDataType) f.getDataType(); AnnotationType referenced = refType.getAnnotationType(); String providedClass = provided(referenced.getName()); if (providedClass!=null) { // Annotationreference is to a type that is user-provided ret.append("import ").append(providedClass).append(";\n"); } } } return ret.toString(); } private String annTypeModifier(AnnotationType annType) { if (isAbstract(annType.getName())) return "abstract "; return ""; } private static String exportInnerImportsFromDocAndSuperTypes(NewDocumentType docType, String packageName) { String ret = ""; ret = ret + "import "+packageName+"."+className(docType.getName())+".*;\n"; ret = ret + exportInnerImportsFromSuperTypes(docType, packageName); return ret; } private static String exportInnerImportsFromSuperTypes(NewDocumentType docType, String packageName) { StringBuilder ret = new StringBuilder(); for (NewDocumentType inherited : docType.getInherited()) { if (inherited.getName().equals("document")) continue; ret.append("import ").append(packageName).append(".").append(className(inherited.getName())).append(".*;\n"); } return ret.toString(); } private String getParentAnnotationType(AnnotationType annType) { if (annType.getInheritedTypes().isEmpty()) return "com.yahoo.document.annotation.Annotation"; String superType = annType.getInheritedTypes().iterator().next().getName(); String providedSuperType = provided(superType); if (providedSuperType!=null) return providedSuperType; return className(annType.getInheritedTypes().iterator().next().getName()); } private void exportDocumentSources(File outputDir, NewDocumentType docType, String packageName) { File dirForSources = new File(outputDir, packageName.replaceAll("\\.", "/")); dirForSources.mkdirs(); File target = new File(dirForSources, className(docType.getName())+".java"); if (target.lastModified() > newestModifiedTime) { getLog().debug("No changes, not updating "+target); return; } try (Writer doc = new FileWriter(target)) { exportDocumentClass(docType, doc, packageName); } catch (IOException e) { throw new RuntimeException("Could not export sources for document type '"+docType.getName()+"'", e); } } /** * Generates the .java file for the Document subclass for the given document type */ private void exportDocumentClass(NewDocumentType docType, Writer out, String packageName) throws IOException { String className = className(docType.getName()); Pair<String, Boolean> extendInfo = javaSuperType(docType); String superType = extendInfo.getFirst(); Boolean multiExtends = extendInfo.getSecond(); out.write( "package "+packageName+";\n\n" + exportInnerImportsFromSuperTypes(docType, packageName) + "/**\n" + " * Generated by vespa-documentgen-plugin, do not edit.\n" + " * Input document type: "+docType.getName()+"\n" + " * Date: "+new Date()+"\n" + " */\n" + "@com.yahoo.document.Generated\npublic class "+className+" extends "+superType+" {\n\n"+ ind(1)+"/** The doc type of this.*/\n" + ind(1)+"public static final com.yahoo.document.DocumentType type = getDocumentType();\n\n"+ ind(1)+"/** Struct type view of the type of the body of this.*/\n" + ind(1)+"/** Struct type view of the type of the header of this.*/\n" + ind(1)+"private static final com.yahoo.document.StructDataType headerStructType = getHeaderStructType();\n\n"); // Constructor out.write( ind(1)+"public "+className+"(com.yahoo.document.DocumentId docId) {\n" + ind(2)+"super("+className+".type, docId);\n" + ind(1)+"}\n\n"); out.write( ind(1)+"protected "+className+"(com.yahoo.document.DocumentType type, com.yahoo.document.DocumentId docId) {\n" + ind(2)+"super(type, docId);\n" + ind(1)+"}\n\n"); // isGenerated() out.write(ind(1)+"@Override protected boolean isGenerated() { return true; }\n\n"); // Mimic header and body to make serialization work. // This can be improved by generating a method to serialize the document _here_, and use that in serialization. exportOverriddenStructGetter(docType.allHeader().getFields(), out, 1, "getHeader", className+".headerStructType"); exportStructTypeGetter(docType.getName()+".header", docType.allHeader().getFields(), out, 1, "getHeaderStructType", "com.yahoo.document.StructDataType"); Collection<Field> allUniqueFields = getAllUniqueFields(multiExtends, docType.getAllFields()); exportExtendedStructTypeGetter(className, docType.getName(), allUniqueFields, docType.getFieldSets(), docType.getImportedFieldNames(), out, 1, "getDocumentType", "com.yahoo.document.DocumentType"); exportCopyConstructor(className, out, 1, true); exportFieldsAndAccessors(className, "com.yahoo.document.Document".equals(superType) ? allUniqueFields : docType.getFields(), out, 1, true); exportDocumentMethods(allUniqueFields, out, 1); exportHashCode(allUniqueFields, out, 1, "(getDataType() != null ? getDataType().hashCode() : 0) + getId().hashCode()"); exportEquals(className, allUniqueFields, out, 1); Set<DataType> exportedStructs = exportStructTypes(docType.getTypes(), out, 1, null); if (hasAnyPositionField(allUniqueFields)) { exportedStructs = exportStructTypes(Arrays.asList(PositionDataType.INSTANCE), out, 1, exportedStructs); } docTypes.put(docType.getName(), packageName+"."+className); for (DataType exportedStruct : exportedStructs) { structTypes.put(exportedStruct.getName(), packageName+"."+className+"."+className(exportedStruct.getName())); } out.write("}\n"); } private static boolean hasAnyPositionDataType(DataType dt) { if (PositionDataType.INSTANCE.equals(dt)) { return true; } else if (dt instanceof CollectionDataType) { return hasAnyPositionDataType(((CollectionDataType)dt).getNestedType()); } else if (dt instanceof StructuredDataType) { return hasAnyPositionField(((StructuredDataType)dt).getFields()); } else { return false; } } private static boolean hasAnyPositionField(Collection<Field> fields) { for (Field f : fields) { if (hasAnyPositionDataType(f.getDataType())) { return true; } } return false; } private Collection<Field> getAllUniqueFields(Boolean multipleInheritance, Collection<Field> allFields) { if (multipleInheritance) { Map<String, Field> seen = new HashMap<>(); List<Field> unique = new ArrayList<>(allFields.size()); for (Field f : allFields) { if (seen.containsKey(f.getName())) { if ( ! f.equals(seen.get(f.getName()))) { throw new IllegalArgumentException("Field '" + f.getName() + "' has conflicting definitions in multiple inheritance." + "First defined as '" + seen.get(f.getName()) + "', then as '" + f + "'."); } } else { unique.add(f); seen.put(f.getName(), f); } } return unique; } return allFields; } /** * The Java class the class of the given type should inherit from. If the input type inherits from _one_ * other type, use that, otherwise Document. */ private static Pair<String,Boolean> javaSuperType(NewDocumentType docType) { String ret = "com.yahoo.document.Document"; Collection<NewDocumentType> specInheriteds = specificInheriteds(docType); boolean singleExtends = singleInheritance(specInheriteds); if (!specInheriteds.isEmpty() && singleExtends) ret = className(specInheriteds.iterator().next().getName()); return new Pair<>(ret, !singleExtends); } private static boolean singleInheritance(Collection<NewDocumentType> specInheriteds) { if (specInheriteds.isEmpty()) return true; if (specInheriteds.size()>1) return false; return singleInheritance(specificInheriteds(specInheriteds.iterator().next())); } /** * The inherited types that are not Document * @return collection of specific inherited types */ private static Collection<NewDocumentType> specificInheriteds(NewDocumentType type) { List<NewDocumentType> ret = new ArrayList<>(); for (NewDocumentType t : type.getInherited()) { if (!"document".equals(t.getName())) ret.add(t); } return ret; } /** * Exports the copy constructor. * * NOTE: This is important, the docproc framework uses that constructor. */ private static void exportCopyConstructor(String className, Writer out, int ind, boolean docId) throws IOException { out.write( ind(ind)+"/**\n"+ ind(ind)+" * Constructs a "+className+" by taking a deep copy of the provided StructuredFieldValue.\n" + ind(ind)+" */\n"); if (docId) { out.write(ind(ind)+"public "+className+"(com.yahoo.document.datatypes.StructuredFieldValue src, com.yahoo.document.DocumentId docId) {\n"+ ind(ind+1)+"super("+className+".type,docId);\n"); } else { out.write(ind(ind)+"public "+className+"(com.yahoo.document.datatypes.StructuredFieldValue src) {\n"+ ind(ind+1)+"super("+className+".type);\n"); } out.write(ind() + "ConcreteDocumentFactory factory = new ConcreteDocumentFactory();\n"); out.write( ind(ind+1)+"for (java.util.Iterator<java.util.Map.Entry<com.yahoo.document.Field, com.yahoo.document.datatypes.FieldValue>>i=src.iterator() ; i.hasNext() ; ) {\n" + ind(ind+2)+"java.util.Map.Entry<com.yahoo.document.Field, com.yahoo.document.datatypes.FieldValue> e = i.next();\n" + ind(ind+2)+"com.yahoo.document.Field f = e.getKey();\n" + ind(ind+2)+"com.yahoo.document.datatypes.FieldValue fv = e.getValue();\n" + ind(ind+2)+"setFieldValue(f, factory.optionallyUpgrade(f, fv));\n" + ind(ind+1)+"}\n"+ ind(ind)+"}\n\n"); } private static void exportStructTypeGetter(String name, Collection<Field> fields, Writer out, int ind, String methodName, String retType) throws IOException { out.write(ind(ind)+"private static "+retType+" "+methodName+"() {\n" + ind(ind+1)+retType+" ret = new "+retType+"(\""+name+"\");\n"); for (Field f : fields) { out.write(ind(ind+1)+"ret.addField(new com.yahoo.document.Field(\""+f.getName()+"\", "+toJavaReference(f.getDataType())+"));\n"); } out.write(ind(ind+1)+"return ret;\n"); out.write(ind(ind)+"}\n\n"); } private static void addExtendedField(String className, Field f, Writer out, int ind) throws IOException { out.write(ind(ind)+ "ret.addField(new com.yahoo.document.ExtendedField(\""+f.getName()+"\", " + toJavaReference(f.getDataType()) + ",\n"); out.write(ind(ind+1) + "new com.yahoo.document.ExtendedField.Extract() {\n"); out.write(ind(ind+2) + "public Object get(com.yahoo.document.datatypes.StructuredFieldValue doc) {return ((" + className + ")doc)." + getter(f.getName()) + "(); }\n"); out.write(ind(ind+2) + "public void set(com.yahoo.document.datatypes.StructuredFieldValue doc, Object value) { ((" + className + ")doc)." + setter(f.getName())+"((" + toJavaType(f.getDataType()) + ")value); }\n"); out.write(ind(ind+1) + "}\n"); out.write(ind(ind) + "));\n"); } private static void addExtendedStringField(String className, Field f, Writer out, int ind) throws IOException { out.write(ind(ind)+ "ret.addField(new com.yahoo.document.ExtendedStringField(\""+f.getName()+"\", " + toJavaReference(f.getDataType()) + ",\n"); out.write(ind(ind+1) + "new com.yahoo.document.ExtendedField.Extract() {\n"); out.write(ind(ind+2) + "public Object get(com.yahoo.document.datatypes.StructuredFieldValue doc) {return ((" + className + ")doc)." + getter(f.getName()) + "(); }\n"); out.write(ind(ind+2) + "public void set(com.yahoo.document.datatypes.StructuredFieldValue doc, Object value) { ((" + className + ")doc)." + setter(f.getName())+"((" + toJavaType(f.getDataType()) + ")value); }\n"); out.write(ind(ind+1) + "},\n"); out.write(ind(ind+1) + "new com.yahoo.document.ExtendedStringField.ExtractSpanTrees() {\n"); out.write(ind(ind+2) + "public java.util.Map<java.lang.String,com.yahoo.document.annotation.SpanTree> get(com.yahoo.document.datatypes.StructuredFieldValue doc) {return ((" + className + ")doc)." + spanTreeGetter(f.getName()) + "(); }\n"); out.write(ind(ind+2) + "public void set(com.yahoo.document.datatypes.StructuredFieldValue doc, java.util.Map<java.lang.String,com.yahoo.document.annotation.SpanTree> value) { ((" + className + ")doc)." + spanTreeSetter(f.getName()) + "(value); }\n"); out.write(ind(ind+1) + "}\n"); out.write(ind(ind) + "));\n"); } private static void exportFieldSetDefinition(Set<FieldSet> fieldSets, Writer out, int ind) throws IOException { out.write(ind(ind) + "java.util.Map<java.lang.String, java.util.Collection<java.lang.String>> fieldSets = new java.util.HashMap<>();\n"); for (FieldSet fieldSet : fieldSets) { out.write(ind(ind) + "fieldSets.put(\"" + fieldSet.getName() + "\", java.util.Arrays.asList("); int count = 0; for (String field : fieldSet.getFieldNames()) { out.write("\"" + field + "\""); if (++count != fieldSet.getFieldNames().size()) { out.write(","); } } out.write("));\n"); } out.write(ind(ind) + "ret.addFieldSets(fieldSets);\n"); } private static void exportImportedFields(Set<String> importedFieldNames, Writer out, int ind) throws IOException { out.write(ind(ind) + "java.util.Set<java.lang.String> importedFieldNames = new java.util.HashSet<>();\n"); for (String importedField : importedFieldNames) { out.write(ind(ind) + "importedFieldNames.add(\"" + importedField + "\");\n"); } } private static void exportExtendedStructTypeGetter(String className, String name, Collection<Field> fields, Set<FieldSet> fieldSets, Set<String> importedFieldNames, Writer out, int ind, String methodName, String retType) throws IOException { out.write(ind(ind)+"private static "+retType+" "+methodName+"() {\n"); if (importedFieldNames != null) { exportImportedFields(importedFieldNames, out, ind + 1); out.write(ind(ind+1)+retType+" ret = new "+retType+"(\"" + name + "\", importedFieldNames);\n"); } else { out.write(ind(ind+1)+retType+" ret = new "+retType+"(\""+name+"\");\n"); } for (Field f : fields) { if (f.getDataType().equals(DataType.STRING)) { addExtendedStringField(className, f, out, ind + 1); } else { addExtendedField(className, f, out, ind + 1); } } if (fieldSets != null) { exportFieldSetDefinition(fieldSets, out, ind+1); } out.write(ind(ind+1)+"return ret;\n"); out.write(ind(ind)+"}\n\n"); } private static void exportOverriddenStructGetter(Collection<Field> fields, Writer out, int ind, String methodName, String structType) throws IOException { out.write(ind(ind)+"@Override @Deprecated public com.yahoo.document.datatypes.Struct "+methodName+"() {\n" + ind(ind+1)+"com.yahoo.document.datatypes.Struct ret = new com.yahoo.document.datatypes.Struct("+structType+");\n"); for (Field f : fields) { out.write(ind(ind+1)+"ret.setFieldValue(\""+f.getName()+"\", getFieldValue(getField(\""+f.getName()+"\")));\n"); } out.write(ind(ind+1)+"return ret;\n"); out.write(ind(ind)+"}\n\n"); } /** * Exports the necessary overridden methods from Document/StructuredFieldValue */ private static void exportDocumentMethods(Collection<Field> fieldSet, Writer out, int ind) throws IOException { exportGetFieldCount(fieldSet, out, ind); exportGetField(out, ind); exportGetFieldValue(fieldSet, out, ind); exportSetFieldValue(out, ind); exportRemoveFieldValue(out, ind); exportIterator(fieldSet, out, ind); exportClear(fieldSet, out, ind); } private static void exportEquals(String className, Collection<Field> fieldSet, Writer out, int ind) throws IOException { out.write(ind(ind)+"@Override public boolean equals(Object o) {\n"); out.write(ind(ind+1)+"if (!(o instanceof "+className+")) return false;\n"); out.write(ind(ind+1)+className+" other = ("+className+")o;\n"); for (Field field: fieldSet) { out.write(ind(ind+1)+"if ("+getter(field.getName())+"()==null) { if (other."+getter(field.getName())+"()!=null) return false; }\n"); out.write(ind(ind+2)+"else if (!("+getter(field.getName())+"().equals(other."+getter(field.getName())+"()))) return false;\n"); } out.write(ind(ind+1)+"return true;\n"); out.write(ind(ind)+"}\n\n"); } private static void exportHashCode(Collection<Field> fieldSet, Writer out, int ind, String hcBase) throws IOException { out.write(ind(ind)+"@Override public int hashCode() {\n"); out.write(ind(ind+1)+"int hc = "+hcBase+";\n"); for (Field field: fieldSet) { out.write(ind(ind+1)+"hc += "+getter(field.getName())+"()!=null ? "+getter(field.getName())+"().hashCode() : 0;\n"); } out.write(ind(ind+1)+"return hc;\n"); out.write(ind(ind)+"}\n\n"); } private static void exportClear(Collection<Field> fieldSet, Writer out, int ind) throws IOException { out.write(ind(ind)+"@Override public void clear() {\n"); for (Field field: fieldSet) { out.write(ind(ind+1)+setter(field.getName())+"(null);\n"); } out.write(ind(ind)+"}\n\n"); } private static void exportIterator(Collection<Field> fieldSet, Writer out, int ind) throws IOException { out.write(ind(ind)+"@Override public java.util.Iterator<java.util.Map.Entry<com.yahoo.document.Field, com.yahoo.document.datatypes.FieldValue>> iterator() {\n"); out.write(ind(ind+1)+"java.util.Map<com.yahoo.document.Field, com.yahoo.document.datatypes.FieldValue> ret = new java.util.HashMap<>();\n"); for (Field field: fieldSet) { String name = field.getName(); out.write(ind(ind+1)+"if ("+getter(name)+"()!=null) {\n"); out.write(ind(ind+2)+"com.yahoo.document.Field f = getField(\""+name+"\");\n"); out.write(ind(ind+2)+"ret.put(f, ((com.yahoo.document.ExtendedField)f).getFieldValue(this));\n" + ind(ind+1)+"}\n"); } out.write(ind(ind+1)+"return ret.entrySet().iterator();\n" + ind(ind)+"}\n\n"); } private static void exportRemoveFieldValue(Writer out, int ind) throws IOException { out.write(ind(ind) + "@Override public com.yahoo.document.datatypes.FieldValue removeFieldValue(com.yahoo.document.Field field) {\n"); out.write(ind(ind+1) + "if (field==null) return null;\n"); out.write(ind(ind+1) + "com.yahoo.document.ExtendedField ef = ensureExtended(field);\n"); out.write(ind(ind+1) + "return (ef != null) ? ef.setFieldValue(this, null) : super.removeFieldValue(field);\n"); out.write(ind(ind) + "}\n"); } private static void exportSetFieldValue(Writer out, int ind) throws IOException { out.write(ind(ind)+"@Override public com.yahoo.document.datatypes.FieldValue setFieldValue(com.yahoo.document.Field field, com.yahoo.document.datatypes.FieldValue value) {\n"); out.write(ind(ind+1)+"com.yahoo.document.ExtendedField ef = ensureExtended(field);\n"); out.write(ind(ind+1)+"return (ef != null) ? ef.setFieldValue(this, value) : super.setFieldValue(field, value);\n"); out.write(ind(ind)+"}\n\n"); } private static void exportGetFieldValue(Collection<Field> fieldSet, Writer out, int ind) throws IOException { out.write(ind(ind)+"@Override public com.yahoo.document.datatypes.FieldValue getFieldValue(com.yahoo.document.Field field) {\n"); out.write(ind(ind+1)+"if (field==null) return null;\n"); out.write(ind(ind+1)+"if (field.getDataType() instanceof com.yahoo.document.StructDataType) {\n"); for (Field field: fieldSet) { String name = field.getName(); if (field.getDataType() instanceof StructDataType) { out.write(ind(ind+2)+"if (\""+name+"\".equals(field.getName())) return "+name+";\n"); } } out.write(ind(ind+1)+"}\n"); out.write(ind(ind+1)+"com.yahoo.document.ExtendedField ef = ensureExtended(field);\n"); out.write(ind(ind+1)+"return (ef != null) ? ef.getFieldValue(this) : super.getFieldValue(field);\n"); out.write(ind(ind)+"}\n\n"); } private static void exportGetField(Writer out, int ind) throws IOException { out.write(ind(ind) + "private com.yahoo.document.ExtendedStringField ensureExtendedString(com.yahoo.document.Field f) {\n"); out.write(ind(ind+1) + "return (com.yahoo.document.ExtendedStringField)((f instanceof com.yahoo.document.ExtendedStringField) ? f : getField(f.getName()));\n"); out.write(ind(ind) + "}\n\n"); out.write(ind(ind) + "private com.yahoo.document.ExtendedField ensureExtended(com.yahoo.document.Field f) {\n"); out.write(ind(ind+1) + "return (com.yahoo.document.ExtendedField)((f instanceof com.yahoo.document.ExtendedField) ? f : getField(f.getName()));\n"); out.write(ind(ind) + "}\n\n"); out.write(ind(ind) + "@Override public com.yahoo.document.Field getField(String fieldName) {\n"); out.write(ind(ind+1) + "if (fieldName==null) return null;\n"); out.write(ind(ind+1) + "return type.getField(fieldName);\n"); out.write(ind(ind) + "}\n\n"); } /** * Exports the struct types found in this collection of fields as separate Java classes */ private static Set<DataType> exportStructTypes(Collection<DataType> fields, Writer out, int ind, Set<DataType> exportedStructs) throws IOException { if (exportedStructs==null) exportedStructs=new HashSet<>(); for (DataType f : fields) { if ((f instanceof StructDataType) && ! f.getName().contains(".")) { if (exportedStructs.contains(f)) continue; exportedStructs.add(f); StructDataType structType = (StructDataType) f; String structClassName = className(structType.getName()); out.write(ind(ind)+"/**\n" + ind(ind)+" * Generated by vespa-documentgen-plugin, do not edit.\n" + ind(ind)+" * Input struct type: "+structType.getName()+"\n" + ind(ind)+" * Date: "+new Date()+"\n" + ind(ind)+" */\n" + ind(ind)+"@com.yahoo.document.Generated\n" + ind(ind) + "public static class "+structClassName+" extends com.yahoo.document.datatypes.Struct {\n\n" + ind(ind+1)+"/** The type of this.*/\n" + ind(ind+1)+"public static final com.yahoo.document.StructDataType type = getStructType();\n\n"); out.write(ind(ind+1)+"public "+structClassName+"() {\n" + ind(ind+2)+"super("+structClassName+".type);\n" + ind(ind+1)+"}\n\n"); exportCopyConstructor(structClassName, out, ind+1, false); exportExtendedStructTypeGetter(structClassName, structType.getName(), structType.getFields(), null, null, out, ind+1, "getStructType", "com.yahoo.document.StructDataType"); exportAssign(structType, structClassName, out, ind+1); exportFieldsAndAccessors(structClassName, structType.getFields(), out, ind+1, true); // Need these methods for serialization. // This can be improved by generating a method to serialize the struct _here_ (and one in the document), and use that in serialization. exportGetFields(structType.getFields(), out, ind+1); exportDocumentMethods(structType.getFields(), out, ind+1); exportHashCode(structType.getFields(), out, ind+1, "(getDataType() != null ? getDataType().hashCode() : 0)"); exportEquals(structClassName, structType.getFields(), out, ind+1); out.write(ind(ind)+"}\n\n"); } } return exportedStructs; } /** * Override this, serialization of structs relies on it */ private static void exportGetFieldCount(Collection<Field> fields, Writer out, int ind) throws IOException { out.write(ind(ind)+"@Override public int getFieldCount() {\n"); out.write(ind(ind+1)+"int ret=0;\n"); for (Field f : fields) { out.write(ind(ind+1)+"if ("+getter(f.getName())+"()!=null) ret++;\n"); } out.write(ind(ind+1)+"return ret;\n"); out.write(ind(ind)+"}\n\n"); } /** * Override the getFields() method of Struct, since serialization of Struct relies on it. */ private static void exportGetFields(Collection<Field> fields, Writer out, int ind) throws IOException { out.write(ind(ind)+"@Override public java.util.Set<java.util.Map.Entry<com.yahoo.document.Field, com.yahoo.document.datatypes.FieldValue>> getFields() {\n" + ind(ind+1)+"java.util.Map<com.yahoo.document.Field, com.yahoo.document.datatypes.FieldValue> ret = new java.util.LinkedHashMap<com.yahoo.document.Field, com.yahoo.document.datatypes.FieldValue>();\n"); for (Field f : fields) { out.write(ind(ind+1)+"if ("+getter(f.getName())+"()!=null) {\n"); out.write(ind(ind+2)+"com.yahoo.document.Field f = getField(\""+f.getName()+"\");\n"); out.write(ind(ind+2)+"ret.put(f, ((com.yahoo.document.ExtendedField)f).getFieldValue(this));\n"); out.write(ind(ind+1)+"}\n"); } out.write(ind(ind+1)+"return ret.entrySet();\n"); out.write(ind(ind)+"}\n\n"); } private static void exportAssign(StructDataType structType, String structClassName, Writer out, int ind) throws IOException { out.write(ind(ind)+"@Override public void assign(Object o) {\n"+ ind(ind+1)+"if (!(o instanceof "+structClassName+")) { super.assign(o); return; }\n"+ ind(ind+1)+structClassName+" other = ("+structClassName+")o;\n"); for (Field f: structType.getFields()) { out.write(ind(ind+1)+setter(f.getName())+"(other."+getter(f.getName())+"());\n"); } out.write(ind(ind)+"}\n\n"); } /** * Exports this set of fields with getters and setters * @param spanTrees If true, include a reference to the list of span trees for the string fields */ private static void exportFieldsAndAccessors(String className, Collection<Field> fields, Writer out, int ind, boolean spanTrees) throws IOException { // List the fields as Java fields for (Field field: fields) { DataType dt = field.getDataType(); out.write( ind(ind)+toJavaType(dt)+" "+field.getName()+";\n"); if (spanTrees && dt.equals(DataType.STRING)) { out.write(ind(ind)+"java.util.Map<java.lang.String,com.yahoo.document.annotation.SpanTree> "+spanTreeGetter(field.getName())+";\n"); // same name on field as get method } } out.write(ind(ind)+"\n"); // Getters, setters and annotation spantree lists for string fields for (Field field: fields) { DataType dt = field.getDataType(); out.write( ind(ind)+"public "+toJavaType(dt)+" "+getter(field.getName())+"() { return "+field.getName()+"; }\n"+ ind(ind)+"public "+className+" "+setter(field.getName())+"("+toJavaType(dt)+" "+field.getName()+") { this."+field.getName()+"="+field.getName()+"; return this; }\n"); if (spanTrees && dt.equals(DataType.STRING)) { out.write(ind(ind)+"public java.util.Map<java.lang.String,com.yahoo.document.annotation.SpanTree> "+spanTreeGetter(field.getName())+"() { return "+field.getName()+"SpanTrees; }\n" + ind(ind)+"public void "+spanTreeSetter(field.getName())+"(java.util.Map<java.lang.String,com.yahoo.document.annotation.SpanTree> spanTrees) { this."+field.getName()+"SpanTrees=spanTrees; }\n"); } } out.write("\n"); } private static String spanTreeSetter(String field) { return setter(field)+"SpanTrees"; } private static String spanTreeGetter(String field) { return field+"SpanTrees"; } /** * Returns spaces corresponding to the given levels of indentations */ private static String ind(int levels) { int indent = levels*STD_INDENT; StringBuilder sb = new StringBuilder(); for (int i = 0 ; i<indent ; i++) { sb.append(" "); } return sb.toString(); } /** * Returns spaces corresponding to 1 level of indentation */ private static String ind() { return ind(1); } private static String getter(String field) { return "get"+upperCaseFirstChar(field); } private static String setter(String field) { return "set"+upperCaseFirstChar(field); } private static String className(String field) { return upperCaseFirstChar(field); } private static String toJavaType(DataType dt) { if (DataType.NONE.equals(dt)) return "void"; if (DataType.INT.equals(dt)) return "java.lang.Integer"; if (DataType.FLOAT.equals(dt)) return "java.lang.Float"; if (DataType.STRING.equals(dt)) return "java.lang.String"; if (DataType.RAW.equals(dt)) return "java.nio.ByteBuffer"; if (DataType.LONG.equals(dt)) return "java.lang.Long"; if (DataType.DOUBLE.equals(dt)) return "java.lang.Double"; if (DataType.DOCUMENT.equals(dt)) return "com.yahoo.document.Document"; if (DataType.URI.equals(dt)) return "java.net.URI"; if (DataType.BYTE.equals(dt)) return "java.lang.Byte"; if (DataType.BOOL.equals(dt)) return "java.lang.Boolean"; if (DataType.TAG.equals(dt)) return "java.lang.String"; if (dt instanceof StructDataType) return className(dt.getName()); if (dt instanceof WeightedSetDataType) return "java.util.Map<"+toJavaType(((WeightedSetDataType)dt).getNestedType())+",java.lang.Integer>"; if (dt instanceof ArrayDataType) return "java.util.List<"+toJavaType(((ArrayDataType)dt).getNestedType())+">"; if (dt instanceof MapDataType) return "java.util.Map<"+toJavaType(((MapDataType)dt).getKeyType())+","+toJavaType(((MapDataType)dt).getValueType())+">"; if (dt instanceof AnnotationReferenceDataType) return className(((AnnotationReferenceDataType) dt).getAnnotationType().getName()); if (dt instanceof ReferenceDataType) { return "com.yahoo.document.DocumentId"; } if (dt instanceof TensorDataType) { return "com.yahoo.tensor.Tensor"; } return "byte[]"; } // bit stupid... private static String toJavaReference(DataType dt) { if (DataType.NONE.equals(dt)) return "com.yahoo.document.DataType.NONE"; if (DataType.INT.equals(dt)) return "com.yahoo.document.DataType.INT"; if (DataType.FLOAT.equals(dt)) return "com.yahoo.document.DataType.FLOAT"; if (DataType.STRING.equals(dt)) return "com.yahoo.document.DataType.STRING"; if (DataType.RAW.equals(dt)) return "com.yahoo.document.DataType.RAW"; if (DataType.LONG.equals(dt)) return "com.yahoo.document.DataType.LONG"; if (DataType.DOUBLE.equals(dt)) return "com.yahoo.document.DataType.DOUBLE"; if (DataType.DOCUMENT.equals(dt)) return "com.yahoo.document.DataType.DOCUMENT"; if (DataType.URI.equals(dt)) return "com.yahoo.document.DataType.URI"; if (DataType.BYTE.equals(dt)) return "com.yahoo.document.DataType.BYTE"; if (DataType.BOOL.equals(dt)) return "com.yahoo.document.DataType.BOOL"; if (DataType.TAG.equals(dt)) return "com.yahoo.document.DataType.TAG"; if (dt instanceof StructDataType) return className(dt.getName()) +".type"; if (dt instanceof WeightedSetDataType) return "new com.yahoo.document.WeightedSetDataType("+toJavaReference(((WeightedSetDataType)dt).getNestedType())+", "+ ((WeightedSetDataType)dt).createIfNonExistent()+", "+ ((WeightedSetDataType)dt).removeIfZero()+","+dt.getId()+")"; if (dt instanceof ArrayDataType) return "new com.yahoo.document.ArrayDataType("+toJavaReference(((ArrayDataType)dt).getNestedType())+")"; if (dt instanceof MapDataType) return "new com.yahoo.document.MapDataType("+toJavaReference(((MapDataType)dt).getKeyType())+", "+ toJavaReference(((MapDataType)dt).getValueType())+", "+dt.getId()+")"; // For annotation references and generated types, the references are to the actual objects of the correct types, so most likely this is never needed, // but there might be scenarios where we want to look up the AnnotationType in the AnnotationTypeRegistry here instead. if (dt instanceof AnnotationReferenceDataType) return "new com.yahoo.document.annotation.AnnotationReferenceDataType(new com.yahoo.document.annotation.AnnotationType(\""+((AnnotationReferenceDataType)dt).getAnnotationType().getName()+"\"))"; if (dt instanceof ReferenceDataType) { // All concrete document types have a public `type` constant with their DocumentType. return String.format("new com.yahoo.document.ReferenceDataType(%s.type, %d)", className(((ReferenceDataType) dt).getTargetType().getName()), dt.getId()); } if (dt instanceof TensorDataType) { return String.format("new com.yahoo.document.TensorDataType(com.yahoo.tensor.TensorType.fromSpec(\"%s\"))", ((TensorDataType)dt).getTensorType().toString()); } return "com.yahoo.document.DataType.RAW"; } @Override public void execute() { File dir = sdDirectory; // Prefer schemasDirectory if set if (this.schemasDirectory != null) dir = this.schemasDirectory; execute(dir, this.outputDirectory, packageName); } Map<String, Schema> getSearches() { return searches; } private static String upperCaseFirstChar(String s) { return s.substring(0, 1).toUpperCase()+s.substring(1); } }
package cn.ibizlab.core.uaa.client; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Collection; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.*; import cn.ibizlab.core.uaa.domain.SysUserAuth; import cn.ibizlab.core.uaa.filter.SysUserAuthSearchContext; import org.springframework.stereotype.Component; /** * 实体[SysUserAuth] 服务对象接口 */ @Component public class SysUserAuthFallback implements SysUserAuthFeignClient { public Page<SysUserAuth> select() { return null; } public SysUserAuth create(SysUserAuth sysuserauth) { return null; } public Boolean createBatch(List<SysUserAuth> sysuserauths) { return false; } public SysUserAuth update(String id, SysUserAuth sysuserauth) { return null; } public Boolean updateBatch(List<SysUserAuth> sysuserauths) { return false; } public Boolean remove(String id) { return false; } public Boolean removeBatch(Collection<String> idList) { return false; } public SysUserAuth get(String id) { return null; } public SysUserAuth getDraft(SysUserAuth entity){ return null; } public Boolean checkKey(SysUserAuth sysuserauth) { return false; } public Object saveEntity(SysUserAuth sysuserauth) { return null; } public Boolean save(SysUserAuth sysuserauth) { return false; } public Boolean saveBatch(List<SysUserAuth> sysuserauths) { return false; } public Page<SysUserAuth> searchDefault(SysUserAuthSearchContext context) { return null; } }
// Copyright 2004 The Apache Software Foundation // // 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 hivemind.test.services.impl; import hivemind.test.services.Bedrock; /** * Implementation of {@link hivemind.test.services.Bedrock}. * * @author Howard Lewis Ship */ public class BedrockImpl implements Bedrock { public void fred() { } public void barney() { } public void wilma() { } }
package com.eegeo.mapapi; import android.graphics.Point; import android.support.annotation.NonNull; import android.support.annotation.UiThread; import android.support.annotation.WorkerThread; import com.eegeo.mapapi.bluesphere.BlueSphere; import com.eegeo.mapapi.bluesphere.BlueSphereApi; import com.eegeo.mapapi.buildings.BuildingHighlight; import com.eegeo.mapapi.buildings.BuildingHighlightOptions; import com.eegeo.mapapi.buildings.BuildingsApi; import com.eegeo.mapapi.camera.CameraAnimationOptions; import com.eegeo.mapapi.camera.CameraApi; import com.eegeo.mapapi.camera.CameraPosition; import com.eegeo.mapapi.camera.CameraUpdate; import com.eegeo.mapapi.camera.CameraUpdateFactory; import com.eegeo.mapapi.camera.Projection; import com.eegeo.mapapi.geometry.LatLng; import com.eegeo.mapapi.geometry.LatLngAlt; import com.eegeo.mapapi.indoorentities.IndoorEntityApi; import com.eegeo.mapapi.indoorentities.IndoorMapEntityInformation; import com.eegeo.mapapi.indoorentities.IndoorMapEntityInformationApi; import com.eegeo.mapapi.indoorentities.IndoorEntityPickedMessage; import com.eegeo.mapapi.indoorentities.OnIndoorEntityPickedListener; import com.eegeo.mapapi.indoorentities.OnIndoorMapEntityInformationChangedListener; import com.eegeo.mapapi.indooroutlines.IndoorMapFloorOutlineInformation; import com.eegeo.mapapi.indooroutlines.IndoorMapFloorOutlineInformationApi; import com.eegeo.mapapi.indooroutlines.OnIndoorMapFloorOutlineInformationLoadedListener; import com.eegeo.mapapi.indoors.ExpandFloorsJniCalls; import com.eegeo.mapapi.indoors.IndoorMap; import com.eegeo.mapapi.indoors.IndoorsApiJniCalls; import com.eegeo.mapapi.indoors.OnFloorChangedListener; import com.eegeo.mapapi.indoors.OnIndoorEnterFailedListener; import com.eegeo.mapapi.indoors.OnIndoorEnteredListener; import com.eegeo.mapapi.indoors.OnIndoorExitedListener; import com.eegeo.mapapi.indoors.OnIndoorMapLoadedListener; import com.eegeo.mapapi.indoors.OnIndoorMapUnloadedListener; import com.eegeo.mapapi.map.EegeoMapOptions; import com.eegeo.mapapi.map.OnInitialStreamingCompleteListener; import com.eegeo.mapapi.markers.Marker; import com.eegeo.mapapi.markers.MarkerApi; import com.eegeo.mapapi.markers.MarkerOptions; import com.eegeo.mapapi.markers.OnMarkerClickListener; import com.eegeo.mapapi.picking.PickResult; import com.eegeo.mapapi.picking.PickingApi; import com.eegeo.mapapi.paths.PointOnPath; import com.eegeo.mapapi.paths.PathApi; import com.eegeo.mapapi.paths.PointOnRoute; import com.eegeo.mapapi.paths.PointOnRouteOptions; import com.eegeo.mapapi.polygons.Polygon; import com.eegeo.mapapi.polygons.PolygonApi; import com.eegeo.mapapi.polygons.PolygonOptions; import com.eegeo.mapapi.polylines.Polyline; import com.eegeo.mapapi.polylines.PolylineApi; import com.eegeo.mapapi.polylines.PolylineOptions; import com.eegeo.mapapi.heatmaps.Heatmap; import com.eegeo.mapapi.heatmaps.HeatmapApi; import com.eegeo.mapapi.heatmaps.HeatmapOptions; import com.eegeo.mapapi.positioner.OnPositionerChangedListener; import com.eegeo.mapapi.positioner.Positioner; import com.eegeo.mapapi.positioner.PositionerApi; import com.eegeo.mapapi.positioner.PositionerOptions; import com.eegeo.mapapi.precaching.PrecacheApi; import com.eegeo.mapapi.precaching.OnPrecacheOperationCompletedListener; import com.eegeo.mapapi.precaching.PrecacheOperation; import com.eegeo.mapapi.precaching.PrecacheOperationResult; import com.eegeo.mapapi.props.Prop; import com.eegeo.mapapi.props.PropOptions; import com.eegeo.mapapi.props.PropsApi; import com.eegeo.mapapi.rendering.RenderingApi; import com.eegeo.mapapi.rendering.RenderingState; import com.eegeo.mapapi.services.mapscene.Mapscene; import com.eegeo.mapapi.services.mapscene.MapsceneApi; import com.eegeo.mapapi.services.mapscene.MapsceneService; import com.eegeo.mapapi.services.poi.PoiApi; import com.eegeo.mapapi.services.poi.PoiSearchResult; import com.eegeo.mapapi.services.poi.PoiService; import com.eegeo.mapapi.services.routing.Route; import com.eegeo.mapapi.services.tag.TagApi; import com.eegeo.mapapi.services.tag.TagService; import com.eegeo.mapapi.services.routing.RoutingQueryResponse; import com.eegeo.mapapi.services.routing.RoutingApi; import com.eegeo.mapapi.services.routing.RoutingService; import com.eegeo.mapapi.util.Callbacks; import com.eegeo.mapapi.util.Promise; import com.eegeo.mapapi.util.Ready; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Main class representing a map. This class is the entry point for methods which change the camera, manage markers, * and handle indoor maps. * * An instance of this class can be obtained through the OnMapReadyCallback passed to the getMapAsync * method on the MapView object. * * Public methods on this class should be called from the Android UI thread. */ public final class EegeoMap { private final long m_eegeoMapApiPtr; private final INativeMessageRunner m_nativeRunner; private final IUiMessageRunner m_uiRunner; private List<OnCameraMoveListener> m_onCameraMoveListeners = new ArrayList<>(); private List<OnMapClickListener> m_onMapClickedListeners = new ArrayList<>(); private List<OnIndoorEnteredListener> m_onIndoorEnteredListeners = new ArrayList<>(); private List<OnIndoorExitedListener> m_onIndoorExitedListeners = new ArrayList<>(); private List<OnIndoorEnterFailedListener> m_onIndoorEnterFailedListeners = new ArrayList<>(); private List<OnIndoorMapLoadedListener> m_onIndoorMapLoadedListeners = new ArrayList<>(); private List<OnIndoorMapUnloadedListener> m_onIndoorMapUnloadedListeners = new ArrayList<>(); private List<OnFloorChangedListener> m_onIndoorFloorChangedListeners = new ArrayList<>(); private List<OnInitialStreamingCompleteListener> m_onInitialStreamingCompleteListeners = new ArrayList<>(); private CameraPosition m_cameraPosition = null; private IndoorMap m_indoorMap = null; private int m_currentIndoorFloor = -1; private Map<String, LatLngAlt> m_indoorMapEntryMarkerLocations = new HashMap<>(); private boolean m_transitioningToIndoorMap = false; private Projection m_projection; private CameraApi m_cameraApi; private MarkerApi m_markerApi; private PositionerApi m_positionerApi; private PolygonApi m_polygonApi; private PolylineApi m_polylineApi; private HeatmapApi m_heatmapApi; private PropsApi m_propsApi; private BlueSphereApi m_blueSphereApi; private BuildingsApi m_buildingsApi; private PickingApi m_pickingApi; private RenderingApi m_renderingApi; private RenderingState m_renderingState; private PoiApi m_poiApi; private TagApi m_tagApi; private MapsceneApi m_mapsceneApi; private RoutingApi m_routingApi; private PathApi m_pathApi; private BlueSphere m_blueSphere = null; private PrecacheApi m_precacheApi; private IndoorEntityApi m_indoorEntityApi; private IndoorMapEntityInformationApi m_indoorMapEntityInformationApi; private IndoorMapFloorOutlineInformationApi m_indoorMapFloorOutlineInformationApi; private static final AllowApiAccess m_allowApiAccess = new AllowApiAccess(); @WorkerThread EegeoMap(INativeMessageRunner nativeRunner, IUiMessageRunner uiRunner, EegeoNativeMapView.ICreateEegeoMapApi createNativeEegeoMapApi, EegeoMapOptions eegeoMapOptions ) { this.m_uiRunner = uiRunner; this.m_nativeRunner = nativeRunner; this.m_eegeoMapApiPtr = createNativeEegeoMapApi.create(this, eegeoMapOptions); this.m_projection = new Projection(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_cameraApi = new CameraApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_markerApi = new MarkerApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_positionerApi = new PositionerApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_polygonApi = new PolygonApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_polylineApi = new PolylineApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_heatmapApi = new HeatmapApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_propsApi = new PropsApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_blueSphereApi = new BlueSphereApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_buildingsApi = new BuildingsApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_pickingApi = new PickingApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_renderingApi = new RenderingApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); boolean mapCollapsed = false; this.m_renderingState = new RenderingState(m_renderingApi, m_allowApiAccess, mapCollapsed); this.m_poiApi = new PoiApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_tagApi = new TagApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_mapsceneApi = new MapsceneApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_routingApi = new RoutingApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_pathApi = new PathApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_precacheApi = new PrecacheApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_indoorEntityApi = new IndoorEntityApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_indoorMapEntityInformationApi = new IndoorMapEntityInformationApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); this.m_indoorMapFloorOutlineInformationApi = new IndoorMapFloorOutlineInformationApi(m_nativeRunner, m_uiRunner, m_eegeoMapApiPtr); } @WorkerThread void initialise(@NonNull EegeoMapOptions eegeoMapOptions) { m_cameraPosition = new CameraPosition.Builder(eegeoMapOptions.getCamera()).build(); initLocation(m_cameraPosition); } /** * Moves the camera change from its current position to a new position. * * @param update Specifies the new position, either by specifying the new camera position, or by describing the desired display area. */ @UiThread public void moveCamera(@NonNull final CameraUpdate update) { m_nativeRunner.runOnNativeThread(new Runnable() { @WorkerThread @Override public void run() { m_cameraApi.moveCamera(update); } }); } /** * Animates the camera change from its current position to a new position. * * @param update Specifies the new position, either by specifying the new camera position, or by describing the desired display area. * @param durationMs Length of time for the transition, in ms. */ @UiThread public void animateCamera(@NonNull final CameraUpdate update, final int durationMs) { final CameraAnimationOptions animationOptions = new CameraAnimationOptions.Builder() .duration(durationMs / 1000.0) .build(); animateCamera(update, animationOptions); } /** * Animates the camera change from its current position to a new position. * * @param update Specifies the new position, either by specifying the new camera position, or by describing the desired display area. * @param animationOptions The animation options for the camera transition. */ @UiThread public void animateCamera(@NonNull final CameraUpdate update, final CameraAnimationOptions animationOptions) { m_nativeRunner.runOnNativeThread(new Runnable() { @WorkerThread @Override public void run() { m_cameraApi.animateCamera(update, animationOptions); } }); } @WorkerThread private void initLocation(@NonNull CameraPosition cameraPosition) { m_cameraApi.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } /** * Returns the current projection. * * @return The current projection. */ @UiThread public Projection getProjection() { return m_projection; } /** * Stops any running camera animation. */ @UiThread public void stopAnimation() { m_nativeRunner.runOnNativeThread(new Runnable() { @Override public void run() { m_cameraApi.cancelAnimation(); } }); } /** * Registers a listener for camera move events. * * @param listener The listener to be notified. */ @UiThread public void addOnCameraMoveListener(@NonNull OnCameraMoveListener listener) { m_onCameraMoveListeners.add(listener); } /** * Unregisters a listener for camera move events. * * @param listener The listener to be removed. */ @UiThread public void removeOnCameraMoveListener(@NonNull OnCameraMoveListener listener) { m_onCameraMoveListeners.remove(listener); } /** * Registers a listener for user map point selection events. * * @param listener The listener to be notified. */ @UiThread public void addOnMapClickListener(@NonNull OnMapClickListener listener) { m_onMapClickedListeners.add(listener); } /** * Unregisters a listener for user map point selection events. * * @param listener The listener to be removed. */ @UiThread public void removeOnMapClickListener(@NonNull OnMapClickListener listener) { m_onMapClickedListeners.remove(listener); } /** * Gets the current camera position. * * @return The current camera position. */ @UiThread public final CameraPosition getCameraPosition() { return m_cameraPosition; } /** * Sets the camera to the specified CameraPosition. No transition or animation is applied. * * @param cameraPosition The new camera position. */ @UiThread public void setCameraPosition(@NonNull CameraPosition cameraPosition) { moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } /** * Enable or Disable the camera restriction when viewing Indoor Maps. When enabled, * the camera is unable to move outside the bounds of the Indoor Map. * @param indoorCameraRestriction Whether the restriction is enabled or disabled. */ @UiThread public void setIndoorCameraRestriction(final Boolean indoorCameraRestriction) { m_nativeRunner.runOnNativeThread(new Runnable() { @WorkerThread @Override public void run() { m_cameraApi.setIndoorCameraRestriction(indoorCameraRestriction); } }); } /** * Set the camera to focus on a particular screen coordinate, so it will rotate and zoom * around this point on screen. * @param point The screen space point, in units of pixels with the origin at the top left * corner of the screen. */ @UiThread public void setCameraScreenSpaceOffset(@NonNull final Point point) { m_nativeRunner.runOnNativeThread(new Runnable() { @WorkerThread @Override public void run() { m_cameraApi.setCameraScreenSpaceOffset(point.x, point.y); } }); } /** * Disable any previously set screen space offset set by setCameraScreenSpaceOffset amd * resume the default behavior. */ @UiThread public void disableCameraScreenSpaceOffset() { m_nativeRunner.runOnNativeThread(new Runnable() { @WorkerThread @Override public void run() { m_cameraApi.disableCameraScreenSpaceOffset(); } }); } /** * Called from the SDK when the screen has been tapped. * * @param point Screen coordinates of the tapped point. */ @UiThread public void onTapped(final Point point) { m_projection.fromScreenLocation(point) .then(new Ready<LatLngAlt>() { @UiThread @Override public void ready(LatLngAlt latLngAlt) { for (OnMapClickListener listener : m_onMapClickedListeners) { listener.onMapClick(latLngAlt); } } }); } @WorkerThread private void jniOnCameraMove() { m_uiRunner.runOnUiThread(new Runnable() { @UiThread @Override public void run() { for (OnCameraMoveListener listener : m_onCameraMoveListeners) { listener.onCameraMove(); } } }); } @WorkerThread private void jniSetCameraPosition(final CameraPosition cameraPosition) { m_uiRunner.runOnUiThread(new Runnable() { @UiThread @Override public void run() { m_cameraPosition = cameraPosition; } }); } /** * Show the expanded indoor map view. */ @UiThread public void expandIndoor() { m_nativeRunner.runOnNativeThread(new Runnable() { public void run() { ExpandFloorsJniCalls.expandIndoor(m_eegeoMapApiPtr); } }); } /** * Show the collapsed indoor map view. */ @UiThread public void collapseIndoor() { m_nativeRunner.runOnNativeThread(new Runnable() { @WorkerThread @Override public void run() { ExpandFloorsJniCalls.collapseIndoor(m_eegeoMapApiPtr); } }); } /** * Gets the active indoor map. * * @return The active indoor map, or null if no indoor map is active. */ @UiThread public IndoorMap getActiveIndoorMap() { return m_indoorMap; } /** * Gets the active floor of the current indoor map. * * @return The index of the active floor of the current indoor map, or -1 if no indoor map is active. */ @UiThread public int getCurrentFloorIndex() { return m_currentIndoorFloor; } /** * Registers a listener for indoor map entrance events. * * @param listener The listener to be notified when the user taps an indoor entrance marker. */ @UiThread public void addOnIndoorEnteredListener(@NonNull OnIndoorEnteredListener listener) { m_onIndoorEnteredListeners.add(listener); } /** * Unregisters a listener for indoor map entrance events. * * @param listener The listener to be removed */ @UiThread public void removeOnIndoorEnteredListener(@NonNull OnIndoorEnteredListener listener) { m_onIndoorEnteredListeners.remove(listener); } @WorkerThread private void jniOnIndoorEntered() { final IndoorMap indoorMap = IndoorsApiJniCalls.getIndoorMapData(m_eegeoMapApiPtr); final int currentIndoorFloor = IndoorsApiJniCalls.getCurrentFloorIndex(m_eegeoMapApiPtr); m_uiRunner.runOnUiThread(new Runnable() { @UiThread @Override public void run() { m_indoorMap = indoorMap; m_currentIndoorFloor = currentIndoorFloor; m_transitioningToIndoorMap = false; for (OnIndoorEnteredListener listener : m_onIndoorEnteredListeners) { listener.onIndoorEntered(); } } }); } /** * Registers a listener for indoor map exit events. * * @param listener The listener to be notified when the user exits an indoor map. */ @UiThread public void addOnIndoorExitedListener(@NonNull OnIndoorExitedListener listener) { m_onIndoorExitedListeners.add(listener); } /** * Unregisters a listener for indoor map exit events. * * @param listener The listener to be removed. */ @UiThread public void removeOnIndoorExitedListener(@NonNull OnIndoorExitedListener listener) { m_onIndoorExitedListeners.remove(listener); } /** * Registers a listener for indoor map enter failed events. * * @param listener The listener to be notified when the user fails to enter an indoor map. */ @UiThread public void addOnIndoorEnterFailedListener(@NonNull OnIndoorEnterFailedListener listener) { m_onIndoorEnterFailedListeners.add(listener); } /** * Unregisters a listener for indoor map failed events. * * @param listener The listener to be removed. */ @UiThread public void removeOnIndoorEnterFailedListener(@NonNull OnIndoorEnterFailedListener listener) { m_onIndoorEnterFailedListeners.remove(listener); } /** * Registers a listener for indoor map loaded events. * * @param listener The listener to be notified when an indoor map is loaded. */ @UiThread public void addOnIndoorMapLoadedListener(@NonNull OnIndoorMapLoadedListener listener) { m_onIndoorMapLoadedListeners.add(listener); } /** * Unregisters a listener for indoor map unloaded events. * * @param listener The listener to be removed. */ @UiThread public void removeOnIndoorMapLoadedListener(@NonNull OnIndoorMapLoadedListener listener) { m_onIndoorMapLoadedListeners.remove(listener); } /** * Registers a listener for indoor map unloaded events. * * @param listener The listener to be notified when an indoor map is unloaded. */ @UiThread public void addOnIndoorMapUnloadedListener(@NonNull OnIndoorMapUnloadedListener listener) { m_onIndoorMapUnloadedListeners.add(listener); } /** * Unregisters a listener for indoor map unloaded events. * * @param listener The listener to be removed. */ @UiThread public void removeOnIndoorMapUnloadedListener(@NonNull OnIndoorMapUnloadedListener listener) { m_onIndoorMapUnloadedListeners.remove(listener); } /** * Exits the current indoor map. */ @UiThread @Deprecated public void onExitIndoorClicked() { m_nativeRunner.runOnNativeThread(new Runnable() { public void run() { IndoorsApiJniCalls.exitIndoorMap(m_eegeoMapApiPtr); } }); } /** * Exits the current indoor map. */ @UiThread public void exitIndoorMap() { m_nativeRunner.runOnNativeThread(new Runnable() { public void run() { IndoorsApiJniCalls.exitIndoorMap(m_eegeoMapApiPtr); } }); } /** * Enters the specified indoor map. * @param indoorMapId The id of the indoor map to enter */ @UiThread public boolean enterIndoorMap(final String indoorMapId) { if (getActiveIndoorMap() != null || m_transitioningToIndoorMap) { return false; } if (!m_indoorMapEntryMarkerLocations.containsKey(indoorMapId)) { return false; } m_transitioningToIndoorMap = true; LatLngAlt location = m_indoorMapEntryMarkerLocations.get(indoorMapId); CameraPosition position = new CameraPosition.Builder() .target(location.latitude, location.longitude) .indoor(indoorMapId) .zoom(19) .build(); CameraAnimationOptions animationOptions = new CameraAnimationOptions.Builder() .interruptByGestureAllowed(false) .build(); animateCamera(CameraUpdateFactory.newCameraPosition(position), animationOptions); return true; } @WorkerThread private void jniOnIndoorExited() { m_uiRunner.runOnUiThread(new Runnable() { public void run() { m_indoorMap = null; m_currentIndoorFloor = -1; for (OnIndoorExitedListener listener : m_onIndoorExitedListeners) { listener.onIndoorExited(); } } }); } @WorkerThread private void jniOnIndoorEnterFailed(final String indoorMapId) { m_uiRunner.runOnUiThread(new Runnable() { public void run() { m_indoorMap = null; m_currentIndoorFloor = -1; m_transitioningToIndoorMap = false; for (OnIndoorEnterFailedListener listener : m_onIndoorEnterFailedListeners) { listener.OnIndoorEnterFailed(indoorMapId); } } }); } /** * Sets the current floor shown in an indoor map. * * @param selectedFloor The index of the floor to be shown, relative to the * array returned by IndoorMap.getFloorIds() */ @UiThread public void setIndoorFloor(final int selectedFloor) { m_nativeRunner.runOnNativeThread(new Runnable() { @WorkerThread @Override public void run() { IndoorsApiJniCalls.floorSelected(m_eegeoMapApiPtr, selectedFloor); } }); } /** * Moves up one floor in the current indoor map. */ @UiThread public void moveIndoorUp() { moveIndoorUp(1); } /** * Moves up a number of floors in the current indoor map. * * @param numberOfFloors The number of floors to move up. */ @UiThread public void moveIndoorUp(final int numberOfFloors) { moveIndoorFloors(numberOfFloors); } /** * Moves down one floor in the current indoor map. */ @UiThread public void moveIndoorDown() { moveIndoorDown(1); } /** * Moves down a number of floors in the current indoor map. * * @param numberOfFloors The number of floors to move down */ @UiThread public void moveIndoorDown(final int numberOfFloors) { moveIndoorFloors(-numberOfFloors); } private void moveIndoorFloors(final int delta) { m_nativeRunner.runOnNativeThread(new Runnable() { public void run() { m_currentIndoorFloor = IndoorsApiJniCalls.getCurrentFloorIndex(m_eegeoMapApiPtr); IndoorsApiJniCalls.floorSelected(m_eegeoMapApiPtr, m_currentIndoorFloor + delta); } }); } /** * Sets the interpolation value used in the expanded indoor view. * * @param dragParameter The float value, in the range 0 .. number of floors. */ @UiThread public void setIndoorFloorInterpolation(final float dragParameter) { m_nativeRunner.runOnNativeThread(new Runnable() { public void run() { IndoorsApiJniCalls.floorSelectionDragged(m_eegeoMapApiPtr, dragParameter); } }); } @UiThread public void setExitIndoorWhenTooFarAway(final Boolean exitWhenFarAway) { m_nativeRunner.runOnNativeThread(new Runnable() { @WorkerThread @Override public void run() { IndoorsApiJniCalls.setExitIndoorWhenTooFarAway(m_eegeoMapApiPtr, exitWhenFarAway); } }); } /** * Registers a listener for indoor map floor change events. * * @param listener The listener to be notified. */ @UiThread public void addOnFloorChangedListener(@NonNull OnFloorChangedListener listener) { m_onIndoorFloorChangedListeners.add(listener); } /** * Unregisters a listener for indoor map floor change events. * * @param listener The listener to be removed. */ @UiThread public void removeOnFloorChangedListener(@NonNull OnFloorChangedListener listener) { m_onIndoorFloorChangedListeners.remove(listener); } @WorkerThread private void jniOnFloorChanged(final int selectedFloor) { m_uiRunner.runOnUiThread(new Runnable() { @UiThread @Override public void run() { m_currentIndoorFloor = selectedFloor; for (OnFloorChangedListener listener : m_onIndoorFloorChangedListeners) { listener.onFloorChanged(m_currentIndoorFloor); } } }); } /** * Create a marker and add it to the map. * * @param markerOptions Creation parameters for the marker * @return The Marker that was added */ @UiThread public Marker addMarker(@NonNull final MarkerOptions markerOptions) { return new Marker(m_markerApi, markerOptions); } /** * Remove a marker from the map and destroy it. * * @param marker The Marker to remove. */ @UiThread public void removeMarker(@NonNull final Marker marker) { marker.destroy(); } /** * Create a positioner and add it to the map. * * @param positionerOptions Creation parameters for the positioner * @return The Positioner that was added */ @UiThread public Positioner addPositioner(@NonNull final PositionerOptions positionerOptions) { return new Positioner(m_positionerApi, positionerOptions); } /** * Remove a positioner from the map and destroy it. * * @param positioner The Positioner to remove. */ @UiThread public void removePositioner(@NonNull final Positioner positioner) { positioner.destroy(); } /** * Create a polygon and add it to the map. * * @param polygonOptions Creation parameters for the marker * @return The Polygon that was added */ @UiThread public Polygon addPolygon(@NonNull final PolygonOptions polygonOptions) { return new Polygon(m_polygonApi, polygonOptions); } /** * Remove a polygon from the map and destroy it. * * @param polygon The Polygon to remove. */ @UiThread public void removePolygon(@NonNull final Polygon polygon) { polygon.destroy(); } /** * Create a polyline and add it to the map. * * @param polylineOptions Creation parameters for the polyline * @return The Polyline that was added */ @UiThread public Polyline addPolyline(@NonNull final PolylineOptions polylineOptions) { return new Polyline(m_polylineApi, polylineOptions); } /** * Remove a polyline from the map and destroy it. * * @param polyline The Polyline to remove. */ @UiThread public void removePolyline(@NonNull final Polyline polyline) { polyline.destroy(); } /** * Create a heatmap and add it to the map. * * @param heatmapOptions Creation parameters for the marker * @return The Heatmap that was added */ @UiThread public Heatmap addHeatmap(@NonNull final HeatmapOptions heatmapOptions) { return new Heatmap(m_heatmapApi, heatmapOptions); } /** * Remove a heatmap from the map and destroy it. * * @param heatmap The Heatmap to remove. */ @UiThread public void removeHeatmap(@NonNull final Heatmap heatmap) { heatmap.destroy(); } /** * Create a building highlight and add it to the map. * * @param buildingHighlightOptions Creation parameters for the building highlight * @return The BuildingHighlight that was added */ @UiThread public BuildingHighlight addBuildingHighlight(@NonNull final BuildingHighlightOptions buildingHighlightOptions) { return new BuildingHighlight(m_buildingsApi, buildingHighlightOptions); } /** * Remove a BuildingHighlight from the map and destroy it. * * @param buildingHighlight The BuildingHighlight to remove. */ @UiThread public void removeBuildingHighlight(@NonNull final BuildingHighlight buildingHighlight) { buildingHighlight.destroy(); } /** * Create a prop and add it to the map. * * @param propOptions Creation parameters for the prop * @return The Prop that was added */ @UiThread public Prop addProp(@NonNull final PropOptions propOptions) { return new Prop(m_propsApi, propOptions); } /** * Remove a prop from the map and destroy it. * * @param prop The Prop to remove. */ @UiThread public void removeProp(@NonNull final Prop prop) { prop.destroy(); } /** * Attempts to find a map feature at the given screen point. A ray is constructed from the * camera location and passing through the screen point. The first intersection of the ray with * any of the currently streamed map features is found, if any. * See PickResult for details of information returned. * * @param point A screen space point, in units of pixels with the origin at the top left * corner of the screen. * @return A promise to provide information about the map feature intersected with, if any. * @eegeo.codeintro The value of the promise can be accessed through an object implementing the Ready interface, for example: * @eegeo.code <pre> * map.pickFeatureAtScreenPoint(point) * .then(new Ready&lt;PickResult&gt;() { * public void ready(PickResult pickResult) { * // use value of pickResult here * } * } * ); * </pre> */ @UiThread public Promise<PickResult> pickFeatureAtScreenPoint(@NonNull final Point point) { return m_pickingApi.pickFeatureAtScreenPoint(point); } /** * Attempts to find a map feature at the given LatLng location. * See PickResult for details of information returned. * @param latLng A LatLng coordinate. * @return A promise to provide information about the map feature intersected with, if any. * @eegeo.codeintro The value of the promise can be accessed through an object implementing the Ready interface, for example: * @eegeo.code <pre> * map.pickFeatureAtLatLng(point) * .then(new Ready&lt;PickResult&gt;() { * public void ready(PickResult pickResult) { * // use value of pickResult here * } * } * ); * </pre> */ @UiThread public Promise<PickResult> pickFeatureAtLatLng(@NonNull final LatLng latLng) { return m_pickingApi.pickFeatureAtLatLng(latLng); } /** * Gets the BlueSphere * * @return The BlueSphere. */ @UiThread public BlueSphere getBlueSphere() { if(m_blueSphere == null) { m_blueSphere = new BlueSphere(m_blueSphereApi); } return m_blueSphere; } /** * Sets whether the map view should display with vertical scaling applied so that terrain and * other map features appear flattened. */ @UiThread public void setMapCollapsed(final boolean isCollapsed) { m_renderingState.setMapCollapsed(isCollapsed); } @UiThread public boolean isMapCollapsed() { return m_renderingState.isMapCollapsed(); } /** * Sets highlights on a list of indoor map entities to the specified ARGB color. */ public void setIndoorEntityHighlights(final String indoorMapId, final Collection<String> indoorEntityIds, final int highlightColorARGB) { List<String> indoorEntityIdsList = new ArrayList<String>(indoorEntityIds); m_indoorEntityApi.setIndoorEntityHighlights(indoorMapId, indoorEntityIdsList, highlightColorARGB); } /** * Clears the highlights from a list of indoor map entities. */ public void clearIndoorEntityHighlights(final String indoorMapId, final Collection<String> indoorEntityIds) { List<String> indoorEntityIdsList = new ArrayList<String>(indoorEntityIds); m_indoorEntityApi.clearIndoorEntityHighlights(indoorMapId, indoorEntityIdsList); } /** * Clears all indoor entity highlights. */ public void clearAllIndoorEntityHighlights() { m_indoorEntityApi.clearAllIndoorEntityHighlights(); } /** * Adds an IndoorMapEntityInformation object, that will become populated with the ids * of any indoor map entities belonging to the specified indoor map as map tiles stream in. * @param indoorMapId The id of the indoor map to obtain entity information for. * @param indoorMapEntityInformationChangedListener A listener object to obtain notification * when the IndoorMapEntityInformation has been * updated with indoor map entity ids. * @return The IndoorMapEntityInformation instance. */ public IndoorMapEntityInformation addIndoorMapEntityInformation( @NonNull final String indoorMapId, final OnIndoorMapEntityInformationChangedListener indoorMapEntityInformationChangedListener ) { return new IndoorMapEntityInformation(m_indoorMapEntityInformationApi, indoorMapId, indoorMapEntityInformationChangedListener); } /** * Remove an IndoorMapEntityInformation object, previously added via addIndoorMapEntityInformation. * @param indoorMapEntityInformation The IndoorMapEntityInformation instance to remove. */ public void removeIndoorMapEntityInformation(@NonNull final IndoorMapEntityInformation indoorMapEntityInformation) { indoorMapEntityInformation.destroy(); } /** * Adds an IndoorMapFloorOutlineInformation object, that will become populated with the outline * of the specified indoor map floor as map tiles stream in. * @param indoorMapId The id of the indoor map. * @param indoorMapFloorId The id of the indoor map floor to obtain outline information for. * @param indoorMapFloorOutlineInformationLoadedListener A listener object to obtain notification * when the IndoorMapFloorOutlineInformation has been * updated with outline. * @return The IndoorMapFloorOutlineInformation instance. */ @UiThread public IndoorMapFloorOutlineInformation addIndoorMapFloorOutlineInformation( @NonNull final String indoorMapId, final int indoorMapFloorId, final OnIndoorMapFloorOutlineInformationLoadedListener indoorMapFloorOutlineInformationLoadedListener ) { return new IndoorMapFloorOutlineInformation(m_indoorMapFloorOutlineInformationApi, indoorMapId, indoorMapFloorId, indoorMapFloorOutlineInformationLoadedListener); } /** * Remove an IndoorMapFloorOutlineInformation object, previously added via addIndoorMapFloorOutlineInformation. * @param indoorMapFloorOutlineInformation The IndoorMapFloorOutlineInformation instance to remove. */ @UiThread public void removeIndoorMapFloorOutlineInformation(@NonNull final IndoorMapFloorOutlineInformation indoorMapFloorOutlineInformation) { indoorMapFloorOutlineInformation.destroy(); } /** * Creates and returns a PoiService for this map. * * @return A new PoiService object. */ @UiThread public PoiService createPoiService() { PoiService poiService = new PoiService(m_poiApi); return poiService; } /** * Creates and returns a TagService for this map * @return A new TagService object. */ @UiThread public TagService createTagService() { TagService tagService = new TagService(m_tagApi); return tagService; } /** * Creates and returns a MapsceneService for this map. * * @return A new MapsceneService object. */ public MapsceneService createMapsceneService() { MapsceneService mapsceneService = new MapsceneService(m_mapsceneApi, this); return mapsceneService; } /** * Creates and returns a RoutingService for this map. * * @return A new RoutingService object. */ @UiThread public RoutingService createRoutingService() { RoutingService routingService = new RoutingService(m_routingApi); return routingService; } /** * Register a listener to an event raised when a marker is tapped by the user. * * @param listener the listener to add */ @UiThread public void addMarkerClickListener(@NonNull OnMarkerClickListener listener) { m_markerApi.addMarkerClickListener(listener); } /** * Unregister a listener to an event raised when a marker is tapped by the user. * * @param listener the listener to remove */ @UiThread public void removeMarkerClickListener(@NonNull OnMarkerClickListener listener) { m_markerApi.removeMarkerClickListener(listener); } /** * Register a listener to an event raised when a Positioner object has changed position. * * @param listener the listener to add */ @UiThread public void addPositionerChangedListener(@NonNull OnPositionerChangedListener listener) { m_positionerApi.addPositionerChangedListener(listener); } /** * Unregister a listener to an event raised when a Positioner object has changed position. * * @param listener the listener to remove */ @UiThread public void removePositionerChangedListener(@NonNull OnPositionerChangedListener listener) { m_positionerApi.removePositionerChangedListener(listener); } /** * Register a listener to an event raised when one or more indoor map entities are clicked or tapped by the user. * * @param listener the listener to add */ @UiThread public void addOnIndoorEntityPickedListener(@NonNull OnIndoorEntityPickedListener listener) { m_indoorEntityApi.addOnIndoorEntityPickedListener(listener); } /** * Unregister a listener to an event raised when one or more indoor map entities are clicked or tapped by the user. * * @param listener the listener to remove */ @UiThread public void removeOnIndoorEntityPickedListener(@NonNull OnIndoorEntityPickedListener listener) { m_indoorEntityApi.removeOnIndoorEntityPickedListener(listener); } /** * Begin an operation to precache a spherical area of the map. This allows that area to load * faster in future. * * @param center The center of the area to precache. * @param radius The radius (in meters) of the area to precache. * @param callback The function to call when the precache operation completes. The function will * be passed a boolean indicating whether the precache completed successfully. * * @return an object with a cancel() method to allow you to cancel the precache operation. */ @UiThread public PrecacheOperation precache( final LatLng center, final double radius, final OnPrecacheOperationCompletedListener callback) throws IllegalArgumentException { final double maximumPrecacheRadius = m_precacheApi.getMaximumPrecacheRadius(); if (radius < 0.0 || radius > maximumPrecacheRadius) { throw new IllegalArgumentException( String.format("radius %f outside of valid (0, %f] range.", radius, maximumPrecacheRadius)); } return m_precacheApi.precache(center, radius, callback); } /** * Gets the maximum radius value that can be passed to precache(center, radius, callback) * * @return the maxium radius that may be passed to precache, in meters */ @UiThread public double getMaximumPrecacheRadius() { return m_precacheApi.getMaximumPrecacheRadius(); } @WorkerThread private void jniOnMarkerClicked(final int markerId) { m_markerApi.notifyMarkerClicked(markerId); } @WorkerThread private void jniOnBuildingInformationReceived(final int buildingHighlightId) { m_buildingsApi.notifyBuildingInformationReceived(buildingHighlightId); } @WorkerThread private void jniOnPositionerProjectionChanged() { m_positionerApi.notifyProjectionChanged(); } @WorkerThread private void jniOnPoiSearchCompleted(final int poiSearchId, final boolean succeeded, final List<PoiSearchResult> searchResults) { m_poiApi.notifySearchComplete(poiSearchId, succeeded, searchResults); } @WorkerThread private void jniOnMapsceneRequestCompleted(final int mapsceneRequestId, final boolean succeeded, final Mapscene mapscene) { m_mapsceneApi.notifyRequestComplete(mapsceneRequestId, succeeded, mapscene); } @WorkerThread private void jniOnSearchTagsLoaded() { m_tagApi.notifyTagsLoaded(); } @WorkerThread private void jniOnPrecacheQueryCompleted(final int precacheOperationId, PrecacheOperationResult result) { m_precacheApi.notifyPrecacheOperationComplete(precacheOperationId, result); } @WorkerThread private void jniOnRoutingQueryCompleted(final int routingQueryId, RoutingQueryResponse response) { m_routingApi.notifyQueryComplete(routingQueryId, response); } @WorkerThread private void jniOnIndoorEntityPicked(IndoorEntityPickedMessage message) { m_indoorEntityApi.notifyIndoorEntityPicked(message); } @WorkerThread private void jniOnIndoorMapEntityInformationChanged(final int indoorMapEntityInformationId) { m_indoorMapEntityInformationApi.notifyIndoorMapEntityInformationChanged(indoorMapEntityInformationId); } @WorkerThread private void jniOnIndoorMapFloorOutlineInformationLoaded(final int indoorMapFloorOutlineInformationId) { m_indoorMapFloorOutlineInformationApi.notifyIndoorMapFloorOutlineInformationLoaded(indoorMapFloorOutlineInformationId); } @WorkerThread private void jniOnIndoorMapLoaded(final String indoorMapId) { m_uiRunner.runOnUiThread(new Runnable() { public void run() { for (OnIndoorMapLoadedListener listener : m_onIndoorMapLoadedListeners) { listener.onIndoorMapLoaded(indoorMapId); } } }); } @WorkerThread private void jniOnIndoorMapUnloaded(final String indoorMapId) { m_uiRunner.runOnUiThread(new Runnable() { public void run() { for (OnIndoorMapUnloadedListener listener : m_onIndoorMapUnloadedListeners) { listener.onIndoorMapUnloaded(indoorMapId); } } }); } @WorkerThread private void jniOnIndoorEntryMarkerAdded(final String indoorMapId, final LatLngAlt location) { m_uiRunner.runOnUiThread(new Runnable() { public void run() { m_indoorMapEntryMarkerLocations.put(indoorMapId, location); } }); } @WorkerThread private void jniOnIndoorEntryMarkerRemoved(final String indoorMapId) { m_uiRunner.runOnUiThread(new Runnable() { public void run() { m_indoorMapEntryMarkerLocations.remove(indoorMapId); } }); } /** * Registers a listener to an event raised when the initial map scene has completed streaming all resources * * @param listener The listener to be notified. */ @UiThread public void addInitialStreamingCompleteListener(@NonNull OnInitialStreamingCompleteListener listener) { m_onInitialStreamingCompleteListeners.add(listener); } /** * Unregisters a listener of the initial streaming complete event * * @param listener The listener to be removed. */ @UiThread public void removeInitialStreamingCompleteListener(@NonNull OnInitialStreamingCompleteListener listener) { m_onInitialStreamingCompleteListeners.remove(listener); } @WorkerThread private void jniNotifyInitialStreamingComplete() { m_uiRunner.runOnUiThread(new Runnable() { @UiThread @Override public void run() { for (OnInitialStreamingCompleteListener listener : m_onInitialStreamingCompleteListeners) { listener.onInitialStreamingComplete(); } } }); } /** * Interface for objects which receive notifications of changes to the camera. */ public interface OnCameraMoveListener { @UiThread void onCameraMove(); } /** * Interface for objects which receive notifications when the user taps on the map. */ public interface OnMapClickListener { @UiThread void onMapClick(LatLngAlt point); } private class OnCameraMoveListenerImpl implements Callbacks.ICallback0 { private OnCameraMoveListener m_listener; @UiThread public OnCameraMoveListenerImpl(OnCameraMoveListener listener) { this.m_listener = listener; } @UiThread public void onCallback() { m_listener.onCameraMove(); } } /** * Retrieve information about the closest point on a Route to a given input point. * * @param point The input point to find the closest point on the Route with. * @param route The Route that should be tested against. * @param pointOnRouteOptions Additional options for the Route; e.g, Indoor Map Id. */ @UiThread public Promise<PointOnRoute> getPointOnRoute(LatLng point, Route route, PointOnRouteOptions pointOnRouteOptions) { return m_pathApi.getPointOnRoute(point, route, pointOnRouteOptions); } /** * Retrieve information about the closest point on a Path to a given input point. * * @param point The input point to find the closest point on the Path with. * @param path The Path that should be tested against. */ @UiThread public Promise<PointOnPath> getPointOnPath(LatLng point, List<LatLng> path) { return m_pathApi.getPointOnPath(point, path); } public static final class AllowApiAccess { @WorkerThread private AllowApiAccess() { } } }
package com.dinuscxj.shootrefreshview; import android.content.Context; public class DensityUtil { public static float dp2px(Context context, float dpValue) { float scale = context.getResources().getDisplayMetrics().density; return dpValue * scale; } }
package com.caacetc.common.config; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; @Configuration @EnableAsync public class SpringAsyncConfig { // @Bean // public AsyncTaskExecutor taskExecutor() { // ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // executor.setMaxPoolSize(10); // return executor; // } }
package com.ph1ash.dexter.beeplepaper; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.Wearable; public class MainActivity extends Activity { private static final String TAG = "BeepleMobile"; private CallbackManager callbackManager; private GoogleApiClient mClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .build(); mClient.connect(); Intent sIntent = new Intent(this, BeeplePaperService.class); startService(sIntent); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_main); final Button btn = (Button) findViewById(R.id.mButt); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent mIntent = new Intent (Intent.ACTION_SEND); sendBroadcast(mIntent); } }); callbackManager = CallbackManager.Factory.create(); Log.d(TAG,"Building login button for FB"); LoginButton loginButton = (LoginButton) findViewById(R.id.login_button); loginButton.setReadPermissions("user_friends"); loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { Log.d(TAG, "Getting access token"); } @Override public void onCancel() { Log.d(TAG, "Login Cancelled"); } @Override public void onError(FacebookException exception) { Log.e(TAG, exception.toString()); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "Getting results"); super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } }
package com.baurine.multitypeadaptertutorial.item; import android.view.View; import com.android.databinding.library.baseAdapters.BR; import com.baurine.multitypeadapter.MultiTypeAdapter; /** * Created by baurine on 1/10/17. */ public abstract class BaseItem implements MultiTypeAdapter.IItem { @Override public int getVariableId() { return BR.item; } //////////////////////////////////////////// // handle event private View.OnClickListener onClickListener; public View.OnClickListener getOnClickListener() { return onClickListener; } public void setOnClickListener(View.OnClickListener onClickListener) { this.onClickListener = onClickListener; } }
package com.sagui.model.layout; public interface IFatuLayoutManager<RULE extends IFatuLayoutRule<?>> { public void setRule(String id, RULE rule); public RULE getRule(String id); }
/** * 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.rya.indexing.entity.query; import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import org.apache.rya.api.domain.RyaType; import org.apache.rya.api.domain.RyaURI; import org.apache.rya.api.resolver.RdfToRyaConversions; import org.apache.rya.indexing.entity.model.Entity; import org.apache.rya.indexing.entity.model.Property; import org.apache.rya.indexing.entity.model.Type; import org.apache.rya.indexing.entity.model.TypedEntity; import org.apache.rya.indexing.entity.storage.EntityStorage; import org.apache.rya.indexing.entity.storage.EntityStorage.EntityStorageException; import org.apache.rya.indexing.entity.storage.mongo.ConvertingCursor; import org.apache.rya.indexing.entity.update.EntityIndexer; import org.apache.rya.rdftriplestore.evaluation.ExternalBatchingIterator; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.RDF; import org.openrdf.query.Binding; import org.openrdf.query.BindingSet; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.Var; import org.openrdf.query.algebra.evaluation.impl.ExternalSet; import org.openrdf.query.algebra.evaluation.iterator.CollectionIteration; import org.openrdf.query.impl.MapBindingSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import edu.umd.cs.findbugs.annotations.DefaultAnnotation; import edu.umd.cs.findbugs.annotations.NonNull; import info.aduna.iteration.CloseableIteration; /** * Indexing Node for {@link Entity} expressions to be inserted into execution plan * to delegate entity portion of query to {@link EntityIndexer}. */ @DefaultAnnotation(NonNull.class) public class EntityQueryNode extends ExternalSet implements ExternalBatchingIterator { private static final Logger LOG = LoggerFactory.getLogger(EntityQueryNode.class); /** * The RyaURI that when used as the Predicate of a Statement Pattern indicates the Type of the Entities. */ private static final RyaURI TYPE_ID_URI = new RyaURI(RDF.TYPE.toString()); // Provided at construction time. private final Type type; private final Collection<StatementPattern> patterns; private final EntityStorage entities; // Information about the subject of the patterns. private final boolean subjectIsConstant; private final Optional<String> subjectConstant; private final Optional<String> subjectVar; //since and EntityQueryNode exists in a single segment, all binding names are garunteed to be assured. private final Set<String> bindingNames; // Information about the objects of the patterns. private final ImmutableMap<RyaURI, Var> objectVariables; // Properties of the Type found in the query private final Set<Property> properties; /** * Constructs an instance of {@link EntityQueryNode}. * * @param type - The type of {@link Entity} this node matches. (not null) * @param patterns - The query StatementPatterns that are solved using an * Entity of the Type. (not null) * @param entities - The {@link EntityStorage} that will be searched to match * {@link BindingSet}s when evaluating a query. (not null) */ public EntityQueryNode(final Type type, final Collection<StatementPattern> patterns, final EntityStorage entities) throws IllegalStateException { this.type = requireNonNull(type); this.patterns = requireNonNull(patterns); this.entities = requireNonNull(entities); bindingNames = new HashSet<>(); properties = new HashSet<>(); // Subject based preconditions. verifySameSubjects(patterns); // Predicate based preconditions. verifyAllPredicatesAreConstants(patterns); verifyHasCorrectTypePattern(type, patterns); verifyAllPredicatesPartOfType(type, patterns); // The Subject may either be constant or a variable. final Var subject = patterns.iterator().next().getSubjectVar(); subjectIsConstant = subject.isConstant(); if(subjectIsConstant) { subjectConstant = Optional.of( subject.getValue().toString() ); subjectVar = Optional.empty(); } else { subjectConstant = Optional.empty(); subjectVar = Optional.of( subject.getName() ); } // Any constant that appears in the Object portion of the SP will be used to make sure they match. final Builder<RyaURI, Var> builder = ImmutableMap.<RyaURI, Var>builder(); for(final StatementPattern sp : patterns) { final Var object = sp.getObjectVar(); final Var pred = sp.getPredicateVar(); final RyaURI predURI = new RyaURI(pred.getValue().stringValue()); bindingNames.addAll(sp.getBindingNames()); if(object.isConstant() && !pred.getValue().equals(RDF.TYPE)) { final RyaType propertyType = RdfToRyaConversions.convertValue(object.getValue()); properties.add(new Property(predURI, propertyType)); } builder.put(predURI, object); } objectVariables = builder.build(); } @Override public Set<String> getBindingNames() { return bindingNames; } @Override public Set<String> getAssuredBindingNames() { return bindingNames; } /** * Verify the Subject for all of the patterns is the same. * * @param patterns - The patterns to check. * @throws IllegalStateException If all of the Subjects are not the same. */ private static void verifySameSubjects(final Collection<StatementPattern> patterns) throws IllegalStateException { requireNonNull(patterns); final Iterator<StatementPattern> it = patterns.iterator(); final Var subject = it.next().getSubjectVar(); while(it.hasNext()) { final StatementPattern pattern = it.next(); if(!pattern.getSubjectVar().equals(subject)) { throw new IllegalStateException("At least one of the patterns has a different subject from the others. " + "All subjects must be the same."); } } } /** * Verifies all of the Statement Patterns have Constants for their predicates. * * @param patterns - The patterns to check. (not null) * @throws IllegalStateException A pattern has a variable predicate. */ private static void verifyAllPredicatesAreConstants(final Collection<StatementPattern> patterns) throws IllegalStateException { requireNonNull(patterns); for(final StatementPattern pattern : patterns) { if(!pattern.getPredicateVar().isConstant()) { throw new IllegalStateException("The Predicate of a Statement Pattern must be constant. Pattern: " + pattern); } } } /** * Verifies a single Statement Pattern defines the Type of Entity this query node matches. * * @param type - The expected Type. (not null) * @param patterns - The patterns to check. (not null) * @throws IllegalStateException No Type or the wrong Type is specified by the patterns. */ private static void verifyHasCorrectTypePattern(final Type type, final Collection<StatementPattern> patterns) throws IllegalStateException { requireNonNull(type); requireNonNull(patterns); boolean typeFound = false; for(final StatementPattern pattern : patterns) { final RyaURI predicate = new RyaURI(pattern.getPredicateVar().getValue().toString()); if(predicate.equals(TYPE_ID_URI)) { final RyaURI typeId = new RyaURI( pattern.getObjectVar().getValue().stringValue() ); if(typeId.equals(type.getId())) { typeFound = true; } else { throw new IllegalStateException("Statement Pattern encountred for a Type that does not match the expected Type." + " Expected Type = '" + type.getId().getData() + "' Found Type = '" + typeId.getData() + "'"); } } } if(!typeFound) { throw new IllegalStateException("The collection of Statement Patterns that this node matches must define which Type they match."); } } /** * Verify all of the patterns have predicates that match one of the Type's property names. * * @param type - The Type the patterns match. (not null) * @param patterns - The patterns to check. * @throws IllegalStateException If any of the non-type defining Statement Patterns * contain a predicate that does not match one of the Type's property names. */ private static void verifyAllPredicatesPartOfType(final Type type, final Collection<StatementPattern> patterns) throws IllegalStateException { requireNonNull(type); requireNonNull(patterns); for(final StatementPattern pattern : patterns) { // Skip TYPE patterns. final RyaURI predicate = new RyaURI( pattern.getPredicateVar().getValue().toString() ); if(predicate.equals(TYPE_ID_URI)) { continue; } if(!type.getPropertyNames().contains(predicate)) { throw new IllegalStateException("The Predicate of a Statement Pattern must be a property name for the Type. " + "Type ID: '" + type.getId().getData() + "' Pattern: " + pattern); } } } @Override public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Collection<BindingSet> bindingSets) throws QueryEvaluationException { requireNonNull(bindingSets); final List<BindingSet> list = new ArrayList<>(); bindingSets.forEach(bindingSet -> { try { list.addAll(findBindings(bindingSet)); } catch (final Exception e) { LOG.error("Unable to evaluate bindingset.", e); } }); return new CollectionIteration<>(list); } @Override public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final BindingSet bindingSet) throws QueryEvaluationException { requireNonNull(bindingSet); return new CollectionIteration<>(findBindings(bindingSet)); } private List<BindingSet> findBindings(final BindingSet bindingSet) throws QueryEvaluationException { final MapBindingSet resultSet = new MapBindingSet(); try { final ConvertingCursor<TypedEntity> entitiesCursor; final String subj; // If the subject needs to be filled in, check if the subject variable is in the binding set. if(subjectIsConstant) { // if it is, fetch that value and then fetch the entity for the subject. subj = subjectConstant.get(); entitiesCursor = entities.search(Optional.of(new RyaURI(subj)), type, properties); } else { entitiesCursor = entities.search(Optional.empty(), type, properties); } while(entitiesCursor.hasNext()) { final TypedEntity typedEntity = entitiesCursor.next(); final ImmutableCollection<Property> properties = typedEntity.getProperties(); //ensure properties match and only add properties that are in the statement patterns to the binding set for(final RyaURI key : objectVariables.keySet()) { final Optional<RyaType> prop = typedEntity.getPropertyValue(new RyaURI(key.getData())); if(prop.isPresent()) { final RyaType type = prop.get(); final String bindingName = objectVariables.get(key).getName(); resultSet.addBinding(bindingName, ValueFactoryImpl.getInstance().createLiteral(type.getData())); } } } } catch (final EntityStorageException e) { throw new QueryEvaluationException("Failed to evaluate the binding set", e); } bindingSet.forEach(new Consumer<Binding>() { @Override public void accept(final Binding binding) { resultSet.addBinding(binding); } }); final List<BindingSet> list = new ArrayList<>(); list.add(resultSet); return list; } /** * @return - The {@link StatementPattern}s that make up this {@link EntityQueryNode} */ public Collection<StatementPattern> getPatterns() { return patterns; } @Override public int hashCode() { return Objects.hash(subjectIsConstant, type, subjectVar, subjectConstant, getPatterns()); } @Override public boolean equals(final Object other) { if(other instanceof EntityQueryNode) { final EntityQueryNode otherNode = (EntityQueryNode)other; final boolean samePatterns = getPatterns().size() == otherNode.getPatterns().size(); boolean match = true; if(samePatterns) { for(final StatementPattern sp : getPatterns()) { if(!otherNode.getPatterns().contains(sp)) { match = false; break; } } } return Objects.equals(subjectIsConstant, otherNode.subjectIsConstant) && Objects.equals(subjectVar, otherNode.subjectVar) && Objects.equals(type, otherNode.type) && Objects.equals(subjectConstant, otherNode.subjectConstant) && samePatterns && match; } return false; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Type: " + type.toString()); sb.append("Statement Patterns:"); sb.append("-------------------"); for(final StatementPattern sp : getPatterns()) { sb.append(sp.toString()); } return sb.toString(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.streaming.runtime.io; import org.apache.flink.annotation.Internal; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.runtime.checkpoint.CheckpointException; import org.apache.flink.runtime.checkpoint.CheckpointFailureReason; import org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter; import org.apache.flink.runtime.checkpoint.channel.InputChannelInfo; import org.apache.flink.runtime.io.disk.iomanager.IOManager; import org.apache.flink.runtime.io.network.api.serialization.SpillingAdaptiveSpanningRecordDeserializer; import org.apache.flink.runtime.plugable.DeserializationDelegate; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.io.checkpointing.CheckpointedInputGate; import org.apache.flink.streaming.runtime.streamrecord.StreamElement; import org.apache.flink.streaming.runtime.watermarkstatus.StatusWatermarkValve; import org.apache.flink.streaming.runtime.watermarkstatus.WatermarkStatus; import java.io.IOException; import java.util.Map; import java.util.concurrent.CompletableFuture; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; /** * Implementation of {@link StreamTaskInput} that wraps an input from network taken from {@link * CheckpointedInputGate}. * * <p>This internally uses a {@link StatusWatermarkValve} to keep track of {@link Watermark} and * {@link WatermarkStatus} events, and forwards them to event subscribers once the {@link * StatusWatermarkValve} determines the {@link Watermark} from all inputs has advanced, or that a * {@link WatermarkStatus} needs to be propagated downstream to denote a status change. * * <p>Forwarding elements, watermarks, or status elements must be protected by synchronizing on the * given lock object. This ensures that we don't call methods on a {@link StreamInputProcessor} * concurrently with the timer callback or other things. */ @Internal public final class StreamTaskNetworkInput<T> extends AbstractStreamTaskNetworkInput< T, SpillingAdaptiveSpanningRecordDeserializer< DeserializationDelegate<StreamElement>>> { public StreamTaskNetworkInput( CheckpointedInputGate checkpointedInputGate, TypeSerializer<T> inputSerializer, IOManager ioManager, StatusWatermarkValve statusWatermarkValve, int inputIndex) { super( checkpointedInputGate, inputSerializer, statusWatermarkValve, inputIndex, getRecordDeserializers(checkpointedInputGate, ioManager)); } // Initialize one deserializer per input channel private static Map< InputChannelInfo, SpillingAdaptiveSpanningRecordDeserializer< DeserializationDelegate<StreamElement>>> getRecordDeserializers( CheckpointedInputGate checkpointedInputGate, IOManager ioManager) { return checkpointedInputGate.getChannelInfos().stream() .collect( toMap( identity(), unused -> new SpillingAdaptiveSpanningRecordDeserializer<>( ioManager.getSpillingDirectoriesPaths()))); } @Override public CompletableFuture<Void> prepareSnapshot( ChannelStateWriter channelStateWriter, long checkpointId) throws CheckpointException { for (Map.Entry< InputChannelInfo, SpillingAdaptiveSpanningRecordDeserializer< DeserializationDelegate<StreamElement>>> e : recordDeserializers.entrySet()) { try { channelStateWriter.addInputData( checkpointId, e.getKey(), ChannelStateWriter.SEQUENCE_NUMBER_UNKNOWN, e.getValue().getUnconsumedBuffer()); } catch (IOException ioException) { throw new CheckpointException(CheckpointFailureReason.IO_EXCEPTION, ioException); } } return checkpointedInputGate.getAllBarriersReceivedFuture(checkpointId); } @Override public void close() throws IOException { super.close(); // cleanup the resources of the checkpointed input gate checkpointedInputGate.close(); } }
/** * Copyright (c) 2016-present, RxJava 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 io.reactivex.internal.observers; import static io.reactivex.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.Test; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.schedulers.Schedulers; public class BlockingMultiObserverTest { @Test public void dispose() { BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<Integer>(); bmo.dispose(); Disposable d = Disposables.empty(); bmo.onSubscribe(d); } @Test public void blockingGetDefault() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<Integer>(); Schedulers.single().scheduleDirect(new Runnable() { @Override public void run() { bmo.onSuccess(1); } }, 100, TimeUnit.MILLISECONDS); assertEquals(1, bmo.blockingGet(0).intValue()); } @Test public void blockingAwait() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<Integer>(); Schedulers.single().scheduleDirect(new Runnable() { @Override public void run() { bmo.onSuccess(1); } }, 100, TimeUnit.MILLISECONDS); assertTrue(bmo.blockingAwait(1, TimeUnit.MINUTES)); } @Test public void blockingGetDefaultInterrupt() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<Integer>(); Thread.currentThread().interrupt(); try { bmo.blockingGet(0); fail("Should have thrown"); } catch (RuntimeException ex) { assertTrue(ex.getCause() instanceof InterruptedException); } finally { Thread.interrupted(); } } @Test public void blockingGetErrorInterrupt() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<Integer>(); Thread.currentThread().interrupt(); try { assertTrue(bmo.blockingGetError() instanceof InterruptedException); } finally { Thread.interrupted(); } } @Test public void blockingGetErrorTimeoutInterrupt() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<Integer>(); Thread.currentThread().interrupt(); try { bmo.blockingGetError(1, TimeUnit.MINUTES); fail("Should have thrown"); } catch (RuntimeException ex) { assertTrue(ex.getCause() instanceof InterruptedException); } finally { Thread.interrupted(); } } @Test public void blockingGetErrorDelayed() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<Integer>(); Schedulers.single().scheduleDirect(new Runnable() { @Override public void run() { bmo.onError(new TestException()); } }, 100, TimeUnit.MILLISECONDS); assertTrue(bmo.blockingGetError() instanceof TestException); } @Test public void blockingGetErrorTimeoutDelayed() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<Integer>(); Schedulers.single().scheduleDirect(new Runnable() { @Override public void run() { bmo.onError(new TestException()); } }, 100, TimeUnit.MILLISECONDS); assertTrue(bmo.blockingGetError(1, TimeUnit.MINUTES) instanceof TestException); } @Test public void blockingGetErrorTimedOut() { final BlockingMultiObserver<Integer> bmo = new BlockingMultiObserver<Integer>(); try { assertNull(bmo.blockingGetError(1, TimeUnit.NANOSECONDS)); fail("Should have thrown"); } catch (RuntimeException expected) { assertEquals(TimeoutException.class, expected.getCause().getClass()); assertEquals(timeoutMessage(1, TimeUnit.NANOSECONDS), expected.getCause().getMessage()); } } }
/* * Copyright 2016 Google 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.hyperaware.conference.android.logging; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; /** * Java logging handler for sending log records to the Android log. * See this app's Application object for an example of how to get this * installed into your app at launch. * * This Handler works best when your code's Loggers all live underneath the * package name given in the constructor. */ public class AndroidLogHandler extends Handler { private final String packageRoot; public AndroidLogHandler(final String package_root) { super(); packageRoot = package_root; } @Override public void publish(final LogRecord record) { final String tag = packageRoot; String name = record.getLoggerName(); // Strip packageRoot from the beginning, if present, to shorten redundant info if (name.startsWith(packageRoot)) { final int trunc = name.length() > packageRoot.length() ? packageRoot.length() + 1 : name.length(); name = name.substring(trunc); } else { // Only use trailing (class name) after the dot final int lastdot = name.lastIndexOf('.'); if (lastdot >= 0 && lastdot < name.length()) { name = name.substring(lastdot + 1); } } final Throwable throwable = record.getThrown(); final Level level = record.getLevel(); final long seq = record.getSequenceNumber(); final String orig_message = record.getMessage(); if (orig_message != null) { try { // Default buffer size is required here to prevent recursive log messages final BufferedReader br = new BufferedReader(new StringReader(orig_message), 8192); String line; while ((line = br.readLine()) != null) { line = name + " " + level + " " + seq + ": " + line; if (level == Level.SEVERE) { Log.e(tag, line); } else if (level == Level.WARNING) { Log.w(tag, line); } else if (level == Level.CONFIG || level == Level.INFO) { Log.i(tag, line); } else if (level == Level.FINE) { Log.v(tag, line); } else { Log.d(tag, line); } } } catch (final IOException ignore) { } } if (throwable != null) { final String line = name + " " + level + " " + seq; if (level == Level.SEVERE) { Log.e(tag, line, throwable); } else if (level == Level.WARNING) { Log.w(tag, line, throwable); } else if (level == Level.CONFIG || level == Level.INFO) { Log.i(tag, line, throwable); } else if (level == Level.FINE) { Log.v(tag, line, throwable); } else { Log.d(tag, line, throwable); } } } @Override public void close() { } @Override public void flush() { } }
package com.github.nakjunizm.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.github.nakjunizm.model.User; import com.github.nakjunizm.service.UserService; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/{name}", method = RequestMethod.GET) public User getUser(@PathVariable String name) { return userService.getUserByName(name); } @RequestMapping(value = "/{name}", method = RequestMethod.PUT) public User putUser(@PathVariable String name, @RequestParam(value="departmentId", required=true) String departmentId) { return userService.putUser(name, departmentId); } }
package es.upm.miw.shop_domain.exceptions; public class ConflictException extends RuntimeException { private static final String DESCRIPTION = "Conflict Exception (409)"; public ConflictException(String detail) { super(DESCRIPTION + ". " + detail); } }
package com.aisparser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link Message3}. */ @RunWith(JUnit4.class) public class Message20Test { @Test public void testParse() { Message20 msg = new Message20(); try { Vdm vdm_message = new Vdm(); int result = vdm_message.add("!AIVDM,1,1,,A,D03OwphiIN>4,0*25"); assertEquals("vdm add failed", 0, result); msg.parse(vdm_message.sixbit()); } catch (Exception e) { fail(e.getMessage()); } assertEquals("num_cmds", 1, msg.num_cmds()); assertEquals("msgid", 20, msg.msgid()); assertEquals("repeat", 0, msg.repeat()); assertEquals("userid", 3669987, msg.userid()); assertEquals("spare1", 0, msg.spare1()); assertEquals("offset1", 790, msg.offset1()); assertEquals("slots1", 5, msg.slots1()); assertEquals("timeout1", 7, msg.timeout1()); assertEquals("increment1", 225, msg.increment1()); } }
/* * Copyright (c) 2019, 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.apimgt.api; public interface PasswordResolver { /** * Get the resolved password * * @param encryptedPassword password string given in registry configuration * @return password as as string */ String getPassword(String encryptedPassword); }
/* * Copyright 2017 ~ 2025 the original author or authors. <wanglsir@gmail.com, 983708408@qq.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wl4g.component.common.io; import java.io.File; import java.io.IOException; import org.apache.commons.compress.archivers.ArchiveException; public class CompressUtilsTests { public static void main(String[] args) throws IOException, ArchiveException { CompressUtils.appendTarArchive(new File("/Users/vjay/Downloads/base-view-master-bin.tar"), new File("/Users/vjay/Downloads/rap1.json"), "rap1.json"); } }
package com.huali.redis.service; import com.huali.redis.model.User; public interface UserService { User getUser(Long id); User getUserByUsername(String username); }
/** * Copyright (C) 2017 Newland Group Holding Limited * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.newlandframework.rpc.async; /** * @author tangjie<https://github.com/tang-jie> * @filename:AsyncCallStatus.java * @description:AsyncCallStatus功能模块 * @blogs http://www.cnblogs.com/jietang/ * @since 2017/3/22 */ public class AsyncCallStatus { private long startTime; private long elapseTime; private CallStatus status; public AsyncCallStatus(long startTime, long elapseTime, CallStatus status) { this.startTime = startTime; this.elapseTime = elapseTime; this.status = status; } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } public long getElapseTime() { return elapseTime; } public void setElapseTime(long elapseTime) { this.elapseTime = elapseTime; } public CallStatus getStatus() { return status; } public void setStatus(CallStatus status) { this.status = status; } public String toString() { return "AsyncLoadStatus [status=" + status + ", startTime=" + startTime + ", elapseTime=" + elapseTime + "]"; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.logz.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.logz.fluent.models.LogzSingleSignOnResourceInner; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Response of a list operation. */ @Fluent public final class LogzSingleSignOnResourceListResponse { @JsonIgnore private final ClientLogger logger = new ClientLogger(LogzSingleSignOnResourceListResponse.class); /* * Results of a list operation. */ @JsonProperty(value = "value") private List<LogzSingleSignOnResourceInner> value; /* * Link to the next set of results, if any. */ @JsonProperty(value = "nextLink") private String nextLink; /** * Get the value property: Results of a list operation. * * @return the value value. */ public List<LogzSingleSignOnResourceInner> value() { return this.value; } /** * Set the value property: Results of a list operation. * * @param value the value value to set. * @return the LogzSingleSignOnResourceListResponse object itself. */ public LogzSingleSignOnResourceListResponse withValue(List<LogzSingleSignOnResourceInner> value) { this.value = value; return this; } /** * Get the nextLink property: Link to the next set of results, if any. * * @return the nextLink value. */ public String nextLink() { return this.nextLink; } /** * Set the nextLink property: Link to the next set of results, if any. * * @param nextLink the nextLink value to set. * @return the LogzSingleSignOnResourceListResponse object itself. */ public LogzSingleSignOnResourceListResponse withNextLink(String nextLink) { this.nextLink = nextLink; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (value() != null) { value().forEach(e -> e.validate()); } } }
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package ai.vespa.rankingexpression.importer; import org.junit.Test; import static org.junit.Assert.assertTrue; public class DimensionRenamerTest { @Test public void testMnistRenaming() { DimensionRenamer renamer = new DimensionRenamer(new IntermediateGraph("test")); renamer.addDimension("first_dimension_of_x"); renamer.addDimension("second_dimension_of_x"); renamer.addDimension("first_dimension_of_w"); renamer.addDimension("second_dimension_of_w"); renamer.addDimension("first_dimension_of_b"); // which dimension to join on matmul renamer.addConstraint("second_dimension_of_x", "first_dimension_of_w", DimensionRenamer.Constraint.equal(false), null); // other dimensions in matmul can't be equal renamer.addConstraint("first_dimension_of_x", "second_dimension_of_w", DimensionRenamer.Constraint.lessThan(false), null); // for efficiency, put dimension to join on innermost renamer.addConstraint("first_dimension_of_x", "second_dimension_of_x", DimensionRenamer.Constraint.lessThan(true), null); renamer.addConstraint("first_dimension_of_w", "second_dimension_of_w", DimensionRenamer.Constraint.greaterThan(true), null); // bias renamer.addConstraint("second_dimension_of_w", "first_dimension_of_b", DimensionRenamer.Constraint.equal(false), null); renamer.solve(); String firstDimensionOfXName = renamer.dimensionNameOf("first_dimension_of_x").get(); String secondDimensionOfXName = renamer.dimensionNameOf("second_dimension_of_x").get(); String firstDimensionOfWName = renamer.dimensionNameOf("first_dimension_of_w").get(); String secondDimensionOfWName = renamer.dimensionNameOf("second_dimension_of_w").get(); String firstDimensionOfBName = renamer.dimensionNameOf("first_dimension_of_b").get(); assertTrue(firstDimensionOfXName.compareTo(secondDimensionOfXName) < 0); assertTrue(firstDimensionOfWName.compareTo(secondDimensionOfWName) > 0); assertTrue(secondDimensionOfXName.compareTo(firstDimensionOfWName) == 0); assertTrue(firstDimensionOfXName.compareTo(secondDimensionOfWName) < 0); assertTrue(secondDimensionOfWName.compareTo(firstDimensionOfBName) == 0); } }
package com.ieng.shortenLink.common; import java.net.URI; import java.net.URISyntaxException; public class Utility { public static String getDomainName(String url) throws URISyntaxException { URI uri = new URI(url); String domain = uri.getHost(); return domain.startsWith("www.") ? domain.substring(4) : domain; } }
package com.xwintop.xTransfer.receiver.bean; import java.io.Serializable; /** * @ClassName: ReceiverConfig * @Description: 接收器配置 * @author: xufeng * @date: 2018/5/28 16:32 */ public interface ReceiverConfig extends Serializable { String getServiceName(); String getId(); void setId(String id); boolean isEnable();//是否开启 boolean isAsync();//是否异步执行 boolean isExceptionExit();//是否发生异常时退出任务 }
package com.anlia.pageturn.factory; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import com.anlia.pageturn.utils.BitmapUtils; import com.anlia.pageturn.utils.ScreenUtils; /** * 页面内容工厂类:制作图像集合型内容 */ public class PicturesPageFactory extends PageFactory { private Context context; public int style;//集合类型 public final static int STYLE_IDS = 1;//drawable目录图片集合类型 public final static int STYLE_URIS = 2;//手机本地目录图片集合类型 private int[] picturesIds; /** * 初始化drawable目录下的图片id集合 * @param context * @param pictureIds */ public PicturesPageFactory(Context context, int[] pictureIds){ this.context = context; this.picturesIds = pictureIds; this.style = STYLE_IDS; if (pictureIds.length > 0){ hasData = true; pageTotal = pictureIds.length; } } private String[] picturesUris; /** * 初始化本地目录下的图片uri集合 * @param context * @param picturesUris */ public PicturesPageFactory(Context context, String[] picturesUris){ this.context = context; this.picturesUris = picturesUris; this.style = STYLE_URIS; if (picturesUris.length > 0){ hasData = true; pageTotal = picturesUris.length; } } @Override public void drawPreviousBitmap(Bitmap bitmap, int pageNum) { Canvas canvas = new Canvas(bitmap); canvas.drawBitmap(getBitmapByIndex(pageNum-2),0,0,null); } @Override public void drawCurrentBitmap(Bitmap bitmap, int pageNum) { Canvas canvas = new Canvas(bitmap); canvas.drawBitmap(getBitmapByIndex(pageNum-1),0,0,null); } @Override public void drawNextBitmap(Bitmap bitmap, int pageNum) { Canvas canvas = new Canvas(bitmap); canvas.drawBitmap(getBitmapByIndex(pageNum),0,0,null); } @Override public Bitmap getBitmapByIndex(int index) { if(hasData){ switch (style){ case STYLE_IDS: return getBitmapFromIds(index); case STYLE_URIS: return getBitmapFromUris(index); default: return null; } }else { return null; } } /** * 从id集合获取bitmap * @param index * @return */ private Bitmap getBitmapFromIds(int index){ return BitmapUtils.drawableToBitmap( context.getResources().getDrawable(picturesIds[index]), ScreenUtils.getScreenWidth(context), ScreenUtils.getScreenHeight(context) ); } /** * 从uri集合获取bitmap * @param index * @return */ private Bitmap getBitmapFromUris(int index){ return null;//这个有空再写啦,大家可自行补充完整 } }
package editor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import macho.MachOCommandFactory; import macho.commands.AbstractMachOCommand; /** * This class was designed specifically to replace the contents of one of the data sections * with custom data. As such, it is currently very tailored to that purpose and should be * generalized. Success when expanding the file is far from guaranteed, as references in the * executable may not be appropriately updated. * */ public class DataSegmentSwapper { private static final int FIRST_COMMAND_OFFSET = 28; private static final int HEADER_SEGMENTS_OFFSET = 16; // These addresses currently need to be manually set. Ideally this would not be the case. private static final int SEGMENT_OFFSET = 12314; private static final int SEGMENT_ADDRESS = 124215; private static final int OLD_SIZE = 12321; private long newSize = 0l; private int sizeDiff = 0; private final BinaryWrapper binary; private final FileChannel newDataSegment; private List<AbstractMachOCommand> commands; /** * Given a string representing the path to the Mach-O file and a path to the new file to * put in it, overwrites a portion of the Mach-O file with the other file. It will update * the Mach-O header as necessary. * @param args * @throws IOException */ public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); if (args.length < 2) { System.out.println("Invalid args. Needs pathToBinary pathToNewSegment"); } Path binaryLocation = Paths.get(args[0]); Path newDataSegmentLocation = Paths.get(args[1]); DataSegmentSwapper tarSwapper = new DataSegmentSwapper(binaryLocation, newDataSegmentLocation); tarSwapper.parseHeader(); tarSwapper.swapFile(); tarSwapper.updateHeader(); System.out.println(System.currentTimeMillis() - time); } private void updateHeader() throws IOException { if (sizeDiff <= 0) { return; } for (AbstractMachOCommand command : commands) { binary.setPosition(command.getCommandStartOffset()); command.updateSizeifNeeded(binary, SEGMENT_OFFSET, sizeDiff); command.updateOffsetsIfNeeded(binary, SEGMENT_OFFSET, sizeDiff); command.updateAddressesIfNeeded(binary, SEGMENT_ADDRESS, sizeDiff); command.updateObjCAddressesIfNeeded(binary, SEGMENT_ADDRESS, sizeDiff); } binary.setPosition(0); } private void swapFile() throws IOException { if (sizeDiff > 0) { binary.insertFileAtOffsetOverriding(SEGMENT_OFFSET, newDataSegment, OLD_SIZE); } else { binary.insertFileAtOffsetOverridingAndZeroing(SEGMENT_OFFSET, newDataSegment, OLD_SIZE); } } /** * Given a Path to the Mach-O file and a Path to the new file to insert into it, * constructs a new {@link DataSegmentSwapper}. * @param binaryLocation The Path to the Mach-O file * @param newDataSegmentLocation The Path to the file to insert into the Mach-O file * @throws IOException */ public DataSegmentSwapper(Path binaryLocation, Path newDataSegmentLocation) throws IOException { binary = new BinaryWrapper(binaryLocation); newDataSegment = FileChannel.open(newDataSegmentLocation, StandardOpenOption.READ, StandardOpenOption.WRITE); newSize = newDataSegment.size(); sizeDiff = (int) (newSize - OLD_SIZE); if (sizeDiff > 0) { while (sizeDiff % 64 != 0) { sizeDiff++; ByteBuffer padding = ByteBuffer.allocate(1); padding.put((byte) 0); padding.position(0); newDataSegment.write(padding, newSize); newSize++; } } } private List<AbstractMachOCommand> parseHeader() throws IOException { int commandCount = binary.getSingleWordAtPosition(HEADER_SEGMENTS_OFFSET); binary.setPosition(FIRST_COMMAND_OFFSET); commands = new ArrayList<>(commandCount); while (commands.size() < commandCount) { commands.add(parseCommand()); } binary.setPosition(0); return commands; } private AbstractMachOCommand parseCommand() throws IOException { AbstractMachOCommand command = MachOCommandFactory.createMachOCommand(binary); command.parseCommand(binary); binary.setPosition(command.getCommandStartOffset() + command.getCommandSize()); return command; } }
package de.embl.cba.mobie.utils; import bdv.util.BdvHandle; import com.google.gson.GsonBuilder; import com.google.gson.internal.LinkedTreeMap; import com.google.gson.stream.JsonReader; import de.embl.cba.bdv.utils.BdvUtils; import de.embl.cba.mobie.Constants; import de.embl.cba.tables.FileUtils; import de.embl.cba.tables.TableColumns; import de.embl.cba.tables.Tables; import de.embl.cba.tables.imagesegment.SegmentProperty; import de.embl.cba.tables.imagesegment.SegmentUtils; import de.embl.cba.tables.tablerow.TableRowImageSegment; import ij.IJ; import mpicbg.spim.data.SpimData; import mpicbg.spim.data.SpimDataException; import mpicbg.spim.data.XmlIoSpimData; import net.imglib2.*; import net.imglib2.Cursor; import net.imglib2.RandomAccess; import net.imglib2.algorithm.neighborhood.HyperSphereShape; import net.imglib2.algorithm.neighborhood.Neighborhood; import net.imglib2.algorithm.neighborhood.Shape; import net.imglib2.realtransform.AffineTransform3D; import net.imglib2.realtransform.Scale3D; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.ARGBType; import net.imglib2.type.numeric.RealType; import java.awt.*; import java.io.*; import java.net.URI; import java.util.*; import java.util.List; import java.util.stream.Collectors; import static de.embl.cba.bdv.utils.BdvUtils.getBdvWindowCenter; import static de.embl.cba.bdv.utils.converters.RandomARGBConverter.goldenRatio; public class Utils { public static double[] delimitedStringToDoubleArray( String s, String delimiter) { String[] sA = s.split(delimiter); double[] nums = new double[sA.length]; for (int i = 0; i < nums.length; i++) { nums[i] = Double.parseDouble(sA[i].trim()); } return nums; } @Deprecated // use ColorUtils instead public static Color getColor(String name) { try { return (Color)Color.class.getField(name.toUpperCase()).get(null); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { e.printStackTrace(); return null; } } public static long[] asLongs( double[] doubles ) { final long[] longs = new long[ doubles.length ]; for ( int i = 0; i < doubles.length; ++i ) { longs[ i ] = (long) doubles[ i ]; } return longs; } public static void log( String text ) { IJ.log( text ); } public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { List<Map.Entry<K, V> > list = new ArrayList<>(map.entrySet()); list.sort( Map.Entry.comparingByValue() ); Map<K, V> result = new LinkedHashMap<>(); for (Map.Entry<K, V> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; } public static < T extends RealType< T > & NativeType< T > > double getLocalMaximum( final RandomAccessibleInterval< T > rai, double[] position, double radius, double calibration ) { // TODO: add out-of-bounds strategy or is this handled by the Neighborhood? Shape shape = new HyperSphereShape( (int) Math.ceil( radius / calibration ) ); final RandomAccessible< Neighborhood< T > > nra = shape.neighborhoodsRandomAccessible( rai ); final RandomAccess< Neighborhood< T > > neighborhoodRandomAccess = nra.randomAccess(); neighborhoodRandomAccess.setPosition( getPixelPosition( position, calibration ) ); final Neighborhood< T > neighborhood = neighborhoodRandomAccess.get(); final Cursor< T > cursor = neighborhood.cursor(); double max = - Double.MAX_VALUE; double value; while( cursor.hasNext() ) { value = cursor.next().getRealDouble(); if ( value > max ) { max = value; } } return max; } public static < T extends RealType< T > & NativeType< T > > double getLocalSum( final RandomAccessibleInterval< T > rai, double[] position, double radius, double calibration ) { // TODO: add out-of-bounds strategy or is this handled by the Neighborhood? Shape shape = new HyperSphereShape( (int) Math.ceil( radius / calibration ) ); final RandomAccessible< Neighborhood< T > > nra = shape.neighborhoodsRandomAccessible( rai ); final RandomAccess< Neighborhood< T > > neighborhoodRandomAccess = nra.randomAccess(); neighborhoodRandomAccess.setPosition( getPixelPosition( position, calibration ) ); final Neighborhood< T > neighborhood = neighborhoodRandomAccess.get(); final Cursor< T > cursor = neighborhood.cursor(); double sum = 0.0; while( cursor.hasNext() ) { sum += cursor.next().getRealDouble(); } return sum; } public static < T extends RealType< T > & NativeType< T > > double getFractionOfNonZeroVoxels( final RandomAccessibleInterval< T > rai, double[] position, double radius, double calibration ) { // TODO: add out-of-bounds strategy or is this handled by the Neighborhood? Shape shape = new HyperSphereShape( (int) Math.ceil( radius / calibration ) ); final RandomAccessible< Neighborhood< T > > nra = shape.neighborhoodsRandomAccessible( rai ); final RandomAccess< Neighborhood< T > > neighborhoodRandomAccess = nra.randomAccess(); neighborhoodRandomAccess.setPosition( getPixelPosition( position, calibration ) ); final Neighborhood< T > neighborhood = neighborhoodRandomAccess.get(); final Cursor< T > neighborhoodCursor = neighborhood.cursor(); long numberOfNonZeroVoxels = 0; long numberOfVoxels = 0; while( neighborhoodCursor.hasNext() ) { numberOfVoxels++; final double realDouble = neighborhoodCursor.next().getRealDouble(); if ( realDouble != 0) { numberOfNonZeroVoxels++; } } return 1.0 * numberOfNonZeroVoxels / numberOfVoxels; } public static String[] combine(String[] a, String[] b){ int length = a.length + b.length; String[] result = new String[length]; System.arraycopy(a, 0, result, 0, a.length); System.arraycopy(b, 0, result, a.length, b.length); return result; } public static Object[] combine(Object[] a, Object[] b){ int length = a.length + b.length; Object[] result = new Object[length]; System.arraycopy(a, 0, result, 0, a.length); System.arraycopy(b, 0, result, a.length, b.length); return result; } private static long[] getPixelPosition( double[] position, double calibration ) { long[] pixelPosition = new long[ position.length ]; for ( int d = 0; d < position.length; ++d ) { pixelPosition[ d ] = (long) ( position[ d ] / calibration ); } return pixelPosition; } public static SpimData openSpimData( File file ) { try { SpimData spimData = new XmlIoSpimData().load( file.toString() ); return spimData; } catch ( SpimDataException e ) { System.out.println( file.toString() ); e.printStackTrace(); return null; } } public static ARGBType asArgbType( Color color ) { return new ARGBType( ARGBType.rgba( color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha() ) ); } public static void wait(int msecs) { try {Thread.sleep(msecs);} catch (InterruptedException e) { } } public static void logVector( String preText, double[] vector ) { String text = preText + ": "; for ( int i = 0; i < vector.length; ++i ) { text += vector[ i ] + " "; } Utils.log( text ); } public static void logVector( String preText, double[] vector, int numDigits ) { String text = preText + ": "; for ( int i = 0; i < vector.length; ++i ) { text += String.format( "%." + numDigits + "f", vector[ i ] ) + " "; } Utils.log( text ); } public static double[] getCSVasDoubles( String csv ) { final String[] split = csv.split( "," ); double[] normalVector = new double[ split.length ]; for ( int i = 0; i < split.length; ++i ) { normalVector[ i ] = Double.parseDouble( split[ i ] ); } return normalVector; } public static void wait100ms() { try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { e.printStackTrace(); } } public static LinkedTreeMap getLinkedTreeMap( InputStream inputStream ) throws IOException { final JsonReader reader = new JsonReader( new InputStreamReader( inputStream, "UTF-8" ) ); GsonBuilder builder = new GsonBuilder(); return builder.create().fromJson( reader, Object.class ); } public static String padLeftSpaces(String inputString, int length) { if (inputString.length() >= length) { return inputString; } StringBuilder sb = new StringBuilder(); while (sb.length() < length - inputString.length()) { sb.append(' '); } sb.append(inputString); return sb.toString(); } public static List< TableRowImageSegment > createAnnotatedImageSegmentsFromTableFile( String tablePath, String imageId ) { log( "Opening table: " + tablePath ); if ( tablePath.startsWith( "http" ) ) { tablePath = FileUtils.resolveTableURL(URI.create(tablePath)); } else { tablePath = FileUtils.resolveTablePath( tablePath ); } Map< String, List< String > > columns = TableColumns.stringColumnsFromTableFile( tablePath ); TableColumns.addLabelImageIdColumn( columns, Constants.COLUMN_NAME_LABEL_IMAGE_ID, imageId ); final Map< SegmentProperty, List< String > > segmentPropertyToColumn = createSegmentPropertyToColumn( columns ); final List< TableRowImageSegment > segments = SegmentUtils.tableRowImageSegmentsFromColumns( columns, segmentPropertyToColumn, false ); return segments; } public static boolean isRelativePath( String tablePath ) { final BufferedReader reader = Tables.getReader( tablePath ); final String firstLine; try { firstLine = reader.readLine(); return firstLine.startsWith( ".." ); } catch ( IOException e ) { e.printStackTrace(); return false; } } public static String getRelativePath( String tablePath ) { final BufferedReader reader = Tables.getReader( tablePath ); try { String link = reader.readLine(); return link; } catch ( IOException e ) { e.printStackTrace(); return null; } } public static Map< SegmentProperty, List< String > > createSegmentPropertyToColumn( Map< String, List< String > > columns ) { final HashMap< SegmentProperty, List< String > > segmentPropertyToColumn = new HashMap<>(); segmentPropertyToColumn.put( SegmentProperty.LabelImage, columns.get( Constants.COLUMN_NAME_LABEL_IMAGE_ID )); segmentPropertyToColumn.put( SegmentProperty.ObjectLabel, columns.get( Constants.COLUMN_NAME_SEGMENT_LABEL_ID ) ); segmentPropertyToColumn.put( SegmentProperty.X, columns.get( "anchor_x" ) ); segmentPropertyToColumn.put( SegmentProperty.Y, columns.get( "anchor_y" ) ); segmentPropertyToColumn.put( SegmentProperty.Z, columns.get( "anchor_z" ) ); SegmentUtils.putDefaultBoundingBoxMapping( segmentPropertyToColumn, columns ); return segmentPropertyToColumn; } /** * Converts a string to a random number between 0 and 1 * @param string * @return */ public static double createRandom( String string ) { double random = string.hashCode() * goldenRatio; random = random - ( long ) Math.floor( random ); return random; } /** * TODO: Make this more generic, to also work with other things than prospr and mobie * * * @param selectionName * @param isRemoveProspr * @return */ public static String getSimplifiedSourceName( String selectionName, boolean isRemoveProspr ) { if ( isRemoveProspr ) selectionName = selectionName.replace( "prospr-", "" ); selectionName = selectionName.replace( "6dpf-1-whole-", "" ); selectionName = selectionName.replace( "segmented-", "" ); selectionName = selectionName.replace( "mask-", "" ); return selectionName; } public static ArrayList< String > getSortedList( Collection< String > strings ) { final ArrayList< String > sorted = new ArrayList<>( strings ); Collections.sort( sorted, new SortIgnoreCase() ); return sorted; } public static String createNormalisedViewerTransformString( BdvHandle bdv, double[] position ) { final AffineTransform3D view = createNormalisedViewerTransform( bdv, position ); final String replace = view.toString().replace( "3d-affine: (", "" ).replace( ")", "" ); final String collect = Arrays.stream( replace.split( "," ) ).map( x -> "n" + x.trim() ).collect( Collectors.joining( "," ) ); return collect; } public static AffineTransform3D createNormalisedViewerTransform( BdvHandle bdv, double[] position ) { final AffineTransform3D view = new AffineTransform3D(); bdv.getViewerPanel().state().getViewerTransform( view ); // translate position to upper left corner of the Window (0,0) final AffineTransform3D translate = new AffineTransform3D(); translate.translate( position ); view.preConcatenate( translate.inverse() ); // divide by window width final int bdvWindowWidth = BdvUtils.getBdvWindowWidth( bdv ); final Scale3D scale = new Scale3D( 1.0 / bdvWindowWidth, 1.0 / bdvWindowWidth, 1.0 / bdvWindowWidth ); view.preConcatenate( scale ); return view; } public static double[] getMousePosition( BdvHandle bdv ) { final RealPoint realPoint = new RealPoint( 2 ); bdv.getViewerPanel().getMouseCoordinates( realPoint ); final double[] doubles = new double[ 3 ]; realPoint.localize( doubles ); return doubles; } public static AffineTransform3D createUnnormalizedViewerTransform( AffineTransform3D normalisedTransform, BdvHandle bdv ) { final AffineTransform3D transform = normalisedTransform.copy(); final int bdvWindowWidth = BdvUtils.getBdvWindowWidth( bdv ); final Scale3D scale = new Scale3D( 1.0 / bdvWindowWidth, 1.0 / bdvWindowWidth, 1.0 / bdvWindowWidth ); transform.preConcatenate( scale.inverse() ); AffineTransform3D translate = new AffineTransform3D(); translate.translate( getBdvWindowCenter( bdv ) ); transform.preConcatenate( translate ); return transform; } public static AffineTransform3D asAffineTransform3D( double[] doubles ) { final AffineTransform3D view = new AffineTransform3D( ); view.set( doubles ); return view; } }
package com.tx5256.models; public class Maladie { int id; String nom_simple; String nom_scientifique; public Maladie(int id, String nom_simple, String nom_scientifique) { super(); this.id = id; this.nom_simple = nom_simple; this.nom_scientifique = nom_scientifique; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNom_simple() { return nom_simple; } public void setNom_simple(String nom_simple) { this.nom_simple = nom_simple; } public String getNom_scientifique() { return nom_scientifique; } public void setNom_scientifique(String nom_scientifique) { this.nom_scientifique = nom_scientifique; } }
package org.cidarlab.eugene.fact; public interface Fact { }
/* * 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.camel.management; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.api.management.ManagedCamelContext; import org.apache.camel.api.management.mbean.ManagedProcessorMBean; import org.apache.camel.builder.RouteBuilder; import org.junit.Test; public class ManagedInlinedProcessorTest extends ManagementTestSupport { @Test public void testManageInlinedProcessor() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = ObjectName.getInstance("org.apache.camel:context=camel-1,type=processors,name=\"custom\""); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); Long counter = (Long) mbeanServer.getAttribute(on, "ExchangesCompleted"); assertEquals(1L, counter.longValue()); ManagedProcessorMBean mb = context.getExtension(ManagedCamelContext.class).getManagedProcessor("custom"); assertNotNull(mb); assertEquals(1L, mb.getExchangesCompleted()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId("foo") .process(exchange -> exchange.getMessage().setBody("Bye World")).id("custom") .to("mock:result"); } }; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-147 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.02.09 at 10:59:16 AM EST // package org.cvrgrid.hl7aecg.jaxb.beans; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for PORT_MT020001.PertinentInformation complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PORT_MT020001.PertinentInformation"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="subjectFindingComment" type="{urn:hl7-org:v3}PORT_MT020001.FindingComment"/> * &lt;/sequence> * &lt;attribute name="type" type="{urn:hl7-org:v3}Classes" default="ActRelationship" /> * &lt;attribute name="typeCode" type="{urn:hl7-org:v3}ActRelationshipType" /> * &lt;attribute name="contextControlCode" type="{urn:hl7-org:v3}ContextControl" default="OP" /> * &lt;attribute name="contextConductionInd" type="{urn:hl7-org:v3}bl" default="true" /> * &lt;attribute name="templateId"> * &lt;simpleType> * &lt;list itemType="{urn:hl7-org:v3}oid" /> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="typeID"> * &lt;simpleType> * &lt;list itemType="{urn:hl7-org:v3}oid" /> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="realmCode"> * &lt;simpleType> * &lt;list itemType="{urn:hl7-org:v3}cs" /> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}cs" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PORT_MT020001.PertinentInformation", propOrder = { "subjectFindingComment" }) public class PORTMT020001PertinentInformation { @XmlElement(required = true) protected PORTMT020001FindingComment subjectFindingComment; @XmlAttribute(name = "type") protected Classes type; @XmlAttribute(name = "typeCode") protected ActRelationshipType typeCode; @XmlAttribute(name = "contextControlCode") protected ContextControl contextControlCode; @XmlAttribute(name = "contextConductionInd") protected Boolean contextConductionInd; @XmlAttribute(name = "templateId") protected List<String> templateId; @XmlAttribute(name = "typeID") protected List<String> typeID; @XmlAttribute(name = "realmCode") protected List<String> realmCode; @XmlAttribute(name = "nullFlavor") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String nullFlavor; /** * Gets the value of the subjectFindingComment property. * * @return * possible object is * {@link PORTMT020001FindingComment } * */ public PORTMT020001FindingComment getSubjectFindingComment() { return subjectFindingComment; } /** * Sets the value of the subjectFindingComment property. * * @param value * allowed object is * {@link PORTMT020001FindingComment } * */ public void setSubjectFindingComment(PORTMT020001FindingComment value) { this.subjectFindingComment = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link Classes } * */ public Classes getType() { if (type == null) { return Classes.ACT_RELATIONSHIP; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link Classes } * */ public void setType(Classes value) { this.type = value; } /** * Gets the value of the typeCode property. * * @return * possible object is * {@link ActRelationshipType } * */ public ActRelationshipType getTypeCode() { return typeCode; } /** * Sets the value of the typeCode property. * * @param value * allowed object is * {@link ActRelationshipType } * */ public void setTypeCode(ActRelationshipType value) { this.typeCode = value; } /** * Gets the value of the contextControlCode property. * * @return * possible object is * {@link ContextControl } * */ public ContextControl getContextControlCode() { if (contextControlCode == null) { return ContextControl.OP; } else { return contextControlCode; } } /** * Sets the value of the contextControlCode property. * * @param value * allowed object is * {@link ContextControl } * */ public void setContextControlCode(ContextControl value) { this.contextControlCode = value; } /** * Gets the value of the contextConductionInd property. * * @return * possible object is * {@link Boolean } * */ public boolean isContextConductionInd() { if (contextConductionInd == null) { return true; } else { return contextConductionInd; } } /** * Sets the value of the contextConductionInd property. * * @param value * allowed object is * {@link Boolean } * */ public void setContextConductionInd(Boolean value) { this.contextConductionInd = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getTemplateId() { if (templateId == null) { templateId = new ArrayList<String>(); } return this.templateId; } /** * Gets the value of the typeID property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the typeID property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTypeID().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getTypeID() { if (typeID == null) { typeID = new ArrayList<String>(); } return this.typeID; } /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<String>(); } return this.realmCode; } /** * Gets the value of the nullFlavor property. * * @return * possible object is * {@link String } * */ public String getNullFlavor() { return nullFlavor; } /** * Sets the value of the nullFlavor property. * * @param value * allowed object is * {@link String } * */ public void setNullFlavor(String value) { this.nullFlavor = value; } }
package pers.ap.soplayer.database; import java.io.File; public class LyricsFile extends MediaItem { File lyricsFile; /** * 歌词文件类构造方法 * @param filename 文件名 * @param url 路径 * @param lyricsFile 文件 */ public LyricsFile(String filename,String url,File lyricsFile){ super(filename, url); this.lyricsFile=lyricsFile; } public File use() { return lyricsFile; } }
/** * 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.uima.alchemy.annotator; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import org.apache.uima.alchemy.digester.DigesterProvider; import org.apache.uima.alchemy.digester.entity.annotated.AnnotatedEntityDigesterProvider; import org.apache.uima.jcas.JCas; /** * * This functionality has been disabled for free API keys * */ @Deprecated public class TextAnnotatedNamedEntityExtractionAnnotator extends AbstractAlchemyAnnotator { protected URL createServiceURI() throws MalformedURLException { return URI.create("http://access.alchemyapi.com/calls/text/TextGetAnnotatedNamedEntityText") .toURL(); } protected String[] getServiceParameters() { return new String[] { "outputMode", "baseUrl", "disambiguate", "quotations", "showSourceText", "coreference" }; } protected DigesterProvider createDigester() { return new AnnotatedEntityDigesterProvider(); } protected void initializeRuntimeParameters(JCas aJCas) { // create parameters string StringBuffer serviceParamsBuf = new StringBuffer(); serviceParamsBuf.append("&text="); String modifiedText = cleanText(aJCas); serviceParamsBuf.append(modifiedText); this.serviceParams += (serviceParamsBuf.toString()); } }
package com.packtpub.java9.concurrency.cookbook.appendix.recipe02; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; public class BadLocks { private Lock lock1, lock2; public BadLocks(Lock lock1, Lock lock2) { this.lock1=lock1; this.lock2=lock2; } public void operation1(){ lock1.lock(); lock2.lock(); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock2.unlock(); lock1.unlock(); } } public void operation2(){ lock2.lock(); lock1.lock(); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock1.unlock(); lock2.unlock(); } } }
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.fhir.examples; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.io.Files; import com.google.fhir.common.JsonFormat.Parser; import com.google.fhir.common.ResourceUtils; import com.google.fhir.r4.core.ContainedResource; import com.google.protobuf.Message; import java.io.IOException; /** * This example reads FHIR resources in json format, one message per file, and emits corresponding * .prototxt files. It is mainly used to generate testdata for JsonFormatTest. */ public class JsonToProtoMain { public static void main(String[] argv) throws IOException { JsonParserArgs args = new JsonParserArgs(argv); Parser fhirParser = Parser.withDefaultTimeZone(args.getDefaultTimezone()); // Process the input files one by one. for (JsonParserArgs.InputOutputFilePair entry : args.getInputOutputFilePairs()) { // We parse as a ContainedResource, because we don't know what type of resource this is. System.out.println("Processing " + entry.input + "..."); ContainedResource.Builder builder = ContainedResource.newBuilder(); String input = Files.asCharSource(entry.input, UTF_8).read(); fhirParser.merge(input, builder); // Extract and print the parsed resource. Message parsed = ResourceUtils.getContainedResource(builder.build()); Files.asCharSink(entry.output, UTF_8).write(parsed.toString()); } } }
/* * 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.xerces.util; import java.util.Hashtable; import org.apache.xerces.dom.AttrImpl; import org.apache.xerces.dom.DocumentImpl; import org.apache.xerces.impl.xs.opti.ElementImpl; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.ls.LSException; /** * Some useful utility methods. * This class was modified in Xerces2 with a view to abstracting as * much as possible away from the representation of the underlying * parsed structure (i.e., the DOM). This was done so that, if Xerces * ever adopts an in-memory representation more efficient than the DOM * (such as a DTM), we should easily be able to convert our schema * parsing to utilize it. * * @version $Id$ */ public class DOMUtil { // // Constructors // /** This class cannot be instantiated. */ protected DOMUtil() {} // // Public static methods // /** * Copies the source tree into the specified place in a destination * tree. The source node and its children are appended as children * of the destination node. * <p> * <em>Note:</em> This is an iterative implementation. */ public static void copyInto(Node src, Node dest) throws DOMException { // get node factory Document factory = dest.getOwnerDocument(); boolean domimpl = factory instanceof DocumentImpl; // placement variables Node start = src; Node parent = src; Node place = src; // traverse source tree while (place != null) { // copy this node Node node = null; int type = place.getNodeType(); switch (type) { case Node.CDATA_SECTION_NODE: { node = factory.createCDATASection(place.getNodeValue()); break; } case Node.COMMENT_NODE: { node = factory.createComment(place.getNodeValue()); break; } case Node.ELEMENT_NODE: { Element element = factory.createElement(place.getNodeName()); node = element; NamedNodeMap attrs = place.getAttributes(); int attrCount = attrs.getLength(); for (int i = 0; i < attrCount; i++) { Attr attr = (Attr)attrs.item(i); String attrName = attr.getNodeName(); String attrValue = attr.getNodeValue(); element.setAttribute(attrName, attrValue); if (domimpl && !attr.getSpecified()) { ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false); } } break; } case Node.ENTITY_REFERENCE_NODE: { node = factory.createEntityReference(place.getNodeName()); break; } case Node.PROCESSING_INSTRUCTION_NODE: { node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue()); break; } case Node.TEXT_NODE: { node = factory.createTextNode(place.getNodeValue()); break; } default: { throw new IllegalArgumentException("can't copy node type, "+ type+" ("+ place.getNodeName()+')'); } } dest.appendChild(node); // iterate over children if (place.hasChildNodes()) { parent = place; place = place.getFirstChild(); dest = node; } // advance else { place = place.getNextSibling(); while (place == null && parent != start) { place = parent.getNextSibling(); parent = parent.getParentNode(); dest = dest.getParentNode(); } } } } // copyInto(Node,Node) /** Finds and returns the first child element node. */ public static Element getFirstChildElement(Node parent) { // search for node Node child = parent.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { return (Element)child; } child = child.getNextSibling(); } // not found return null; } // getFirstChildElement(Node):Element /** Finds and returns the first visible child element node. */ public static Element getFirstVisibleChildElement(Node parent) { // search for node Node child = parent.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE && !isHidden(child)) { return (Element)child; } child = child.getNextSibling(); } // not found return null; } // getFirstChildElement(Node):Element /** Finds and returns the first visible child element node. */ public static Element getFirstVisibleChildElement(Node parent, Hashtable hiddenNodes) { // search for node Node child = parent.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE && !isHidden(child, hiddenNodes)) { return (Element)child; } child = child.getNextSibling(); } // not found return null; } // getFirstChildElement(Node):Element /** Finds and returns the last child element node. * Overload previous method for non-Xerces node impl. */ public static Element getLastChildElement(Node parent) { // search for node Node child = parent.getLastChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { return (Element)child; } child = child.getPreviousSibling(); } // not found return null; } // getLastChildElement(Node):Element /** Finds and returns the last visible child element node. */ public static Element getLastVisibleChildElement(Node parent) { // search for node Node child = parent.getLastChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE && !isHidden(child)) { return (Element)child; } child = child.getPreviousSibling(); } // not found return null; } // getLastChildElement(Node):Element /** Finds and returns the last visible child element node. * Overload previous method for non-Xerces node impl */ public static Element getLastVisibleChildElement(Node parent, Hashtable hiddenNodes) { // search for node Node child = parent.getLastChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE && !isHidden(child, hiddenNodes)) { return (Element)child; } child = child.getPreviousSibling(); } // not found return null; } // getLastChildElement(Node):Element /** Finds and returns the next sibling element node. */ public static Element getNextSiblingElement(Node node) { // search for node Node sibling = node.getNextSibling(); while (sibling != null) { if (sibling.getNodeType() == Node.ELEMENT_NODE) { return (Element)sibling; } sibling = sibling.getNextSibling(); } // not found return null; } // getNextSiblingElement(Node):Element // get next visible (un-hidden) node. public static Element getNextVisibleSiblingElement(Node node) { // search for node Node sibling = node.getNextSibling(); while (sibling != null) { if (sibling.getNodeType() == Node.ELEMENT_NODE && !isHidden(sibling)) { return (Element)sibling; } sibling = sibling.getNextSibling(); } // not found return null; } // getNextSiblingdElement(Node):Element // get next visible (un-hidden) node, overload previous method for non Xerces node impl public static Element getNextVisibleSiblingElement(Node node, Hashtable hiddenNodes) { // search for node Node sibling = node.getNextSibling(); while (sibling != null) { if (sibling.getNodeType() == Node.ELEMENT_NODE && !isHidden(sibling, hiddenNodes)) { return (Element)sibling; } sibling = sibling.getNextSibling(); } // not found return null; } // getNextSiblingdElement(Node):Element // set this Node as being hidden public static void setHidden(Node node) { if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl) ((org.apache.xerces.impl.xs.opti.NodeImpl)node).setReadOnly(true, false); else if (node instanceof org.apache.xerces.dom.NodeImpl) ((org.apache.xerces.dom.NodeImpl)node).setReadOnly(true, false); } // setHidden(node):void // set this Node as being hidden, overloaded method public static void setHidden(Node node, Hashtable hiddenNodes) { if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl) { ((org.apache.xerces.impl.xs.opti.NodeImpl)node).setReadOnly(true, false); } else { hiddenNodes.put(node, ""); } } // setHidden(node):void // set this Node as being visible public static void setVisible(Node node) { if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl) ((org.apache.xerces.impl.xs.opti.NodeImpl)node).setReadOnly(false, false); else if (node instanceof org.apache.xerces.dom.NodeImpl) ((org.apache.xerces.dom.NodeImpl)node).setReadOnly(false, false); } // setVisible(node):void // set this Node as being visible, overloaded method public static void setVisible(Node node, Hashtable hiddenNodes) { if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl) { ((org.apache.xerces.impl.xs.opti.NodeImpl)node).setReadOnly(false, false); } else { hiddenNodes.remove(node); } } // setVisible(node):void // is this node hidden? public static boolean isHidden(Node node) { if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl) return ((org.apache.xerces.impl.xs.opti.NodeImpl)node).getReadOnly(); else if (node instanceof org.apache.xerces.dom.NodeImpl) return ((org.apache.xerces.dom.NodeImpl)node).getReadOnly(); return false; } // isHidden(Node):boolean // is this node hidden? overloaded method public static boolean isHidden(Node node, Hashtable hiddenNodes) { if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl) { return ((org.apache.xerces.impl.xs.opti.NodeImpl)node).getReadOnly(); } else { return hiddenNodes.containsKey(node); } } // isHidden(Node):boolean /** Finds and returns the first child node with the given name. */ public static Element getFirstChildElement(Node parent, String elemName) { // search for node Node child = parent.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName().equals(elemName)) { return (Element)child; } } child = child.getNextSibling(); } // not found return null; } // getFirstChildElement(Node,String):Element /** Finds and returns the last child node with the given name. */ public static Element getLastChildElement(Node parent, String elemName) { // search for node Node child = parent.getLastChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName().equals(elemName)) { return (Element)child; } } child = child.getPreviousSibling(); } // not found return null; } // getLastChildElement(Node,String):Element /** Finds and returns the next sibling node with the given name. */ public static Element getNextSiblingElement(Node node, String elemName) { // search for node Node sibling = node.getNextSibling(); while (sibling != null) { if (sibling.getNodeType() == Node.ELEMENT_NODE) { if (sibling.getNodeName().equals(elemName)) { return (Element)sibling; } } sibling = sibling.getNextSibling(); } // not found return null; } // getNextSiblingdElement(Node,String):Element /** Finds and returns the first child node with the given qualified name. */ public static Element getFirstChildElementNS(Node parent, String uri, String localpart) { // search for node Node child = parent.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { String childURI = child.getNamespaceURI(); if (childURI != null && childURI.equals(uri) && child.getLocalName().equals(localpart)) { return (Element)child; } } child = child.getNextSibling(); } // not found return null; } // getFirstChildElementNS(Node,String,String):Element /** Finds and returns the last child node with the given qualified name. */ public static Element getLastChildElementNS(Node parent, String uri, String localpart) { // search for node Node child = parent.getLastChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { String childURI = child.getNamespaceURI(); if (childURI != null && childURI.equals(uri) && child.getLocalName().equals(localpart)) { return (Element)child; } } child = child.getPreviousSibling(); } // not found return null; } // getLastChildElementNS(Node,String,String):Element /** Finds and returns the next sibling node with the given qualified name. */ public static Element getNextSiblingElementNS(Node node, String uri, String localpart) { // search for node Node sibling = node.getNextSibling(); while (sibling != null) { if (sibling.getNodeType() == Node.ELEMENT_NODE) { String siblingURI = sibling.getNamespaceURI(); if (siblingURI != null && siblingURI.equals(uri) && sibling.getLocalName().equals(localpart)) { return (Element)sibling; } } sibling = sibling.getNextSibling(); } // not found return null; } // getNextSiblingdElementNS(Node,String,String):Element /** Finds and returns the first child node with the given name. */ public static Element getFirstChildElement(Node parent, String elemNames[]) { // search for node Node child = parent.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { for (int i = 0; i < elemNames.length; i++) { if (child.getNodeName().equals(elemNames[i])) { return (Element)child; } } } child = child.getNextSibling(); } // not found return null; } // getFirstChildElement(Node,String[]):Element /** Finds and returns the last child node with the given name. */ public static Element getLastChildElement(Node parent, String elemNames[]) { // search for node Node child = parent.getLastChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { for (int i = 0; i < elemNames.length; i++) { if (child.getNodeName().equals(elemNames[i])) { return (Element)child; } } } child = child.getPreviousSibling(); } // not found return null; } // getLastChildElement(Node,String[]):Element /** Finds and returns the next sibling node with the given name. */ public static Element getNextSiblingElement(Node node, String elemNames[]) { // search for node Node sibling = node.getNextSibling(); while (sibling != null) { if (sibling.getNodeType() == Node.ELEMENT_NODE) { for (int i = 0; i < elemNames.length; i++) { if (sibling.getNodeName().equals(elemNames[i])) { return (Element)sibling; } } } sibling = sibling.getNextSibling(); } // not found return null; } // getNextSiblingdElement(Node,String[]):Element /** Finds and returns the first child node with the given qualified name. */ public static Element getFirstChildElementNS(Node parent, String[][] elemNames) { // search for node Node child = parent.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { for (int i = 0; i < elemNames.length; i++) { String uri = child.getNamespaceURI(); if (uri != null && uri.equals(elemNames[i][0]) && child.getLocalName().equals(elemNames[i][1])) { return (Element)child; } } } child = child.getNextSibling(); } // not found return null; } // getFirstChildElementNS(Node,String[][]):Element /** Finds and returns the last child node with the given qualified name. */ public static Element getLastChildElementNS(Node parent, String[][] elemNames) { // search for node Node child = parent.getLastChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { for (int i = 0; i < elemNames.length; i++) { String uri = child.getNamespaceURI(); if (uri != null && uri.equals(elemNames[i][0]) && child.getLocalName().equals(elemNames[i][1])) { return (Element)child; } } } child = child.getPreviousSibling(); } // not found return null; } // getLastChildElementNS(Node,String[][]):Element /** Finds and returns the next sibling node with the given qualified name. */ public static Element getNextSiblingElementNS(Node node, String[][] elemNames) { // search for node Node sibling = node.getNextSibling(); while (sibling != null) { if (sibling.getNodeType() == Node.ELEMENT_NODE) { for (int i = 0; i < elemNames.length; i++) { String uri = sibling.getNamespaceURI(); if (uri != null && uri.equals(elemNames[i][0]) && sibling.getLocalName().equals(elemNames[i][1])) { return (Element)sibling; } } } sibling = sibling.getNextSibling(); } // not found return null; } // getNextSiblingdElementNS(Node,String[][]):Element /** * Finds and returns the first child node with the given name and * attribute name, value pair. */ public static Element getFirstChildElement(Node parent, String elemName, String attrName, String attrValue) { // search for node Node child = parent.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element)child; if (element.getNodeName().equals(elemName) && element.getAttribute(attrName).equals(attrValue)) { return element; } } child = child.getNextSibling(); } // not found return null; } // getFirstChildElement(Node,String,String,String):Element /** * Finds and returns the last child node with the given name and * attribute name, value pair. */ public static Element getLastChildElement(Node parent, String elemName, String attrName, String attrValue) { // search for node Node child = parent.getLastChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element)child; if (element.getNodeName().equals(elemName) && element.getAttribute(attrName).equals(attrValue)) { return element; } } child = child.getPreviousSibling(); } // not found return null; } // getLastChildElement(Node,String,String,String):Element /** * Finds and returns the next sibling node with the given name and * attribute name, value pair. Since only elements have attributes, * the node returned will be of type Node.ELEMENT_NODE. */ public static Element getNextSiblingElement(Node node, String elemName, String attrName, String attrValue) { // search for node Node sibling = node.getNextSibling(); while (sibling != null) { if (sibling.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element)sibling; if (element.getNodeName().equals(elemName) && element.getAttribute(attrName).equals(attrValue)) { return element; } } sibling = sibling.getNextSibling(); } // not found return null; } // getNextSiblingElement(Node,String,String,String):Element /** * Returns the concatenated child text of the specified node. * This method only looks at the immediate children of type * <code>Node.TEXT_NODE</code> or the children of any child * node that is of type <code>Node.CDATA_SECTION_NODE</code> * for the concatenation. * * @param node The node to look at. */ public static String getChildText(Node node) { // is there anything to do? if (node == null) { return null; } // concatenate children text StringBuffer str = new StringBuffer(); Node child = node.getFirstChild(); while (child != null) { short type = child.getNodeType(); if (type == Node.TEXT_NODE) { str.append(child.getNodeValue()); } else if (type == Node.CDATA_SECTION_NODE) { str.append(getChildText(child)); } child = child.getNextSibling(); } // return text value return str.toString(); } // getChildText(Node):String // return the name of this element public static String getName(Node node) { return node.getNodeName(); } // getLocalName(Element): String /** returns local name of this element if not null, otherwise returns the name of the node */ public static String getLocalName(Node node) { String name = node.getLocalName(); return (name!=null)? name:node.getNodeName(); } // getLocalName(Element): String public static Element getParent(Element elem) { Node parent = elem.getParentNode(); if (parent instanceof Element) return (Element)parent; return null; } // getParent(Element):Element // get the Document of which this Node is a part public static Document getDocument(Node node) { return node.getOwnerDocument(); } // getDocument(Node):Document // return this Document's root node public static Element getRoot(Document doc) { return doc.getDocumentElement(); } // getRoot(Document(: Element // some methods for handling attributes: // return the right attribute node public static Attr getAttr(Element elem, String name) { return elem.getAttributeNode(name); } // getAttr(Element, String):Attr // return the right attribute node public static Attr getAttrNS(Element elem, String nsUri, String localName) { return elem.getAttributeNodeNS(nsUri, localName); } // getAttrNS(Element, String):Attr // get all the attributes for an Element public static Attr[] getAttrs(Element elem) { NamedNodeMap attrMap = elem.getAttributes(); Attr [] attrArray = new Attr[attrMap.getLength()]; for (int i=0; i<attrMap.getLength(); i++) attrArray[i] = (Attr)attrMap.item(i); return attrArray; } // getAttrs(Element): Attr[] // get attribute's value public static String getValue(Attr attribute) { return attribute.getValue(); } // getValue(Attr):String // It is noteworthy that, because of the way the DOM specs // work, the next two methods return the empty string (not // null!) when the attribute with the specified name does not // exist on an element. Beware! // return the value of the attribute of the given element // with the given name public static String getAttrValue(Element elem, String name) { return elem.getAttribute(name); } // getAttr(Element, String):Attr // return the value of the attribute of the given element // with the given name public static String getAttrValueNS(Element elem, String nsUri, String localName) { return elem.getAttributeNS(nsUri, localName); } // getAttrValueNS(Element, String):Attr // return the prefix public static String getPrefix(Node node) { return node.getPrefix(); } // return the namespace URI public static String getNamespaceURI(Node node) { return node.getNamespaceURI(); } // return annotation public static String getAnnotation(Node node) { if (node instanceof ElementImpl) { return ((ElementImpl)node).getAnnotation(); } return null; } // return synthetic annotation public static String getSyntheticAnnotation(Node node) { if (node instanceof ElementImpl) { return ((ElementImpl)node).getSyntheticAnnotation(); } return null; } /** * Creates a DOMException. On J2SE 1.4 and above the cause for the exception will be set. */ public static DOMException createDOMException(short code, Throwable cause) { DOMException de = new DOMException(code, cause != null ? cause.getMessage() : null); if (cause != null && ThrowableMethods.fgThrowableMethodsAvailable) { try { ThrowableMethods.fgThrowableInitCauseMethod.invoke(de, new Object [] {cause}); } // Something went wrong. There's not much we can do about it. catch (Exception e) {} } return de; } /** * Creates an LSException. On J2SE 1.4 and above the cause for the exception will be set. */ public static LSException createLSException(short code, Throwable cause) { LSException lse = new LSException(code, cause != null ? cause.getMessage() : null); if (cause != null && ThrowableMethods.fgThrowableMethodsAvailable) { try { ThrowableMethods.fgThrowableInitCauseMethod.invoke(lse, new Object [] {cause}); } // Something went wrong. There's not much we can do about it. catch (Exception e) {} } return lse; } /** * Holder of methods from java.lang.Throwable. */ static class ThrowableMethods { // Method: java.lang.Throwable.initCause(java.lang.Throwable) private static java.lang.reflect.Method fgThrowableInitCauseMethod = null; // Flag indicating whether or not Throwable methods available. private static boolean fgThrowableMethodsAvailable = false; private ThrowableMethods() {} // Attempt to get methods for java.lang.Throwable on class initialization. static { try { fgThrowableInitCauseMethod = Throwable.class.getMethod("initCause", new Class [] {Throwable.class}); fgThrowableMethodsAvailable = true; } // ClassNotFoundException, NoSuchMethodException or SecurityException // Whatever the case, we cannot use java.lang.Throwable.initCause(java.lang.Throwable). catch (Exception exc) { fgThrowableInitCauseMethod = null; fgThrowableMethodsAvailable = false; } } } } // class DOMUtil
package com.baiye.redscarf.common.util; import com.baiye.redscarf.common.model.base.AuthID; import org.aspectj.lang.ProceedingJoinPoint; /** * 请不要随意修改,如要添加元素,请创建新的类继承该类,在新的类中添加 * * @author 白也 * @date 2020/11/17 3:55 下午 */ public class AopUtils { public static AuthID getAuthId(ProceedingJoinPoint point) { if (point == null) { return null; } AuthID id = null; Object[] args = point.getArgs(); for (Object arg : args) { if (null == arg) { continue; } if (arg instanceof AuthID) { id = (AuthID) arg; break; } } return id; } }
/* * 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.lucene.util; import java.util.Arrays; /** * A builder for {@link CharsRef} instances. * @lucene.internal */ public class CharsRefBuilder implements Appendable { private static final String NULL_STRING = "null"; private final CharsRef ref; /** Sole constructor. */ public CharsRefBuilder() { ref = new CharsRef(); } /** Return a reference to the chars of this builder. */ public char[] chars() { return ref.chars; } /** Return the number of chars in this buffer. */ public int length() { return ref.length; } /** Set the length. */ public void setLength(int length) { this.ref.length = length; } /** Return the char at the given offset. */ public char charAt(int offset) { return ref.chars[offset]; } /** Set a char. */ public void setCharAt(int offset, char b) { ref.chars[offset] = b; } /** * Reset this builder to the empty state. */ public void clear() { ref.length = 0; } @Override public CharsRefBuilder append(CharSequence csq) { if (csq == null) { return append(NULL_STRING); } return append(csq, 0, csq.length()); } @Override public CharsRefBuilder append(CharSequence csq, int start, int end) { if (csq == null) { return append(NULL_STRING); } grow(ref.length + end - start); for (int i = start; i < end; ++i) { setCharAt(ref.length++, csq.charAt(i)); } return this; } @Override public CharsRefBuilder append(char c) { grow(ref.length + 1); setCharAt(ref.length++, c); return this; } /** * Copies the given {@link CharsRef} referenced content into this instance. */ public void copyChars(CharsRef other) { copyChars(other.chars, other.offset, other.length); } /** * Used to grow the reference array. */ public void grow(int newLength) { ref.chars = ArrayUtil.grow(ref.chars, newLength); } /** * Copy the provided bytes, interpreted as UTF-8 bytes. */ public void copyUTF8Bytes(byte[] bytes, int offset, int length) { grow(length); ref.length = UnicodeUtil.UTF8toUTF16(bytes, offset, length, ref.chars); } /** * Copy the provided bytes, interpreted as UTF-8 bytes. */ public void copyUTF8Bytes(BytesRef bytes) { copyUTF8Bytes(bytes.bytes, bytes.offset, bytes.length); } /** * Copies the given array into this instance. */ public void copyChars(char[] otherChars, int otherOffset, int otherLength) { grow(otherLength); System.arraycopy(otherChars, otherOffset, ref.chars, 0, otherLength); ref.length = otherLength; } /** * Appends the given array to this CharsRef */ public void append(char[] otherChars, int otherOffset, int otherLength) { int newLen = ref.length + otherLength; grow(newLen); System.arraycopy(otherChars, otherOffset, ref.chars, ref.length, otherLength); ref.length = newLen; } /** * Return a {@link CharsRef} that points to the internal content of this * builder. Any update to the content of this builder might invalidate * the provided <code>ref</code> and vice-versa. */ public CharsRef get() { assert ref.offset == 0 : "Modifying the offset of the returned ref is illegal"; return ref; } /** Build a new {@link CharsRef} that has the same content as this builder. */ public CharsRef toCharsRef() { return new CharsRef(Arrays.copyOf(ref.chars, ref.length), 0, ref.length); } @Override public String toString() { return get().toString(); } @Override public boolean equals(Object obj) { throw new UnsupportedOperationException(); } @Override public int hashCode() { throw new UnsupportedOperationException(); } }
/** * Copyright 2009-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 * * 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.ibatis.submitted.foreach_map; import java.util.LinkedHashMap; import java.util.Map; public class MapParam { public Map<Object, Object> getMap() { return map; } public void setMap(Map<Object, Object> map) { this.map = map; } private Map<Object, Object> map = new LinkedHashMap<>(); }
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.jscomp.CheckRequiresForConstructors.MISSING_REQUIRE_WARNING; import com.google.common.collect.ImmutableList; import com.google.javascript.jscomp.CheckLevel; import com.google.javascript.jscomp.Result; /** * Tests for {@link CheckRequiresForConstructors}. * */ public class CheckRequiresForConstructorsTest extends CompilerTestCase { @Override protected CompilerPass getProcessor(Compiler compiler) { return new CheckRequiresForConstructors(compiler, CheckLevel.WARNING); } public void testPassWithNoNewNodes() { String js = "var str = 'g4'; /* does not use new */"; testSame(js); } public void testPassWithOneNew() { String js = "var goog = {};" + "goog.require('foo.bar.goo'); var bar = new foo.bar.goo();"; testSame(js); } public void testPassWithOneNewOuterClass() { String js = "var goog = {};" + "goog.require('goog.foo.Bar'); var bar = new goog.foo.Bar.Baz();"; testSame(js); } public void testPassWithOneNewOuterClassWithUpperPrefix() { String js = "var goog = {};" + "goog.require('goog.foo.IDBar'); var bar = new goog.foo.IDBar.Baz();"; testSame(js); } public void testFailWithOneNew() { String[] js = new String[] {"var foo = {}; var bar = new foo.bar();"}; String warning = "'foo.bar' used but not goog.require'd"; test(js, js, null, MISSING_REQUIRE_WARNING, warning); } public void testPassWithTwoNewNodes() { String js = "var goog = {};" + "goog.require('goog.foo.Bar');goog.require('goog.foo.Baz');" + "var str = new goog.foo.Bar('g4'), num = new goog.foo.Baz(5); "; testSame(js); } public void testPassWithNestedNewNodes() { String js = "var goog = {}; goog.require('goog.foo.Bar'); " + "var str = new goog.foo.Bar(new goog.foo.Bar('5')); "; testSame(js); } public void testFailWithNestedNewNodes() { String[] js = new String[] {"var goog = {}; goog.require('goog.foo.Bar'); " + "var str = new goog.foo.Bar(new goog.foo.Baz('5')); "}; String warning = "'goog.foo.Baz' used but not goog.require'd"; test(js, js, null, MISSING_REQUIRE_WARNING, warning); } public void testPassWithLocalFunctions() { String js = "/** @constructor */ function tempCtor() {}; var foo = new tempCtor();"; testSame(js); } public void testPassWithLocalVariables() { String js = "/** @constructor */ var nodeCreator = function() {};" + "var newNode = new nodeCreator();"; testSame(js); } public void testFailWithLocalVariableInMoreThanOneFile() { // there should be a warning for the 2nd script because it is only declared // in the 1st script String localVar = "/** @constructor */ function tempCtor() {}" + "function baz(){" + " /** @constructor */ function tempCtor() {}; " + "var foo = new tempCtor();}"; String[] js = new String[] {localVar, " var foo = new tempCtor();"}; String warning = "'tempCtor' used but not goog.require'd"; test(js, js, null, MISSING_REQUIRE_WARNING, warning); } public void testNewNodesMetaTraditionalFunctionForm() { // the class in this script creates an instance of itself // there should be no warning because the class should not have to // goog.require itself . String js = "/** @constructor */ function Bar(){}; " + "Bar.prototype.bar = function(){ return new Bar();};"; testSame(js); } public void testNewNodesMeta() { String js = "var goog = {};" + "/** @constructor */goog.ui.Option = function(){};" + "goog.ui.Option.optionDecorator = function(){" + " return new goog.ui.Option(); };"; testSame(js); } public void testShouldWarnWhenInstantiatingObjectsDefinedInGlobalScope() { // there should be a warning for the 2nd script because // Bar was declared in the 1st file, not the 2nd String good = "/** @constructor */ function Bar(){}; " + "Bar.prototype.bar = function(){return new Bar();};"; String bad = "/** @constructor */ function Foo(){ var bar = new Bar();}"; String[] js = new String[] {good, bad}; String warning = "'Bar' used but not goog.require'd"; test(js, js, null, MISSING_REQUIRE_WARNING, warning); } public void testShouldWarnWhenInstantiatingGlobalClassesFromGlobalScope() { // there should be a warning for the 2nd script because Baz // was declared in the first file, not the 2nd String good = "/** @constructor */ function Baz(){}; " + "Baz.prototype.bar = function(){return new Baz();};"; String bad = "var baz = new Baz()"; String[] js = new String[] {good, bad}; String warning = "'Baz' used but not goog.require'd"; test(js, js, null, MISSING_REQUIRE_WARNING, warning); } public void testIgnoresNativeObject() { String externs = "/** @constructor */ function String(val) {}"; String js = "var str = new String('4');"; test(externs, js, js, null, null); } public void testNewNodesWithMoreThanOneFile() { // Bar is created, and goog.require()ed, but in different files. String[] js = new String[] { "var goog = {};" + "/** @constructor */ function Bar() {}" + "goog.require('Bar');", "var bar = new Bar();"}; String warning = "'Bar' used but not goog.require'd"; test(js, js, null, MISSING_REQUIRE_WARNING, warning); } public void testPassWithoutWarningsAndMultipleFiles() { String[] js = new String[] { "var goog = {};" + "goog.require('Foo'); var foo = new Foo();", "goog.require('Bar'); var bar = new Bar();"}; testSame(js); } public void testFailWithWarningsAndMultipleFiles() { /* goog.require is in the code base, but not in the correct file */ String[] js = new String[] { "var goog = {};" + "/** @constructor */ function Bar() {}" + "goog.require('Bar');", "var bar = new Bar();"}; String warning = "'Bar' used but not goog.require'd"; test(js, js, null, MISSING_REQUIRE_WARNING, warning); } public void testCanStillCallNumberWithoutNewOperator() { String externs = "/** @constructor */ function Number(opt_value) {}"; String js = "var n = Number('42');"; test(externs, js, js, null, null); js = "var n = Number();"; test(externs, js, js, null, null); } public void testRequiresAreCaughtBeforeProcessed() { String js = "var foo = {}; var bar = new foo.bar.goo();"; SourceFile input = SourceFile.fromCode("foo.js", js); Compiler compiler = new Compiler(); CompilerOptions opts = new CompilerOptions(); opts.checkRequires = CheckLevel.WARNING; opts.closurePass = true; Result result = compiler.compile(ImmutableList.<SourceFile>of(), ImmutableList.of(input), opts); JSError[] warnings = result.warnings; assertNotNull(warnings); assertTrue(warnings.length > 0); String expectation = "'foo.bar.goo' used but not goog.require'd"; for (JSError warning : warnings) { if (expectation.equals(warning.description)) { return; } } fail("Could not find the following warning:" + expectation); } public void testNoWarningsForThisConstructor() { String js = "var goog = {};" + "/** @constructor */goog.Foo = function() {};" + "goog.Foo.bar = function() {" + " return new this.constructor; " + "};"; testSame(js); } public void testBug2062487() { testSame( "var goog = {};" + "/** @constructor */goog.Foo = function() {" + " /** @constructor */ this.x_ = function() {};" + " this.y_ = new this.x_();" + "};"); } public void testIgnoreDuplicateWarningsForSingleClasses(){ // no use telling them the same thing twice String[] js = new String[]{ "var goog = {};" + "/** @constructor */goog.Foo = function() {};" + "goog.Foo.bar = function(){" + " var first = new goog.Forgot();" + " var second = new goog.Forgot();" + "};"}; String warning = "'goog.Forgot' used but not goog.require'd"; test(js, js, null, MISSING_REQUIRE_WARNING, warning); } }
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sym.demozxing.zxing; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.PlanarYUVLuminanceSource; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.common.HybridBinarizer; import com.sym.demozxing.R; import java.io.ByteArrayOutputStream; import java.util.Map; final class DecodeHandler extends Handler { private static final String TAG = DecodeHandler.class.getSimpleName(); private final CaptureActivity activity; private final MultiFormatReader multiFormatReader; private boolean running = true; DecodeHandler(CaptureActivity activity, Map<DecodeHintType,Object> hints) { multiFormatReader = new MultiFormatReader(); multiFormatReader.setHints(hints); this.activity = activity; } @Override public void handleMessage(Message message) { if (!running) { return; } switch (message.what) { case R.id.decode: decode((byte[]) message.obj, message.arg1, message.arg2); break; case R.id.quit: running = false; Looper.myLooper().quit(); break; } } /** * Decode the data within the viewfinder rectangle, and time how long it took. For efficiency, * reuse the same reader objects from one decode to the next. * * @param data The YUV preview frame. * @param width The width of the preview frame. * @param height The height of the preview frame. */ private void decode(byte[] data, int width, int height) { long start = System.currentTimeMillis(); Result rawResult = null; //下面这段代码是新添加的 byte[] rotatedData = new byte[data.length]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) rotatedData[x * height + height - y - 1] = data[x + y * width]; } int tmp = width; width = height; height = tmp; data = rotatedData; PlanarYUVLuminanceSource source = activity.getCameraManager().buildLuminanceSource(data, width, height); if (source != null) { BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); try { rawResult = multiFormatReader.decodeWithState(bitmap); } catch (ReaderException re) { // continue } finally { multiFormatReader.reset(); } } Handler handler = activity.getHandler(); if (rawResult != null) { // Don't log the barcode contents for security. long end = System.currentTimeMillis(); Log.d(TAG, "Found barcode in " + (end - start) + " ms"); if (handler != null) { Message message = Message.obtain(handler, R.id.decode_succeeded, rawResult); Bundle bundle = new Bundle(); bundleThumbnail(source, bundle); message.setData(bundle); message.sendToTarget(); } } else { if (handler != null) { Message message = Message.obtain(handler, R.id.decode_failed); message.sendToTarget(); } } } private static void bundleThumbnail(PlanarYUVLuminanceSource source, Bundle bundle) { int[] pixels = source.renderThumbnail(); int width = source.getThumbnailWidth(); int height = source.getThumbnailHeight(); Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.ARGB_8888); ByteArrayOutputStream out = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out); bundle.putByteArray(DecodeThread.BARCODE_BITMAP, out.toByteArray()); bundle.putFloat(DecodeThread.BARCODE_SCALED_FACTOR, (float) width / source.getWidth()); } }
/* * Gitea API. * This documentation describes the Gitea API. * * OpenAPI spec version: 1.1.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.gitea.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * CreateStatusOption holds the information needed to create a new Status for a Commit */ @ApiModel(description = "CreateStatusOption holds the information needed to create a new Status for a Commit") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-10-15T10:08:30.717+03:00") public class CreateStatusOption { @SerializedName("context") private String context = null; @SerializedName("description") private String description = null; @SerializedName("state") private String state = null; @SerializedName("target_url") private String targetUrl = null; public CreateStatusOption context(String context) { this.context = context; return this; } /** * Get context * @return context **/ @ApiModelProperty(value = "") public String getContext() { return context; } public void setContext(String context) { this.context = context; } public CreateStatusOption description(String description) { this.description = description; return this; } /** * Get description * @return description **/ @ApiModelProperty(value = "") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public CreateStatusOption state(String state) { this.state = state; return this; } /** * Get state * @return state **/ @ApiModelProperty(value = "") public String getState() { return state; } public void setState(String state) { this.state = state; } public CreateStatusOption targetUrl(String targetUrl) { this.targetUrl = targetUrl; return this; } /** * Get targetUrl * @return targetUrl **/ @ApiModelProperty(value = "") public String getTargetUrl() { return targetUrl; } public void setTargetUrl(String targetUrl) { this.targetUrl = targetUrl; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateStatusOption createStatusOption = (CreateStatusOption) o; return Objects.equals(this.context, createStatusOption.context) && Objects.equals(this.description, createStatusOption.description) && Objects.equals(this.state, createStatusOption.state) && Objects.equals(this.targetUrl, createStatusOption.targetUrl); } @Override public int hashCode() { return Objects.hash(context, description, state, targetUrl); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CreateStatusOption {\n"); sb.append(" context: ").append(toIndentedString(context)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" state: ").append(toIndentedString(state)).append("\n"); sb.append(" targetUrl: ").append(toIndentedString(targetUrl)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.browser_ui.notifications; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationChannelGroup; import android.os.Build; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Mocked implementation of the NotificationManagerProxy. Imitates behavior of the Android * notification manager, and provides access to the displayed notifications for tests. */ public class MockNotificationManagerProxy implements NotificationManagerProxy { private static final String KEY_SEPARATOR = ":"; /** * Holds a notification and the arguments passed to #notify and #cancel. */ public static class NotificationEntry { public final Notification notification; public final String tag; public final int id; NotificationEntry(Notification notification, String tag, int id) { this.notification = notification; this.tag = tag; this.id = id; } } // Maps (id:tag) to a NotificationEntry. private final Map<String, NotificationEntry> mNotifications; private int mMutationCount; private boolean mNotificationsEnabled = true; public MockNotificationManagerProxy() { mNotifications = new LinkedHashMap<>(); mMutationCount = 0; } /** * Returns the notifications currently managed by the mocked notification manager, in the order * in which they were shown, together with their associated tag and id. The list is not updated * when the internal data structure changes. * * @return List of the managed notifications. */ public List<NotificationEntry> getNotifications() { return new ArrayList<>(mNotifications.values()); } /** * May be used by tests to determine if a call has recently successfully been handled by the * notification manager. If the mutation count is higher than zero, it will be decremented by * one automatically. * * @return The number of recent mutations. */ public int getMutationCountAndDecrement() { int mutationCount = mMutationCount; if (mutationCount > 0) mMutationCount--; return mutationCount; } public void setNotificationsEnabled(boolean enabled) { mNotificationsEnabled = enabled; } @Override public boolean areNotificationsEnabled() { return mNotificationsEnabled; } @Override public void cancel(int id) { cancel(null /* tag */, id); } @Override public void cancel(@Nullable String tag, int id) { String key = makeKey(id, tag); mNotifications.remove(key); mMutationCount++; } @Override public void cancelAll() { mNotifications.clear(); mMutationCount++; } @Override public void notify(int id, Notification notification) { notify(null /* tag */, id, notification); } @Override public void notify(@Nullable String tag, int id, Notification notification) { mNotifications.put(makeKey(id, tag), new NotificationEntry(notification, tag, id)); mMutationCount++; } @Override public void notify(ChromeNotification notification) { notify(notification.getMetadata().tag, notification.getMetadata().id, notification.getNotification()); } private static String makeKey(int id, @Nullable String tag) { String key = Integer.toString(id); if (tag != null) key += KEY_SEPARATOR + tag; return key; } // The following Channel methods are not implemented because a naive implementation would // have compatibility issues (NotificationChannel is new in O), and we currently don't need them // where the MockNotificationManagerProxy is used in tests. @TargetApi(Build.VERSION_CODES.O) @Override public void createNotificationChannel(NotificationChannel channel) {} @TargetApi(Build.VERSION_CODES.O) @Override public void createNotificationChannelGroup(NotificationChannelGroup channelGroup) {} @TargetApi(Build.VERSION_CODES.O) @Override public List<NotificationChannel> getNotificationChannels() { return null; } @Override @TargetApi(Build.VERSION_CODES.O) public List<NotificationChannelGroup> getNotificationChannelGroups() { return null; } @TargetApi(Build.VERSION_CODES.O) @Override public void deleteNotificationChannel(String id) {} @TargetApi(Build.VERSION_CODES.O) @Override public NotificationChannel getNotificationChannel(String channelId) { return null; } @Override public void deleteNotificationChannelGroup(String groupId) {} }
package org.checkerframework.dataflow.cfg.node; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.Tree; import java.util.Objects; import org.checkerframework.checker.nullness.qual.Nullable; /** * A node for a conditional or expression: * * <pre> * <em>expression</em> || <em>expression</em> * </pre> */ public class ConditionalOrNode extends BinaryOperationNode { /** * Create a new ConditionalOrNode. * * @param tree the conditional-or tree for this node * @param left the first argument * @param right the second argument */ public ConditionalOrNode(BinaryTree tree, Node left, Node right) { super(tree, left, right); assert tree.getKind() == Tree.Kind.CONDITIONAL_OR; } @Override public <R, P> R accept(NodeVisitor<R, P> visitor, P p) { return visitor.visitConditionalOr(this, p); } @Override public String toString() { return "(" + getLeftOperand() + " || " + getRightOperand() + ")"; } @Override public boolean equals(@Nullable Object obj) { if (!(obj instanceof ConditionalOrNode)) { return false; } ConditionalOrNode other = (ConditionalOrNode) obj; return getLeftOperand().equals(other.getLeftOperand()) && getRightOperand().equals(other.getRightOperand()); } @Override public int hashCode() { return Objects.hash(getLeftOperand(), getRightOperand()); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.06.12 at 09:16:35 AM EDT // package com.vmware.vim25; /** * */ @SuppressWarnings("all") public class UserProfile extends ApplyProfile { public String key; public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
/* * This file is part of dependency-check-core. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) 2020 The OWASP Foundation. All Rights Reserved. */ package org.owasp.dependencycheck.analyzer; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.exception.InitializationException; import org.owasp.dependencycheck.utils.FileFilterBuilder; import org.owasp.dependencycheck.utils.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import us.springett.parsers.cpe.exceptions.CpeValidationException; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.owasp.dependencycheck.processing.MixAuditProcessor; import org.owasp.dependencycheck.utils.processing.ProcessReader; @Experimental public class ElixirMixAuditAnalyzer extends AbstractFileTypeAnalyzer { /** * The logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(ElixirMixAuditAnalyzer.class); /** * A descriptor for the type of dependencies processed or added by this * analyzer. */ public static final String DEPENDENCY_ECOSYSTEM = "elixir"; /** * The name of the analyzer. */ private static final String ANALYZER_NAME = "Elixir Mix Audit Analyzer"; /** * The phase that this analyzer is intended to run in. */ private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.PRE_INFORMATION_COLLECTION; /** * The filter defining which files will be analyzed. */ private static final FileFilter FILTER = FileFilterBuilder.newInstance().addFilenames("mix.lock").build(); /** * Name. */ public static final String NAME = "Name: "; /** * Version. */ public static final String VERSION = "Version: "; /** * Advisory. */ public static final String ADVISORY = "Advisory: "; /** * Criticality. */ public static final String CRITICALITY = "Criticality: "; /** * The DAL. */ private CveDB cvedb = null; /** * @return a filter that accepts files named mix.lock */ @Override protected FileFilter getFileFilter() { return FILTER; } @Override protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException { if (engine != null) { this.cvedb = engine.getDatabase(); } // Here we check if mix_audit actually runs from this location. We do this by running the // `mix_audit --version` command and seeing whether or not it succeeds (if it returns with an exit value of 0) final Process process; try { final List<String> mixAuditArgs = ImmutableList.of("--version"); process = launchMixAudit(getSettings().getTempDirectory(), mixAuditArgs); } catch (AnalysisException ae) { setEnabled(false); final String msg = String.format("Exception from mix_audit process: %s. Disabling %s", ae.getCause(), ANALYZER_NAME); throw new InitializationException(msg, ae); } catch (IOException ex) { setEnabled(false); throw new InitializationException("Unable to create temporary file, the Mix Audit Analyzer will be disabled", ex); } final int exitValue; final String mixAuditVersionDetails; try (ProcessReader processReader = new ProcessReader(process)) { processReader.readAll(); exitValue = process.exitValue(); if (exitValue != 0) { if (Strings.isNullOrEmpty(processReader.getError())) { LOGGER.warn("Unexpected exit value from mix_audit process and error stream unexpectedly not ready to capture error details. " + "Disabling {}. Exit value was: {}", ANALYZER_NAME, exitValue); setEnabled(false); throw new InitializationException("mix_audit error stream unexpectedly not ready."); } else { setEnabled(false); LOGGER.warn("Unexpected exit value from mix_audit process. Disabling {}. Exit value was: {}. " + "error stream output from mix_audit process was: {}", ANALYZER_NAME, exitValue, processReader.getError()); throw new InitializationException("Unexpected exit value from bundle-audit process."); } } else { if (Strings.isNullOrEmpty(processReader.getOutput())) { LOGGER.warn("mix_audit input stream unexpectedly not ready to capture version details. Disabling {}", ANALYZER_NAME); setEnabled(false); throw new InitializationException("mix_audit input stream unexpectedly not ready to capture version details."); } else { mixAuditVersionDetails = processReader.getOutput(); } } } catch (InterruptedException ex) { setEnabled(false); final String msg = String.format("mix_audit process was interrupted. Disabling %s", ANALYZER_NAME); Thread.currentThread().interrupt(); throw new InitializationException(msg); } catch (IOException ex) { setEnabled(false); final String msg = String.format("IOException '%s' during mix_audit process was interrupted. Disabling %s", ex.getMessage(), ANALYZER_NAME); throw new InitializationException(msg); } if (isEnabled()) { LOGGER.debug("{} is enabled and is using mix_audit with version: {}.", ANALYZER_NAME, mixAuditVersionDetails); } } /** * Returns the key used in the properties file to reference the analyzer's * enabled property. * * @return the analyzer's enabled property setting key */ @Override protected String getAnalyzerEnabledSettingKey() { return Settings.KEYS.ANALYZER_MIX_AUDIT_ENABLED; } /** * Returns the name of the analyzer. * * @return the name of the analyzer. */ @Override public String getName() { return ANALYZER_NAME; } /** * Returns the phase that the analyzer is intended to run in. * * @return the phase that the analyzer is intended to run in. */ @Override public AnalysisPhase getAnalysisPhase() { return ANALYSIS_PHASE; } /** * Launch mix audit. * * @param folder directory that contains the mix.lock file * @param mixAuditArgs the arguments to pass to mix audit * @return a handle to the process * @throws AnalysisException thrown when there is an issue launching mix * audit */ private Process launchMixAudit(File folder, List<String> mixAuditArgs) throws AnalysisException { if (!folder.isDirectory()) { throw new AnalysisException(String.format("%s should have been a directory.", folder.getAbsolutePath())); } final List<String> args = new ArrayList<>(); final String mixAuditPath = getSettings().getString(Settings.KEYS.ANALYZER_MIX_AUDIT_PATH); File mixAudit = null; if (mixAuditPath != null) { mixAudit = new File(mixAuditPath); if (!mixAudit.isFile()) { LOGGER.warn("Supplied `mixAudit` path is incorrect: {}", mixAuditPath); mixAudit = null; } } else { final Path homePath = Paths.get(System.getProperty("user.home")); final Path escriptPath = Paths.get(homePath.toString(), ".mix", "escripts", "mix_audit"); mixAudit = escriptPath.toFile(); } args.add(mixAudit != null ? mixAudit.getAbsolutePath() : "mix_audit"); args.addAll(mixAuditArgs); final ProcessBuilder builder = new ProcessBuilder(args); builder.directory(folder); try { LOGGER.info("Launching: {} from {}", args, folder); return builder.start(); } catch (IOException ioe) { throw new AnalysisException("mix_audit initialization failure; this error can be ignored if you are not analyzing Elixir. " + "Otherwise ensure that mix_audit is installed and the path to mix_audit is correctly specified", ioe); } } /** * Determines if the analyzer can analyze the given file type. * * @param dependency the dependency to determine if it can analyze * @param engine the dependency-check engine * @throws AnalysisException thrown if there is an analysis exception. */ @Override protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { final File parentFile = dependency.getActualFile().getParentFile(); final List<String> mixAuditArgs = ImmutableList.of("--format", "json"); final Process process = launchMixAudit(parentFile, mixAuditArgs); final int exitValue; try (MixAuditProcessor processor = new MixAuditProcessor(dependency, engine); ProcessReader processReader = new ProcessReader(process, processor)) { processReader.readAll(); exitValue = process.exitValue(); if (exitValue < 0 || exitValue > 1) { final String msg = String.format("Unexpected exit code from mix_audit process; exit code: %s", exitValue); throw new AnalysisException(msg); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new AnalysisException("mix_audit process interrupted", ie); } catch (IOException | CpeValidationException ioe) { LOGGER.warn("mix_audit failure", ioe); throw new AnalysisException("mix_audit failure", ioe); } } }
/* * Created on May 13, 2006 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package biomight.disease.noninfectious; /** * @author SurferJim * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class WaldenstromMacroglobulinemia { }
/** * 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.zookeeper.test; import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT; import java.io.File; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.PortAssignment; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZKTestCase; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Id; import org.apache.zookeeper.server.ServerCnxnFactory; import org.apache.zookeeper.server.SyncRequestProcessor; import org.apache.zookeeper.server.ZooKeeperServer; import org.junit.Assert; import org.junit.Test; public class ACLTest extends ZKTestCase implements Watcher { private static final Logger LOG = LoggerFactory.getLogger(ACLTest.class); private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique(); private volatile CountDownLatch startSignal; @Test public void testDisconnectedAddAuth() throws Exception { File tmpDir = ClientBase.createTmpDir(); ClientBase.setupTestEnv(); ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000); SyncRequestProcessor.setSnapCount(1000); final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]); ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1); f.startup(zks); try { LOG.info("starting up the zookeeper server .. waiting"); Assert.assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT)); ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this); try { zk.addAuthInfo("digest", "pat:test".getBytes()); zk.setACL("/", Ids.CREATOR_ALL_ACL, -1); } finally { zk.close(); } } finally { f.shutdown(); zks.shutdown(); Assert.assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT)); } } /** * Verify that acl optimization of storing just * a few acls and there references in the data * node is actually working. */ @Test public void testAcls() throws Exception { File tmpDir = ClientBase.createTmpDir(); ClientBase.setupTestEnv(); ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000); SyncRequestProcessor.setSnapCount(1000); final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]); ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1); f.startup(zks); ZooKeeper zk; String path; try { LOG.info("starting up the zookeeper server .. waiting"); Assert.assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT)); zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this); LOG.info("starting creating acls"); for (int i = 0; i < 100; i++) { path = "/" + i; zk.create(path, path.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } Assert.assertTrue("size of the acl map ", (1 == zks.getZKDatabase().getAclSize())); for (int j = 100; j < 200; j++) { path = "/" + j; ACL acl = new ACL(); acl.setPerms(0); Id id = new Id(); id.setId("1.1.1."+j); id.setScheme("ip"); acl.setId(id); ArrayList<ACL> list = new ArrayList<ACL>(); list.add(acl); zk.create(path, path.getBytes(), list, CreateMode.PERSISTENT); } Assert.assertTrue("size of the acl map ", (101 == zks.getZKDatabase().getAclSize())); } finally { // now shutdown the server and restart it f.shutdown(); zks.shutdown(); Assert.assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT)); } startSignal = new CountDownLatch(1); zks = new ZooKeeperServer(tmpDir, tmpDir, 3000); f = ServerCnxnFactory.createFactory(PORT, -1); f.startup(zks); try { Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT)); startSignal.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); Assert.assertTrue("count == 0", startSignal.getCount() == 0); Assert.assertTrue("acl map ", (101 == zks.getZKDatabase().getAclSize())); for (int j = 200; j < 205; j++) { path = "/" + j; ACL acl = new ACL(); acl.setPerms(0); Id id = new Id(); id.setId("1.1.1."+j); id.setScheme("ip"); acl.setId(id); ArrayList<ACL> list = new ArrayList<ACL>(); list.add(acl); zk.create(path, path.getBytes(), list, CreateMode.PERSISTENT); } Assert.assertTrue("acl map ", (106 == zks.getZKDatabase().getAclSize())); zk.close(); } finally { f.shutdown(); zks.shutdown(); Assert.assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT)); } } /* * (non-Javadoc) * * @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatcherEvent) */ public void process(WatchedEvent event) { LOG.info("Event:" + event.getState() + " " + event.getType() + " " + event.getPath()); if (event.getState() == KeeperState.SyncConnected) { if (startSignal != null && startSignal.getCount() > 0) { LOG.info("startsignal.countDown()"); startSignal.countDown(); } else { LOG.warn("startsignal " + startSignal); } } } }
package com.crd.demo.common.models.response; import java.io.Serializable; import java.util.Date; /** * SearchResponse from Remote Source * * @author YuCheng Hu */ public class SearchResponse implements Serializable { private static final long serialVersionUID = -2014480627591149391L; private String uuid; private Date currentDate; public static long getSerialVersionUID() { return serialVersionUID; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public Date getCurrentDate() { return currentDate; } public void setCurrentDate(Date currentDate) { this.currentDate = currentDate; } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v201811; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * The action used for approving {@link Order} objects. All {@link LineItem} * objects within the order will be approved as well. This action does not * make any changes to the {@link LineItem#reservationStatus} of the line * items within the order. If there are reservable line items that have not * been reserved the operation will not succeed. * * * <p>Java class for ApproveOrdersWithoutReservationChanges complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ApproveOrdersWithoutReservationChanges"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201811}OrderAction"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ApproveOrdersWithoutReservationChanges") public class ApproveOrdersWithoutReservationChanges extends OrderAction { }
/* * 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.ignite.internal.processors.igfs; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import junit.framework.TestCase; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.igfs.IgfsMode; import org.apache.ignite.igfs.IgfsPath; import org.apache.ignite.internal.util.typedef.T2; import static org.apache.ignite.igfs.IgfsMode.DUAL_ASYNC; import static org.apache.ignite.igfs.IgfsMode.DUAL_SYNC; import static org.apache.ignite.igfs.IgfsMode.PRIMARY; import static org.apache.ignite.igfs.IgfsMode.PROXY; /** * */ public class IgfsModeResolverSelfTest extends TestCase { /** */ private IgfsModeResolver reslvr; /** {@inheritDoc} */ @Override protected void setUp() throws Exception { reslvr = new IgfsModeResolver(DUAL_SYNC, new ArrayList<>(Arrays.asList(new T2<>( new IgfsPath("/a/b/c/d"), PROXY), new T2<>(new IgfsPath("/a/P/"), PRIMARY), new T2<>(new IgfsPath("/a/b/"), DUAL_ASYNC)))); } /** * @throws Exception If failed. */ public void testCanContain() throws Exception { for (IgfsMode m: IgfsMode.values()) { // Each mode can contain itself: assertTrue(IgfsUtils.canContain(m, m)); // PRIMARY and PROXY can contain itself only: assertTrue(IgfsUtils.canContain(PRIMARY,m) == (m == PRIMARY)); assertTrue(IgfsUtils.canContain(PROXY,m) == (m == PROXY)); // Any mode but PRIMARY & PROXY can contain any mode: if (m != PRIMARY && m != PROXY) for (IgfsMode n: IgfsMode.values()) assertTrue(IgfsUtils.canContain(m,n)); } } /** * @throws Exception If failed. */ public void testResolve() throws Exception { assertEquals(DUAL_SYNC, reslvr.resolveMode(IgfsPath.ROOT)); assertEquals(DUAL_SYNC, reslvr.resolveMode(new IgfsPath("/a"))); assertEquals(DUAL_SYNC, reslvr.resolveMode(new IgfsPath("/a/1"))); assertEquals(PRIMARY, reslvr.resolveMode(new IgfsPath("/a/P"))); assertEquals(PRIMARY, reslvr.resolveMode(new IgfsPath("/a/P/c"))); assertEquals(PRIMARY, reslvr.resolveMode(new IgfsPath("/a/P/c/2"))); assertEquals(DUAL_ASYNC, reslvr.resolveMode(new IgfsPath("/a/b/"))); assertEquals(DUAL_ASYNC, reslvr.resolveMode(new IgfsPath("/a/b/3"))); assertEquals(DUAL_ASYNC, reslvr.resolveMode(new IgfsPath("/a/b/3/4"))); assertEquals(PROXY, reslvr.resolveMode(new IgfsPath("/a/b/c/d"))); assertEquals(PROXY, reslvr.resolveMode(new IgfsPath("/a/b/c/d/5"))); assertEquals(PROXY, reslvr.resolveMode(new IgfsPath("/a/b/c/d/6"))); } /** * @throws Exception If failed. */ public void testModesValidation() throws Exception { // Another mode inside PRIMARY directory: try { IgfsUtils.preparePathModes(DUAL_SYNC, Arrays.asList( new T2<>(new IgfsPath("/a/"), PRIMARY), new T2<>(new IgfsPath("/a/b/"), DUAL_ASYNC)), new HashSet<IgfsPath>()); fail("IgniteCheckedException expected"); } catch (IgniteCheckedException ice) { // Expected. } // PRIMARY default mode and non-primary subfolder: for (IgfsMode m: IgfsMode.values()) { if (m != IgfsMode.PRIMARY) { try { IgfsUtils.preparePathModes(PRIMARY, Arrays.asList(new T2<>(new IgfsPath("/a/"), DUAL_ASYNC)), new HashSet<IgfsPath>()); fail("IgniteCheckedException expected"); } catch (IgniteCheckedException ice) { // Expected. } } } // Duplicated sub-folders should be ignored: List<T2<IgfsPath, IgfsMode>> modes = IgfsUtils.preparePathModes(DUAL_SYNC, Arrays.asList( new T2<>(new IgfsPath("/a"), PRIMARY), new T2<>(new IgfsPath("/c/d/"), PRIMARY), new T2<>(new IgfsPath("/c/d/e/f"), PRIMARY) ), new HashSet<IgfsPath>()); assertNotNull(modes); assertEquals(2, modes.size()); assertEquals(modes, Arrays.asList( new T2<>(new IgfsPath("/c/d/"), PRIMARY), new T2<>(new IgfsPath("/a"), PRIMARY) )); // Non-duplicated sub-folders should not be ignored: modes = IgfsUtils.preparePathModes(DUAL_SYNC, Arrays.asList( new T2<>(new IgfsPath("/a/b"), DUAL_ASYNC), new T2<>(new IgfsPath("/a/b/c"), DUAL_SYNC), new T2<>(new IgfsPath("/a/b/c/d"), DUAL_ASYNC) ), new HashSet<IgfsPath>()); assertNotNull(modes); assertEquals(modes.size(), 3); assertEquals(modes, Arrays.asList( new T2<>(new IgfsPath("/a/b/c/d"), DUAL_ASYNC), new T2<>(new IgfsPath("/a/b/c"), DUAL_SYNC), new T2<>(new IgfsPath("/a/b"), DUAL_ASYNC) )); } /** * @throws Exception If failed. */ public void testDualParentsWithPrimaryChild() throws Exception { Set<IgfsPath> set = new HashSet<>(); IgfsUtils.preparePathModes(DUAL_SYNC, Arrays.asList( new T2<>(new IgfsPath("/a/b"), DUAL_ASYNC), new T2<>(new IgfsPath("/a/b/c"), PRIMARY), new T2<>(new IgfsPath("/a/b/x/y"), PRIMARY), new T2<>(new IgfsPath("/a/b/x/z"), PRIMARY), new T2<>(new IgfsPath("/m"), PRIMARY) ), set); assertEquals(set, new HashSet<IgfsPath>() {{ add(new IgfsPath("/a/b")); add(new IgfsPath("/a/b/x")); add(IgfsPath.ROOT); }}); set = new HashSet<>(); IgfsUtils.preparePathModes(DUAL_ASYNC, Arrays.asList( new T2<>(new IgfsPath("/a/b/x/y/z"), PRIMARY), new T2<>(new IgfsPath("/a/b/c"), PRIMARY), new T2<>(new IgfsPath("/a/k"), PRIMARY), new T2<>(new IgfsPath("/a/z"), PRIMARY) ), set); assertEquals(set, new HashSet<IgfsPath>() {{ add(new IgfsPath("/a/b")); add(new IgfsPath("/a")); add(new IgfsPath("/a/b/x/y")); }}); } }
package com.dianping.pigeon.governor.service; import java.util.List; import com.dianping.pigeon.registry.exception.RegistryException; /** * pigeon注册信息服务 * @author xiangwu * */ public interface RegistrationInfoService { /** * 获取服务的应用名称 * @param url 服务名称,标示一个服务的url * @param group 泳道名称,没有填null * @return 应用名称 * @throws RegistryException */ String getAppOfService(String url, String group) throws RegistryException; /** * 获取服务的应用名称 * @param url 服务名称,标示一个服务的url * @return 应用名称 * @throws RegistryException */ String getAppOfService(String url) throws RegistryException; /** * 获取服务地址的权重 * @param address 服务地址,格式ip:port * @return 权重 * @throws RegistryException */ String getWeightOfAddress(String address) throws RegistryException; /** * 获取服务地址的应用名称 * @param address 服务地址,格式ip:port * @return 应用名称 * @throws RegistryException */ String getAppOfAddress(String address) throws RegistryException; /** * 获取服务的地址列表 * @param url 服务名称,标示一个服务的url * @param group 泳道,没有填null * @return 逗号分隔的地址列表,地址格式ip:port * @throws RegistryException */ List<String> getAddressListOfService(String url, String group) throws RegistryException; /** * 获取服务的地址列表 * @param url 服务名称,标示一个服务的url * @return 逗号分隔的地址列表,地址格式ip:port * @throws RegistryException */ List<String> getAddressListOfService(String url) throws RegistryException; }
package productManage.dao.yk.Imp; import java.util.List; import org.hibernate.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import productManage.dao.BaseDao; import productManage.dao.yk.SampleOrderDAO; import productManage.model.yk.SampleOrders; @Repository public class SampleOrderDAOImp implements SampleOrderDAO{ @Autowired private BaseDao baseDao; @Override public void save(SampleOrders sampleOrder) { // TODO Auto-generated method stub baseDao.save(sampleOrder); } @Override public void update(SampleOrders sampleOrder) { // TODO Auto-generated method stub baseDao.update(sampleOrder); } @Override public void detele(SampleOrders sampleOrder) { // TODO Auto-generated method stub baseDao.delete(sampleOrder); } @Override public List<SampleOrders> getAllSampleOrders() { // TODO Auto-generated method stub return baseDao.getAllList(SampleOrders.class); } @Override public SampleOrders getSampleOrderByID(int sampleOrderID) { // TODO Auto-generated method stub return (SampleOrders) baseDao.load(SampleOrders.class, sampleOrderID); } @Override public SampleOrders getSampleOrderByCode(String sampleOrderCode) { // TODO Auto-generated method stub String hql = "from SampleOrders s where s.sampleOrderCode='"+sampleOrderCode+"'"; Session session = baseDao.getSession(); return (SampleOrders) session.createQuery(hql).list().get(0); } }
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.cognitoidentity.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * A description of the identity. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/IdentityDescription" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class IdentityDescription implements Serializable, Cloneable, StructuredPojo { /** * <p> * A unique identifier in the format REGION:GUID. * </p> */ private String identityId; /** * <p> * The provider names. * </p> */ private java.util.List<String> logins; /** * <p> * Date on which the identity was created. * </p> */ private java.util.Date creationDate; /** * <p> * Date on which the identity was last modified. * </p> */ private java.util.Date lastModifiedDate; /** * <p> * A unique identifier in the format REGION:GUID. * </p> * * @param identityId * A unique identifier in the format REGION:GUID. */ public void setIdentityId(String identityId) { this.identityId = identityId; } /** * <p> * A unique identifier in the format REGION:GUID. * </p> * * @return A unique identifier in the format REGION:GUID. */ public String getIdentityId() { return this.identityId; } /** * <p> * A unique identifier in the format REGION:GUID. * </p> * * @param identityId * A unique identifier in the format REGION:GUID. * @return Returns a reference to this object so that method calls can be chained together. */ public IdentityDescription withIdentityId(String identityId) { setIdentityId(identityId); return this; } /** * <p> * The provider names. * </p> * * @return The provider names. */ public java.util.List<String> getLogins() { return logins; } /** * <p> * The provider names. * </p> * * @param logins * The provider names. */ public void setLogins(java.util.Collection<String> logins) { if (logins == null) { this.logins = null; return; } this.logins = new java.util.ArrayList<String>(logins); } /** * <p> * The provider names. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setLogins(java.util.Collection)} or {@link #withLogins(java.util.Collection)} if you want to override the * existing values. * </p> * * @param logins * The provider names. * @return Returns a reference to this object so that method calls can be chained together. */ public IdentityDescription withLogins(String... logins) { if (this.logins == null) { setLogins(new java.util.ArrayList<String>(logins.length)); } for (String ele : logins) { this.logins.add(ele); } return this; } /** * <p> * The provider names. * </p> * * @param logins * The provider names. * @return Returns a reference to this object so that method calls can be chained together. */ public IdentityDescription withLogins(java.util.Collection<String> logins) { setLogins(logins); return this; } /** * <p> * Date on which the identity was created. * </p> * * @param creationDate * Date on which the identity was created. */ public void setCreationDate(java.util.Date creationDate) { this.creationDate = creationDate; } /** * <p> * Date on which the identity was created. * </p> * * @return Date on which the identity was created. */ public java.util.Date getCreationDate() { return this.creationDate; } /** * <p> * Date on which the identity was created. * </p> * * @param creationDate * Date on which the identity was created. * @return Returns a reference to this object so that method calls can be chained together. */ public IdentityDescription withCreationDate(java.util.Date creationDate) { setCreationDate(creationDate); return this; } /** * <p> * Date on which the identity was last modified. * </p> * * @param lastModifiedDate * Date on which the identity was last modified. */ public void setLastModifiedDate(java.util.Date lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } /** * <p> * Date on which the identity was last modified. * </p> * * @return Date on which the identity was last modified. */ public java.util.Date getLastModifiedDate() { return this.lastModifiedDate; } /** * <p> * Date on which the identity was last modified. * </p> * * @param lastModifiedDate * Date on which the identity was last modified. * @return Returns a reference to this object so that method calls can be chained together. */ public IdentityDescription withLastModifiedDate(java.util.Date lastModifiedDate) { setLastModifiedDate(lastModifiedDate); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getIdentityId() != null) sb.append("IdentityId: ").append(getIdentityId()).append(","); if (getLogins() != null) sb.append("Logins: ").append(getLogins()).append(","); if (getCreationDate() != null) sb.append("CreationDate: ").append(getCreationDate()).append(","); if (getLastModifiedDate() != null) sb.append("LastModifiedDate: ").append(getLastModifiedDate()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof IdentityDescription == false) return false; IdentityDescription other = (IdentityDescription) obj; if (other.getIdentityId() == null ^ this.getIdentityId() == null) return false; if (other.getIdentityId() != null && other.getIdentityId().equals(this.getIdentityId()) == false) return false; if (other.getLogins() == null ^ this.getLogins() == null) return false; if (other.getLogins() != null && other.getLogins().equals(this.getLogins()) == false) return false; if (other.getCreationDate() == null ^ this.getCreationDate() == null) return false; if (other.getCreationDate() != null && other.getCreationDate().equals(this.getCreationDate()) == false) return false; if (other.getLastModifiedDate() == null ^ this.getLastModifiedDate() == null) return false; if (other.getLastModifiedDate() != null && other.getLastModifiedDate().equals(this.getLastModifiedDate()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getIdentityId() == null) ? 0 : getIdentityId().hashCode()); hashCode = prime * hashCode + ((getLogins() == null) ? 0 : getLogins().hashCode()); hashCode = prime * hashCode + ((getCreationDate() == null) ? 0 : getCreationDate().hashCode()); hashCode = prime * hashCode + ((getLastModifiedDate() == null) ? 0 : getLastModifiedDate().hashCode()); return hashCode; } @Override public IdentityDescription clone() { try { return (IdentityDescription) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.cognitoidentity.model.transform.IdentityDescriptionMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package com.example.einkaufsliste; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
/* * Copyright 2012 International Business Machines Corp. * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.batch.api.chunk.listener; /** * RetryReadListener intercepts retry processing for an ItemReader. */ public interface RetryReadListener { /** * The onRetryReadException method receives control when a retryable * exception is thrown from an ItemReader readItem method. This method * receives the exception as input. This method receives control in the same * checkpoint scope as the ItemReader. If this method throws a an exception, * the job ends in the FAILED state. * * @param ex * specifies the exception thrown by the item reader. * @throws Exception * is thrown if an error occurs. */ public void onRetryReadException(Exception ex) throws Exception; }
package advent2016; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; public class Day3 { private static final String NUMBER_DELIMETER = "\\s+"; public long task1(File file) throws IOException { return Files .lines(file.toPath()).map(line -> new Triangle(line)) .filter(triangle -> triangle.isReal()).count(); } public int task2(File file) throws IOException { List<List<Integer>> columns = new ArrayList<List<Integer>>(3); columns.add(new ArrayList<>()); columns.add(new ArrayList<>()); columns.add(new ArrayList<>()); Files.lines(file.toPath()).map(line -> line.trim().split(NUMBER_DELIMETER)).forEach( split -> { columns.get(0).add(Integer.valueOf(split[0].trim())); columns.get(1).add(Integer.valueOf(split[1].trim())); columns.get(2).add(Integer.valueOf(split[2].trim())); }); int triangleCount = 0; for (List<Integer> column : columns) { for (int i = 0; i < column.size(); i += 3) { if (new Triangle(column.get(i), column.get(i + 1), column.get(i + 2)).isReal()) { triangleCount++; } } } return triangleCount; } class Triangle { private final int x; private final int y; private final int z; public Triangle(String text) { String[] split = text.trim().split(NUMBER_DELIMETER); x = Integer.valueOf(split[0].trim()); y = Integer.valueOf(split[1].trim()); z = Integer.valueOf(split[2].trim()); } public Triangle(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public boolean isReal() { if (x + y > z && x + z > y && y + z > x) { return true; } return false; } } }
/* * * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package springfox.documentation.schema; import com.fasterxml.classmate.ResolvedType; import com.fasterxml.classmate.types.ResolvedArrayType; import com.fasterxml.classmate.types.ResolvedPrimitiveType; import springfox.documentation.service.AllowableValues; import springfox.documentation.spi.schema.EnumTypeDeterminer; import springfox.documentation.spi.schema.contexts.ModelContext; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import static java.util.Optional.*; import static springfox.documentation.schema.Collections.*; import static springfox.documentation.schema.Types.*; public class ResolvedTypes { private ResolvedTypes() { throw new UnsupportedOperationException(); } public static String simpleQualifiedTypeName(ResolvedType type) { if (type instanceof ResolvedPrimitiveType) { Type primitiveType = type.getErasedType(); return typeNameFor(primitiveType); } if (type instanceof ResolvedArrayType) { return typeNameFor(type.getArrayElementType().getErasedType()); } return type.getErasedType().getName(); } public static AllowableValues allowableValues(ResolvedType resolvedType) { if (isContainerType(resolvedType)) { List<ResolvedType> typeParameters = resolvedType.getTypeParameters(); if (typeParameters != null && typeParameters.size() == 1) { return Enums.allowableValues(typeParameters.get(0).getErasedType()); } } return Enums.allowableValues(resolvedType.getErasedType()); } public static Optional<String> resolvedTypeSignature(ResolvedType resolvedType) { return ofNullable(resolvedType).map(ResolvedType::getSignature); } public static Function<ResolvedType, ModelReference> modelRefFactory( final ModelContext parentContext, final EnumTypeDeterminer enumTypeDeterminer, final TypeNameExtractor typeNameExtractor, final Map<String, String> knownNames) { return new ModelReferenceProvider( typeNameExtractor, enumTypeDeterminer, parentContext, knownNames); } public static Function<ResolvedType, ModelReference> modelRefFactory( final ModelContext parentContext, final EnumTypeDeterminer enumTypeDeterminer, final TypeNameExtractor typeNameExtractor) { return new ModelReferenceProvider(typeNameExtractor, enumTypeDeterminer, parentContext, new HashMap<>()); } }
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow.lite; import static com.google.common.truth.Truth.assertThat; import java.nio.ByteBuffer; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Comparator; import java.util.Map; import java.util.PriorityQueue; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Smoke tests for {@link org.tensorflow.lite.Interpreter} agains MobileNet models. * * <p>Note that these tests are not intended to validate accuracy, rather, they serve to exercise * end-to-end inference, against a meaningful model, to tease out any stability/runtime issues. */ @RunWith(JUnit4.class) public final class InterpreterMobileNetTest { private static final ByteBuffer MOBILENET_FLOAT_MODEL_BUFFER = TestUtils.getTestFileAsBuffer( "tensorflow/lite/java/demo/app/src/main/assets/mobilenet_v1_1.0_224.tflite"); private static final ByteBuffer MOBILENET_QUANTIZED_MODEL_BUFFER = TestUtils.getTestFileAsBuffer( "tensorflow/lite/java/demo/app/src/main/assets/mobilenet_v1_1.0_224_quant.tflite"); @Test public void testMobileNet() { runMobileNetFloatTest(new Interpreter.Options()); } @Test public void testMobileNetMultithreaded() { runMobileNetFloatTest(new Interpreter.Options().setNumThreads(2)); } @Test public void testMobileNetEnhancedCpuKernels() { runMobileNetFloatTest(new Interpreter.Options().setUseXNNPACK(true)); } @Test public void testMobileNetEnhancedCpuKernelsMultithreaded() { runMobileNetFloatTest(new Interpreter.Options().setUseXNNPACK(true).setNumThreads(2)); } @Test public void testMobileNetQuantized() { runMobileNetQuantizedTest(new Interpreter.Options()); } @Test public void testMobileNetQuantizedMultithreaded() { runMobileNetQuantizedTest(new Interpreter.Options().setNumThreads(2)); } @Test public void testMobileNetQuantizedEnhancedCpu() { // The "enhanced CPU flag" should only impact float models, this is a sanity test to confirm. runMobileNetQuantizedTest(new Interpreter.Options().setUseXNNPACK(true)); } private static void runMobileNetFloatTest(Interpreter.Options options) { ByteBuffer img = TestUtils.getTestImageAsFloatByteBuffer( "tensorflow/lite/java/src/testdata/grace_hopper_224.jpg"); float[][] labels = new float[1][1001]; try (Interpreter interpreter = new Interpreter(MOBILENET_FLOAT_MODEL_BUFFER, options)) { interpreter.run(img, labels); assertThat(interpreter.getInputTensor(0).shape()).isEqualTo(new int[] {1, 224, 224, 3}); assertThat(interpreter.getOutputTensor(0).shape()).isEqualTo(new int[] {1, 1001}); } assertThat(labels[0]) .usingExactEquality() .containsNoneOf(new float[] {Float.NaN, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY}); // 653 == "military uniform" assertThat(getTopKLabels(labels, 3)).contains(653); } private static void runMobileNetQuantizedTest(Interpreter.Options options) { ByteBuffer img = TestUtils.getTestImageAsByteBuffer( "tensorflow/lite/java/src/testdata/grace_hopper_224.jpg"); byte[][] labels = new byte[1][1001]; try (Interpreter interpreter = new Interpreter(MOBILENET_QUANTIZED_MODEL_BUFFER, options)) { interpreter.run(img, labels); assertThat(interpreter.getInputTensor(0).shape()).isEqualTo(new int[] {1, 224, 224, 3}); assertThat(interpreter.getOutputTensor(0).shape()).isEqualTo(new int[] {1, 1001}); } // 653 == "military uniform" assertThat(getTopKLabels(labels, 3)).contains(653); } private static ArrayList<Integer> getTopKLabels(byte[][] byteLabels, int k) { float[][] labels = new float[1][1001]; for (int i = 0; i < byteLabels[0].length; ++i) { labels[0][i] = (byteLabels[0][i] & 0xff) / 255.0f; } return getTopKLabels(labels, k); } private static ArrayList<Integer> getTopKLabels(float[][] labels, int k) { PriorityQueue<Map.Entry<Integer, Float>> pq = new PriorityQueue<>( k, new Comparator<Map.Entry<Integer, Float>>() { @Override public int compare(Map.Entry<Integer, Float> o1, Map.Entry<Integer, Float> o2) { // Intentionally reversed to put high confidence at the head of the queue. return o1.getValue().compareTo(o2.getValue()) * -1; } }); for (int i = 0; i < labels[0].length; ++i) { pq.add(new AbstractMap.SimpleEntry<>(i, labels[0][i])); } final ArrayList<Integer> topKLabels = new ArrayList<>(); int topKLabelsSize = Math.min(pq.size(), k); for (int i = 0; i < topKLabelsSize; ++i) { topKLabels.add(pq.poll().getKey()); } return topKLabels; } }
/* * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2019-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yofish.gary.api.dto.req; import com.yofish.gary.api.page.PageQuery; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; /** * @author pqq * @version v1.0 * @date 2019年6月27日 10:00:00 * @work 权限查询请求req */ @ApiModel("权限查询请求req") @Setter @Getter public class PermissionQueryReqDTO extends PageQuery { private static final long serialVersionUID = -5366256300461044678L; @ApiModelProperty("权限id") private Long permissionId; @ApiModelProperty("权限名称") private String permissionName; }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.parameterserver.distributed.v2.util; import lombok.*; import lombok.extern.slf4j.Slf4j; import org.nd4j.common.primitives.Atomic; import org.nd4j.common.util.SerializationUtils; import org.nd4j.parameterserver.distributed.v2.enums.MeshBuildMode; import org.nd4j.parameterserver.distributed.enums.NodeStatus; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * This class provides methods for ephemeral mesh network management * * @author raver119@gmail.com */ @Slf4j public class MeshOrganizer implements Serializable { private static final long serialVersionUID = 1L; private MeshBuildMode buildMode = MeshBuildMode.MESH; // this value determines max number of direct downstream connections for any given node (affects root node as well) public static final int MAX_DOWNSTREAMS = 8; // max distance from root public static final int MAX_DEPTH = 5; // just shortcut to the root node of the tree @Getter(AccessLevel.PUBLIC) private Node rootNode = new Node(true); // SortedSet, with sort by number of downstreams private transient List<Node> sortedNodes = new ArrayList<>(); // flattened map of the tree, ID -> Node private transient Map<String, Node> nodeMap = new HashMap<>(); // this field is used private long version = 0L; public MeshOrganizer() { for (int e = 0; e < MAX_DOWNSTREAMS; e++) fillQueue.add(rootNode); } @Deprecated public MeshOrganizer(@NonNull MeshBuildMode mode) { this(); this.buildMode = mode; } // queue with future leafs protected transient Queue<Node> fillQueue = new LinkedTransferQueue<>(); public long getVersion() { return version; } /** * This method adds new node to the network * * PLEASE NOTE: Default port 40123 is used * @param ip */ public Node addNode(@NonNull String ip) { return addNode(ip, 40123); } /** * This methods adds new node to the network */ public Node addNode(@NonNull String ip, @NonNull int port) { val node = Node.builder() .id(ip) .port(port) .upstream(null) .build(); return this.addNode(node); } /** * This method returns absolutely independent copy of this Mesh * @return */ public MeshOrganizer clone() { val b = SerializationUtils.toByteArray(this); return SerializationUtils.fromByteArray(b); } /** * This method adds new node to the mesh * * @param node * @return */ public synchronized Node addNode(@NonNull Node node) { version++; if (buildMode == MeshBuildMode.MESH) { // :) val candidate = fillQueue.poll(); // adding node to the candidate candidate.addDownstreamNode(node); // adding this node for future connections for (int e = 0; e < MAX_DOWNSTREAMS; e++) fillQueue.add(node); sortedNodes.add(node); Collections.sort(sortedNodes); } else { rootNode.addDownstreamNode(node); } // after all we add this node to the flattened map, for future access nodeMap.put(node.getId(), node); return node; } /** * This method marks Node (specified by IP) as offline, and remaps its downstreams * * @param ip * @throws NoSuchElementException */ public void markNodeOffline(@NonNull String ip) throws NoSuchElementException { markNodeOffline(getNodeById(ip)); } /** * This method marks given Node as offline, remapping its downstreams * @param node */ public void markNodeOffline(@NonNull Node node) { synchronized (node) { node.status(NodeStatus.OFFLINE); for (val n : node.getDownstreamNodes()) remapNode(n); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MeshOrganizer that = (MeshOrganizer) o; val bm = buildMode == that.buildMode; val rn = Objects.equals(rootNode, that.rootNode); return bm && rn; } @Override public int hashCode() { return Objects.hash(buildMode, rootNode); } /** * This method reconnects given node to another node */ public void remapNode(@NonNull String ip) { remapNode(getNodeById(ip)); } /** * This method reconnects given node to another node */ public void remapNodeAndDownstreams(@NonNull String ip) { remapNodeAndDownstreams(getNodeById(ip)); } /** * This method remaps node and its downstreams somewhere * @param node */ public synchronized void remapNodeAndDownstreams(@NonNull Node node) { version++; node.setUpstreamNode(this.rootNode); for (val n: node.getDownstreamNodes()) { this.rootNode.addDownstreamNode(n); node.removeFromDownstreams(n); } } /** * This method reconnects given node to another node */ public synchronized void remapNode(@NonNull Node node) { version++; if (buildMode == MeshBuildMode.MESH) { node.getUpstreamNode().removeFromDownstreams(node); boolean m = false; for (val n : sortedNodes) { // we dont want to remap node to itself if (!Objects.equals(n, node) && n.status().equals(NodeStatus.ONLINE)) { n.addDownstreamNode(node); m = true; break; } } // if we were unable to find good enough node - we'll map this node to the rootNode if (!m) { rootNode.addDownstreamNode(node); } // i hope we won't deadlock here? :) synchronized (this) { Collections.sort(sortedNodes); } } else if (buildMode == MeshBuildMode.PLAIN) { // nothing to do here } } /** * This method removes node from tree */ public void removeNode() { // TODO: implement this one throw new UnsupportedOperationException(); } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { // default deserialization ois.defaultReadObject(); val desc = rootNode.getDescendantNodes(); nodeMap = new HashMap<>(); for (val d: desc) nodeMap.put(d.getId(), d); } /** * This method returns true, if node is known * @return */ public boolean isKnownNode(@NonNull String id) { if (rootNode.getId() == null) return false; if (rootNode.getId().equals(id)) return true; return nodeMap.containsKey(id); } /** * This method returns upstream connection for a given node */ public Node getUpstreamForNode(@NonNull String ip) throws NoSuchElementException { val node = getNodeById(ip); return node.getUpstreamNode(); } /** * This method returns downstream connections for a given node */ public Collection<Node> getDownstreamsForNode(@NonNull String ip) throws NoSuchElementException { val node = getNodeById(ip); return node.getDownstreamNodes(); } /** * This method returns total number of nodes below given one * @return */ public long numberOfDescendantsOfNode() { return rootNode.numberOfDescendants(); } /** * This method returns total number of nodes in this mesh * * PLESE NOTE: this method INCLUDES root node * @return */ public long totalNodes() { return rootNode.numberOfDescendants() + 1; } /** * This method returns size of flattened map of nodes. * Suited for tests. * * @return */ protected long flatSize() { return (long) nodeMap.size(); } /** * This method returns our mesh as collection of nodes * @return */ public Collection<Node> flatNodes() { return nodeMap.values(); } /** * This method returns Node representing given IP * @return */ public Node getNodeById(@NonNull String id) throws NoSuchElementException { if (id.equals(rootNode.getId())) return rootNode; val node = nodeMap.get(id); if (node == null) { log.info("Existing nodes: [{}]", this.flatNodes()); throw new NoSuchElementException(id); } return node; } /** * This class represents basic tree node */ @NoArgsConstructor @AllArgsConstructor @Builder public static class Node implements Serializable, Comparable<Node> { private static final long serialVersionUID = 1L; @Getter(AccessLevel.PUBLIC) @Setter(AccessLevel.PROTECTED) @Builder.Default private boolean rootNode = false; @Getter @Setter private String id; @Getter @Setter private int port; @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private Node upstream; @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private final List<Node> downstream = new CopyOnWriteArrayList<>(); private AtomicInteger position = new AtomicInteger(0); @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) @Builder.Default private Atomic<NodeStatus> status = new Atomic<>(NodeStatus.ONLINE); /** * This method returns current status of this node * @return */ public synchronized NodeStatus status() { return status.get(); } /** * This method ret * @param status */ protected synchronized void status(@NonNull NodeStatus status) { this.status.set(status); } /** * This method return candidate for new connection * * @param node * @return */ protected Node getNextCandidate(Node node) { // if there's no candidates - just connect to this node if (downstream.size() == 0) return this; if (node == null) return downstream.get(0); // TODO: we can get rid of flat scan here, but it's one-off step anyway... // we return next node after this node boolean b = false; for (val v: downstream) { if (b) return v; if (Objects.equals(node, v)) b = true; } return null; } protected Node(boolean rootNode) { this.rootNode = rootNode; } /** * This method adds downstream node to the list of connections * @param node * @return */ public Node addDownstreamNode(@NonNull Node node) { this.downstream.add(node); node.setUpstreamNode(this); return node; } /** * This method pushes node to the bottom of this node downstream * @param node * @return */ protected Node pushDownstreamNode(@NonNull Node node) { if (isRootNode()) { if (downstream.size() == 0) { return addDownstreamNode(node); } else { // we should find first not full sub-branch for (val d: downstream) if (d.numberOfDescendants() < MeshOrganizer.MAX_DEPTH * MeshOrganizer.MAX_DOWNSTREAMS) return d.pushDownstreamNode(node); // if we're here - we'll have to add new branch to the root return addDownstreamNode(node); } } else { val distance = distanceFromRoot(); for (val d: downstream) if (d.numberOfDescendants() < MeshOrganizer.MAX_DOWNSTREAMS * (MeshOrganizer.MAX_DEPTH - distance)) return d.pushDownstreamNode(node); return addDownstreamNode(node); } } /** * This method allows to set master node for this node * @param node * @return */ protected Node setUpstreamNode(@NonNull Node node) { this.upstream = node; return node; } /** * This method returns the node this one it connected to * @return */ public Node getUpstreamNode() { return upstream; } /** * This method returns number of downstream nodes connected to this node * @return */ public long numberOfDescendants() { val cnt = new AtomicLong(downstream.size()); for (val n: downstream) cnt.addAndGet(n.numberOfDescendants()); return cnt.get(); } /** * This method returns number of nodes that has direct connection for this node * @return */ public long numberOfDownstreams() { return downstream.size(); } /** * This method returns collection of nodes that have direct connection to this node * @return */ public Collection<Node> getDownstreamNodes() { return downstream; } /** * This method returns all nodes * @return */ public Collection<Node> getDescendantNodes() { val result = new ArrayList<Node>(getDownstreamNodes()); for (val n:downstream) result.addAll(n.getDescendantNodes()); return result; } /** * This method returns number of hops between * @return */ public int distanceFromRoot() { if (upstream.isRootNode()) return 1; else return upstream.distanceFromRoot() + 1; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; val rn = this.upstream == null ? "root" : this.upstream.getId(); val on = node.upstream == null ? "root" : node.upstream.getId(); return rootNode == node.rootNode && port == node.port && Objects.equals(id, node.id) && Objects.equals(downstream, node.downstream) && Objects.equals(status, node.status) && Objects.equals(rn, on); } @Override public int hashCode() { return Objects.hash(upstream == null ? "root" : upstream.getId(), rootNode, id, port, downstream, status); } @Override public String toString() { val builder = new StringBuilder(); if (downstream == null || downstream.size() == 0) builder.append("none"); else { for (val n: downstream) { builder.append("[").append(n.getId()).append("], "); } } // downstreams: [" + builder.toString() +"]; ] // upstreamId: [" + upstreamId + "]; val strId = id == null ? "null" : id; val upstreamId = upstream == null ? "none" : upstream.getId(); return "[ Id: ["+ strId +"]; ]"; } /** * This method remove all downstreams for a given node */ public void truncateDownstreams() { downstream.clear(); } /** * This method removes * @param node */ public synchronized void removeFromDownstreams(@NonNull Node node) { val r = downstream.remove(node); if (!r) throw new NoSuchElementException(node.getId()); } @Override public int compareTo(@NonNull Node o) { return Long.compare(this.numberOfDownstreams(), o.numberOfDownstreams()); } } }
/* * Kores-SourceWriter - Translates Kores Structure to Java Source <https://github.com/JonathanxD/Kores-SourceWriter> * * The MIT License (MIT) * * Copyright (c) 2021 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <jonathan.scripter@programmer.net> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.koresframework.kores.source.test; import com.koresframework.kores.base.TypeDeclaration; import com.koresframework.kores.test.InnerClassTest_; import org.junit.Test; public class InnerTest { @Test public void innerTest() { TypeDeclaration $ = InnerClassTest_.$(); SourceTest test = CommonSourceTest.test(this.getClass(), $); test.expect("package test;\n" + "\n" + "public class InnerClass {\n" + "\n" + " protected String field = \"XSD\";\n" + "\n" + " public InnerClass() {\n" + " new Inner().call();\n" + " }\n" + "\n" + " protected InnerClass(String str) {\n" + " System.out.println(str);\n" + " }\n" + "\n" + " public void mm() {\n" + " System.out.println(\"A\");\n" + " }\n" + "\n" + " public class Inner {\n" + "\n" + " public InnerClass a = new InnerClass(\"Hello\");\n" + "\n" + " protected String call() {\n" + " System.out.println(InnerClass.this.field);\n" + " InnerClass.this.mm();\n" + " return \"A\";\n" + " }\n" + " }\n" + "\n" + "}\n"); } }
package io.fixprotocol.orchestra.client.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * element metadata including pedigree */ @ApiModel(description = "element metadata including pedigree") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-04-23T17:52:38.213Z") public class EntityAttributes { @JsonProperty("added") private String added = null; @JsonProperty("addedEP") private Integer addedEP = null; /** * Gets or Sets changeType */ public enum ChangeTypeEnum { EDITORIAL("Editorial"), DEFINITIONAL("Definitional"); private String value; ChangeTypeEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static ChangeTypeEnum fromValue(String text) { for (ChangeTypeEnum b : ChangeTypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } } @JsonProperty("changeType") private ChangeTypeEnum changeType = null; @JsonProperty("deprecated") private String deprecated = null; @JsonProperty("deprecatedEP") private Integer deprecatedEP = null; @JsonProperty("issue") private String issue = null; @JsonProperty("lastModified") private String lastModified = null; @JsonProperty("replaced") private String replaced = null; @JsonProperty("replacedEP") private Integer replacedEP = null; @JsonProperty("replacedByField") private Integer replacedByField = null; /** * Gets or Sets supported */ public enum SupportedEnum { SUPPORTED("supported"), FORBIDDEN("forbidden"), IGNORED("ignored"); private String value; SupportedEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static SupportedEnum fromValue(String text) { for (SupportedEnum b : SupportedEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } } @JsonProperty("supported") private SupportedEnum supported = SupportedEnum.SUPPORTED; @JsonProperty("updated") private String updated = null; @JsonProperty("updatedEP") private Integer updatedEP = null; public EntityAttributes added(String added) { this.added = added; return this; } /** * Get added * @return added **/ @ApiModelProperty(value = "") public String getAdded() { return added; } public void setAdded(String added) { this.added = added; } public EntityAttributes addedEP(Integer addedEP) { this.addedEP = addedEP; return this; } /** * Get addedEP * @return addedEP **/ @ApiModelProperty(value = "") public Integer getAddedEP() { return addedEP; } public void setAddedEP(Integer addedEP) { this.addedEP = addedEP; } public EntityAttributes changeType(ChangeTypeEnum changeType) { this.changeType = changeType; return this; } /** * Get changeType * @return changeType **/ @ApiModelProperty(value = "") public ChangeTypeEnum getChangeType() { return changeType; } public void setChangeType(ChangeTypeEnum changeType) { this.changeType = changeType; } public EntityAttributes deprecated(String deprecated) { this.deprecated = deprecated; return this; } /** * Get deprecated * @return deprecated **/ @ApiModelProperty(value = "") public String getDeprecated() { return deprecated; } public void setDeprecated(String deprecated) { this.deprecated = deprecated; } public EntityAttributes deprecatedEP(Integer deprecatedEP) { this.deprecatedEP = deprecatedEP; return this; } /** * Get deprecatedEP * @return deprecatedEP **/ @ApiModelProperty(value = "") public Integer getDeprecatedEP() { return deprecatedEP; } public void setDeprecatedEP(Integer deprecatedEP) { this.deprecatedEP = deprecatedEP; } public EntityAttributes issue(String issue) { this.issue = issue; return this; } /** * Get issue * @return issue **/ @ApiModelProperty(value = "") public String getIssue() { return issue; } public void setIssue(String issue) { this.issue = issue; } public EntityAttributes lastModified(String lastModified) { this.lastModified = lastModified; return this; } /** * Get lastModified * @return lastModified **/ @ApiModelProperty(value = "") public String getLastModified() { return lastModified; } public void setLastModified(String lastModified) { this.lastModified = lastModified; } public EntityAttributes replaced(String replaced) { this.replaced = replaced; return this; } /** * Get replaced * @return replaced **/ @ApiModelProperty(value = "") public String getReplaced() { return replaced; } public void setReplaced(String replaced) { this.replaced = replaced; } public EntityAttributes replacedEP(Integer replacedEP) { this.replacedEP = replacedEP; return this; } /** * Get replacedEP * @return replacedEP **/ @ApiModelProperty(value = "") public Integer getReplacedEP() { return replacedEP; } public void setReplacedEP(Integer replacedEP) { this.replacedEP = replacedEP; } public EntityAttributes replacedByField(Integer replacedByField) { this.replacedByField = replacedByField; return this; } /** * Get replacedByField * @return replacedByField **/ @ApiModelProperty(value = "") public Integer getReplacedByField() { return replacedByField; } public void setReplacedByField(Integer replacedByField) { this.replacedByField = replacedByField; } public EntityAttributes supported(SupportedEnum supported) { this.supported = supported; return this; } /** * Get supported * @return supported **/ @ApiModelProperty(value = "") public SupportedEnum getSupported() { return supported; } public void setSupported(SupportedEnum supported) { this.supported = supported; } public EntityAttributes updated(String updated) { this.updated = updated; return this; } /** * Get updated * @return updated **/ @ApiModelProperty(value = "") public String getUpdated() { return updated; } public void setUpdated(String updated) { this.updated = updated; } public EntityAttributes updatedEP(Integer updatedEP) { this.updatedEP = updatedEP; return this; } /** * Get updatedEP * @return updatedEP **/ @ApiModelProperty(value = "") public Integer getUpdatedEP() { return updatedEP; } public void setUpdatedEP(Integer updatedEP) { this.updatedEP = updatedEP; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EntityAttributes entityAttributes = (EntityAttributes) o; return Objects.equals(this.added, entityAttributes.added) && Objects.equals(this.addedEP, entityAttributes.addedEP) && Objects.equals(this.changeType, entityAttributes.changeType) && Objects.equals(this.deprecated, entityAttributes.deprecated) && Objects.equals(this.deprecatedEP, entityAttributes.deprecatedEP) && Objects.equals(this.issue, entityAttributes.issue) && Objects.equals(this.lastModified, entityAttributes.lastModified) && Objects.equals(this.replaced, entityAttributes.replaced) && Objects.equals(this.replacedEP, entityAttributes.replacedEP) && Objects.equals(this.replacedByField, entityAttributes.replacedByField) && Objects.equals(this.supported, entityAttributes.supported) && Objects.equals(this.updated, entityAttributes.updated) && Objects.equals(this.updatedEP, entityAttributes.updatedEP); } @Override public int hashCode() { return Objects.hash(added, addedEP, changeType, deprecated, deprecatedEP, issue, lastModified, replaced, replacedEP, replacedByField, supported, updated, updatedEP); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class EntityAttributes {\n"); sb.append(" added: ").append(toIndentedString(added)).append("\n"); sb.append(" addedEP: ").append(toIndentedString(addedEP)).append("\n"); sb.append(" changeType: ").append(toIndentedString(changeType)).append("\n"); sb.append(" deprecated: ").append(toIndentedString(deprecated)).append("\n"); sb.append(" deprecatedEP: ").append(toIndentedString(deprecatedEP)).append("\n"); sb.append(" issue: ").append(toIndentedString(issue)).append("\n"); sb.append(" lastModified: ").append(toIndentedString(lastModified)).append("\n"); sb.append(" replaced: ").append(toIndentedString(replaced)).append("\n"); sb.append(" replacedEP: ").append(toIndentedString(replacedEP)).append("\n"); sb.append(" replacedByField: ").append(toIndentedString(replacedByField)).append("\n"); sb.append(" supported: ").append(toIndentedString(supported)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append(" updatedEP: ").append(toIndentedString(updatedEP)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
/* * Copyright [2020] [MaxKey of copyright http://www.maxkey.top] * * 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.maxkey.autoconfigure; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.maxkey.authn.support.socialsignon.service.JdbcSocialsAssociateService; import org.maxkey.authn.support.socialsignon.service.SocialSignOnProvider; import org.maxkey.authn.support.socialsignon.service.SocialSignOnProviderService; import org.maxkey.constants.ConstantsProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcTemplate; @Configuration @ComponentScan(basePackages = { "org.maxkey.authn.support.socialsignon" }) @PropertySource(ConstantsProperties.maxKeyPropertySource) public class SocialSignOnAutoConfiguration implements InitializingBean { private static final Logger _logger = LoggerFactory.getLogger(SocialSignOnAutoConfiguration.class); @Bean(name = "socialSignOnProviderService") @ConditionalOnClass(SocialSignOnProvider.class) public SocialSignOnProviderService socialSignOnProviderService() throws IOException { SocialSignOnProviderService socialSignOnProviderService = new SocialSignOnProviderService(); Resource resource = new ClassPathResource( ConstantsProperties.classPathResource(ConstantsProperties.classPathResource(ConstantsProperties.maxKeyPropertySource))); Properties properties = new Properties(); properties.load(resource.getInputStream()); String [] providerList =properties.get("config.login.socialsignon.providers").toString().split(","); List<SocialSignOnProvider> socialSignOnProviderList = new ArrayList<SocialSignOnProvider>(); for(String provider : providerList) { String providerName = properties.getProperty("config.socialsignon."+provider+".provider.name"); String icon=properties.getProperty("config.socialsignon."+provider+".icon"); String clientId=properties.getProperty("config.socialsignon."+provider+".client.id"); String clientSecret=properties.getProperty("config.socialsignon."+provider+".client.secret"); String sortOrder = properties.getProperty("config.socialsignon."+provider+".sortorder"); SocialSignOnProvider socialSignOnProvider = new SocialSignOnProvider(); socialSignOnProvider.setProvider(provider); socialSignOnProvider.setProviderName(providerName); socialSignOnProvider.setIcon(icon); socialSignOnProvider.setClientId(clientId); socialSignOnProvider.setClientSecret(clientSecret); socialSignOnProvider.setSortOrder(Integer.valueOf(sortOrder)); _logger.debug("socialSignOnProvider " + socialSignOnProvider.getProvider() + "(" + socialSignOnProvider.getProviderName()+")"); _logger.trace("socialSignOnProvider " + socialSignOnProvider); socialSignOnProviderList.add(socialSignOnProvider); } socialSignOnProviderService.setSocialSignOnProviders(socialSignOnProviderList); _logger.debug("SocialSignOnProviderService inited."); return socialSignOnProviderService; } @Bean(name = "socialsAssociateService") public JdbcSocialsAssociateService socialsAssociateService( JdbcTemplate jdbcTemplate) { JdbcSocialsAssociateService socialsAssociateService = new JdbcSocialsAssociateService(jdbcTemplate); _logger.debug("JdbcSocialsAssociateService inited."); return socialsAssociateService; } @Override public void afterPropertiesSet() throws Exception { // TODO Auto-generated method stub } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|pdfbox operator|. name|contentstream operator|. name|operator package|; end_package begin_class specifier|public specifier|final class|class name|OperatorName block|{ comment|// non stroking color specifier|public specifier|static specifier|final name|String name|NON_STROKING_COLOR init|= literal|"sc" decl_stmt|; specifier|public specifier|static specifier|final name|String name|NON_STROKING_COLOR_N init|= literal|"scn" decl_stmt|; specifier|public specifier|static specifier|final name|String name|NON_STROKING_RGB init|= literal|"rg" decl_stmt|; specifier|public specifier|static specifier|final name|String name|NON_STROKING_GRAY init|= literal|"g" decl_stmt|; specifier|public specifier|static specifier|final name|String name|NON_STROKING_CMYK init|= literal|"k" decl_stmt|; specifier|public specifier|static specifier|final name|String name|NON_STROKING_COLORSPACE init|= literal|"cs" decl_stmt|; comment|// stroking color specifier|public specifier|static specifier|final name|String name|STROKING_COLOR init|= literal|"SC" decl_stmt|; specifier|public specifier|static specifier|final name|String name|STROKING_COLOR_N init|= literal|"SCN" decl_stmt|; specifier|public specifier|static specifier|final name|String name|STROKING_COLOR_RGB init|= literal|"RG" decl_stmt|; specifier|public specifier|static specifier|final name|String name|STROKING_COLOR_GRAY init|= literal|"G" decl_stmt|; specifier|public specifier|static specifier|final name|String name|STROKING_COLOR_CMYK init|= literal|"K" decl_stmt|; specifier|public specifier|static specifier|final name|String name|STROKING_COLORSPACE init|= literal|"CS" decl_stmt|; comment|// marked content specifier|public specifier|static specifier|final name|String name|BEGIN_MARKED_CONTENT_SEQ init|= literal|"BDC" decl_stmt|; specifier|public specifier|static specifier|final name|String name|BEGIN_MARKED_CONTENT init|= literal|"BMC" decl_stmt|; specifier|public specifier|static specifier|final name|String name|END_MARKED_CONTENT init|= literal|"EMC" decl_stmt|; specifier|public specifier|static specifier|final name|String name|MARKED_CONTENT_POINT_WITH_PROPS init|= literal|"DP" decl_stmt|; specifier|public specifier|static specifier|final name|String name|MARKED_CONTENT_POINT init|= literal|"MP" decl_stmt|; specifier|public specifier|static specifier|final name|String name|DRAW_OBJECT init|= literal|"Do" decl_stmt|; comment|// state specifier|public specifier|static specifier|final name|String name|CONCAT init|= literal|"cm" decl_stmt|; specifier|public specifier|static specifier|final name|String name|RESTORE init|= literal|"Q" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SAVE init|= literal|"q" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_FLATNESS init|= literal|"i" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_GRAPHICS_STATE_PARAMS init|= literal|"gs" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_LINE_CAPSTYLE init|= literal|"J" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_LINE_DASHPATTERN init|= literal|"d" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_LINE_JOINSTYLE init|= literal|"j" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_LINE_MITERLIMIT init|= literal|"M" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_LINE_WIDTH init|= literal|"w" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_MATRIX init|= literal|"Tm" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_RENDERINGINTENT init|= literal|"ri" decl_stmt|; comment|// graphics specifier|public specifier|static specifier|final name|String name|APPEND_RECT init|= literal|"re" decl_stmt|; specifier|public specifier|static specifier|final name|String name|BEGIN_INLINE_IMAGE init|= literal|"BI" decl_stmt|; specifier|public specifier|static specifier|final name|String name|BEGIN_INLINE_IMAGE_DATA init|= literal|"ID" decl_stmt|; specifier|public specifier|static specifier|final name|String name|END_INLINE_IMAGE init|= literal|"EI" decl_stmt|; specifier|public specifier|static specifier|final name|String name|CLIP_EVEN_ODD init|= literal|"W*" decl_stmt|; specifier|public specifier|static specifier|final name|String name|CLIP_NON_ZERO init|= literal|"W" decl_stmt|; specifier|public specifier|static specifier|final name|String name|CLOSE_AND_STROKE init|= literal|"s" decl_stmt|; specifier|public specifier|static specifier|final name|String name|CLOSE_FILL_EVEN_ODD_AND_STROKE init|= literal|"b*" decl_stmt|; specifier|public specifier|static specifier|final name|String name|CLOSE_FILL_NON_ZERO_AND_STROKE init|= literal|"b" decl_stmt|; specifier|public specifier|static specifier|final name|String name|CLOSE_PATH init|= literal|"h" decl_stmt|; specifier|public specifier|static specifier|final name|String name|CURVE_TO init|= literal|"c" decl_stmt|; specifier|public specifier|static specifier|final name|String name|CURVE_TO_REPLICATE_FINAL_POINT init|= literal|"y" decl_stmt|; specifier|public specifier|static specifier|final name|String name|CURVE_TO_REPLICATE_INITIAL_POINT init|= literal|"v" decl_stmt|; specifier|public specifier|static specifier|final name|String name|ENDPATH init|= literal|"n" decl_stmt|; specifier|public specifier|static specifier|final name|String name|FILL_EVEN_ODD_AND_STROKE init|= literal|"B*" decl_stmt|; specifier|public specifier|static specifier|final name|String name|FILL_EVEN_ODD init|= literal|"f*" decl_stmt|; specifier|public specifier|static specifier|final name|String name|FILL_NON_ZERO_AND_STROKE init|= literal|"B" decl_stmt|; specifier|public specifier|static specifier|final name|String name|FILL_NON_ZERO init|= literal|"f" decl_stmt|; specifier|public specifier|static specifier|final name|String name|LEGACY_FILL_NON_ZERO init|= literal|"F" decl_stmt|; specifier|public specifier|static specifier|final name|String name|LINE_TO init|= literal|"l" decl_stmt|; specifier|public specifier|static specifier|final name|String name|MOVE_TO init|= literal|"m" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SHADING_FILL init|= literal|"sh" decl_stmt|; specifier|public specifier|static specifier|final name|String name|STROKE_PATH init|= literal|"S" decl_stmt|; comment|// text specifier|public specifier|static specifier|final name|String name|BEGIN_TEXT init|= literal|"BT" decl_stmt|; specifier|public specifier|static specifier|final name|String name|END_TEXT init|= literal|"ET" decl_stmt|; specifier|public specifier|static specifier|final name|String name|MOVE_TEXT init|= literal|"Td" decl_stmt|; specifier|public specifier|static specifier|final name|String name|MOVE_TEXT_SET_LEADING init|= literal|"TD" decl_stmt|; specifier|public specifier|static specifier|final name|String name|NEXT_LINE init|= literal|"T*" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_CHAR_SPACING init|= literal|"Tc" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_FONT_AND_SIZE init|= literal|"Tf" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_TEXT_HORIZONTAL_SCALING init|= literal|"Tz" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_TEXT_LEADING init|= literal|"TL" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_TEXT_RENDERINGMODE init|= literal|"Tr" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_TEXT_RISE init|= literal|"Ts" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SET_WORD_SPACING init|= literal|"Tw" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SHOW_TEXT init|= literal|"Tj" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SHOW_TEXT_ADJUSTED init|= literal|"TJ" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SHOW_TEXT_LINE init|= literal|"'" decl_stmt|; specifier|public specifier|static specifier|final name|String name|SHOW_TEXT_LINE_AND_SPACE init|= literal|"\"" decl_stmt|; comment|// type3 font specifier|public specifier|static specifier|final name|String name|TYPE3_D0 init|= literal|"d0" decl_stmt|; specifier|public specifier|static specifier|final name|String name|TYPE3_D1 init|= literal|"d1" decl_stmt|; comment|// compatibility section specifier|public specifier|static specifier|final name|String name|BEGIN_COMPATIBILITY_SECTION init|= literal|"BX" decl_stmt|; specifier|public specifier|static specifier|final name|String name|END_COMPATIBILITY_SECTION init|= literal|"EX" decl_stmt|; comment|/** * private constructor */ specifier|private name|OperatorName parameter_list|() block|{ } block|} end_class end_unit
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2020 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.erd.editor; import org.eclipse.draw2d.LightweightSystem; import org.eclipse.draw2d.MarginBorder; import org.eclipse.draw2d.Viewport; import org.eclipse.draw2d.parts.ScrollableThumbnail; import org.eclipse.draw2d.parts.Thumbnail; import org.eclipse.gef.LayerConstants; import org.eclipse.gef.editparts.ScalableFreeformRootEditPart; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.part.Page; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; /** * This is a sample implementation of an outline page showing an * overview of a graphical editor. * * @author Gunnar Wagenknecht */ public class ERDOutlinePage extends Page implements IContentOutlinePage { /** * the control of the overview */ private Canvas overview; /** * the root edit part */ private ScalableFreeformRootEditPart rootEditPart; /** * the thumbnail */ private Thumbnail thumbnail; /** * Creates a new ERDOutlinePage instance. * * @param rootEditPart the root edit part to show the overview from */ public ERDOutlinePage(ScalableFreeformRootEditPart rootEditPart) { super(); this.rootEditPart = rootEditPart; } @Override public void addSelectionChangedListener(ISelectionChangedListener listener) { } /* (non-Javadoc) * @see org.eclipse.ui.part.IPage#createControl(org.eclipse.swt.widgets.Composite) */ @Override public void createControl(Composite parent) { // create canvas and lws overview = new Canvas(parent, SWT.NONE); LightweightSystem lws = new LightweightSystem(overview); // create thumbnail thumbnail = new ScrollableThumbnail((Viewport) rootEditPart.getFigure()); thumbnail.setBorder(new MarginBorder(3)); thumbnail.setSource( rootEditPart.getLayer(LayerConstants.PRINTABLE_LAYERS)); lws.setContents(thumbnail); } /* (non-Javadoc) * @see org.eclipse.ui.part.IPage#dispose() */ @Override public void dispose() { if (null != thumbnail) thumbnail.deactivate(); super.dispose(); } /* (non-Javadoc) * @see org.eclipse.ui.part.IPage#getControl() */ @Override public Control getControl() { return overview; } @Override public ISelection getSelection() { return StructuredSelection.EMPTY; } @Override public void removeSelectionChangedListener(ISelectionChangedListener listener) { } @Override public void setFocus() { if (getControl() != null) getControl().setFocus(); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(org.eclipse.jface.viewers.ISelection) */ @Override public void setSelection(ISelection selection) { } }
/** * Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2006-2016 * * 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.glite.security.voms.admin.persistence.dao.generic; import org.glite.security.voms.admin.persistence.model.VOMSUser; public interface UserDAO extends NamedEntityDAO<VOMSUser, Long> { }
// // ======================================================================== // Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under // the terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0 // // This Source Code may also be made available under the following // Secondary Licenses when the conditions for such availability set // forth in the Eclipse Public License, v. 2.0 are satisfied: // the Apache License v2.0 which is available at // https://www.apache.org/licenses/LICENSE-2.0 // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.http; import java.util.ArrayList; import java.util.List; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; public class QuotedQualityCSVTest { @Test public void test7231Sec532Example1() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" audio/*; q=0.2, audio/basic"); assertThat(values, Matchers.contains("audio/basic", "audio/*")); } @Test public void test7231Sec532Example2() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("text/plain; q=0.5, text/html,"); values.addValue("text/x-dvi; q=0.8, text/x-c"); assertThat(values, Matchers.contains("text/html", "text/x-c", "text/x-dvi", "text/plain")); } @Test public void test7231Sec532Example3() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("text/*, text/plain, text/plain;format=flowed, */*"); // Note this sort is only on quality and not the most specific type as per 5.3.2 assertThat(values, Matchers.contains("text/*", "text/plain", "text/plain;format=flowed", "*/*")); } @Test public void test7231532Example3MostSpecific() { QuotedQualityCSV values = new QuotedQualityCSV(QuotedQualityCSV.MOST_SPECIFIC_MIME_ORDERING); values.addValue("text/*, text/plain, text/plain;format=flowed, */*"); assertThat(values, Matchers.contains("text/plain;format=flowed", "text/plain", "text/*", "*/*")); } @Test public void test7231Sec532Example4() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("text/*;q=0.3, text/html;q=0.7, text/html;level=1,"); values.addValue("text/html;level=2;q=0.4, */*;q=0.5"); assertThat(values, Matchers.contains( "text/html;level=1", "text/html", "*/*", "text/html;level=2", "text/*" )); } @Test public void test7231Sec534Example1() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("compress, gzip"); values.addValue(""); values.addValue("*"); values.addValue("compress;q=0.5, gzip;q=1.0"); values.addValue("gzip;q=1.0, identity; q=0.5, *;q=0"); assertThat(values, Matchers.contains( "compress", "gzip", "*", "gzip", "gzip", "compress", "identity" )); } @Test public void testOWS() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" value 0.5 ; p = v ; q =0.5 , value 1.0 "); assertThat(values, Matchers.contains( "value 1.0", "value 0.5;p=v")); } @Test public void testEmpty() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(",aaaa, , bbbb ,,cccc,"); assertThat(values, Matchers.contains( "aaaa", "bbbb", "cccc")); } @Test public void testQuoted() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" value 0.5 ; p = \"v ; q = \\\"0.5\\\" , value 1.0 \" "); assertThat(values, Matchers.contains( "value 0.5;p=\"v ; q = \\\"0.5\\\" , value 1.0 \"")); } @Test public void testOpenQuote() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("value;p=\"v"); assertThat(values, Matchers.contains( "value;p=\"v")); } @Test public void testQuotedQuality() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" value 0.5 ; p = v ; q = \"0.5\" , value 1.0 "); assertThat(values, Matchers.contains( "value 1.0", "value 0.5;p=v")); } @Test public void testBadQuality() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("value0.5;p=v;q=0.5,value1.0,valueBad;q=X"); assertThat(values, Matchers.contains( "value1.0", "value0.5;p=v")); } @Test public void testBad() { QuotedQualityCSV values = new QuotedQualityCSV(); // None of these should throw exceptions values.addValue(null); values.addValue(""); values.addValue(";"); values.addValue("="); values.addValue(","); values.addValue(";;"); values.addValue(";="); values.addValue(";,"); values.addValue("=;"); values.addValue("=="); values.addValue("=,"); values.addValue(",;"); values.addValue(",="); values.addValue(",,"); values.addValue(";;;"); values.addValue(";;="); values.addValue(";;,"); values.addValue(";=;"); values.addValue(";=="); values.addValue(";=,"); values.addValue(";,;"); values.addValue(";,="); values.addValue(";,,"); values.addValue("=;;"); values.addValue("=;="); values.addValue("=;,"); values.addValue("==;"); values.addValue("==="); values.addValue("==,"); values.addValue("=,;"); values.addValue("=,="); values.addValue("=,,"); values.addValue(",;;"); values.addValue(",;="); values.addValue(",;,"); values.addValue(",=;"); values.addValue(",=="); values.addValue(",=,"); values.addValue(",,;"); values.addValue(",,="); values.addValue(",,,"); values.addValue("x;=1"); values.addValue("=1"); values.addValue("q=x"); values.addValue("q=0"); values.addValue("q="); values.addValue("q=,"); values.addValue("q=;"); } private static final String[] preferBrotli = {"br", "gzip"}; private static final String[] preferGzip = {"gzip", "br"}; private static final String[] noFormats = {}; @Test public void testFirefoxContentEncodingWithBrotliPreference() { QuotedQualityCSV values = new QuotedQualityCSV(preferBrotli); values.addValue("gzip, deflate, br"); assertThat(values, contains("br", "gzip", "deflate")); } @Test public void testFirefoxContentEncodingWithGzipPreference() { QuotedQualityCSV values = new QuotedQualityCSV(preferGzip); values.addValue("gzip, deflate, br"); assertThat(values, contains("gzip", "br", "deflate")); } @Test public void testFirefoxContentEncodingWithNoPreference() { QuotedQualityCSV values = new QuotedQualityCSV(noFormats); values.addValue("gzip, deflate, br"); assertThat(values, contains("gzip", "deflate", "br")); } @Test public void testChromeContentEncodingWithBrotliPreference() { QuotedQualityCSV values = new QuotedQualityCSV(preferBrotli); values.addValue("gzip, deflate, sdch, br"); assertThat(values, contains("br", "gzip", "deflate", "sdch")); } @Test public void testComplexEncodingWithGzipPreference() { QuotedQualityCSV values = new QuotedQualityCSV(preferGzip); values.addValue("gzip;q=0.9, identity;q=0.1, *;q=0.01, deflate;q=0.9, sdch;q=0.7, br;q=0.9"); assertThat(values, contains("gzip", "br", "deflate", "sdch", "identity", "*")); } @Test public void testComplexEncodingWithBrotliPreference() { QuotedQualityCSV values = new QuotedQualityCSV(preferBrotli); values.addValue("gzip;q=0.9, identity;q=0.1, *;q=0, deflate;q=0.9, sdch;q=0.7, br;q=0.99"); assertThat(values, contains("br", "gzip", "deflate", "sdch", "identity")); } @Test public void testStarEncodingWithGzipPreference() { QuotedQualityCSV values = new QuotedQualityCSV(preferGzip); values.addValue("br, *"); assertThat(values, contains("*", "br")); } @Test public void testStarEncodingWithBrotliPreference() { QuotedQualityCSV values = new QuotedQualityCSV(preferBrotli); values.addValue("gzip, *"); assertThat(values, contains("*", "gzip")); } @Test public void testSameQuality() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("one;q=0.5,two;q=0.5,three;q=0.5"); assertThat(values.getValues(), Matchers.contains("one", "two", "three")); } @Test public void testNoQuality() { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("one,two;,three;x=y"); assertThat(values.getValues(), Matchers.contains("one", "two", "three;x=y")); } @Test public void testQuality() { List<String> results = new ArrayList<>(); QuotedQualityCSV values = new QuotedQualityCSV() { @Override protected void parsedValue(StringBuffer buffer) { results.add("parsedValue: " + buffer.toString()); super.parsedValue(buffer); } @Override protected void parsedParam(StringBuffer buffer, int valueLength, int paramName, int paramValue) { String param = buffer.substring(paramName, buffer.length()); results.add("parsedParam: " + param); super.parsedParam(buffer, valueLength, paramName, paramValue); } }; // The provided string is not legal according to some RFCs ( not a token because of = and not a parameter because not preceded by ; ) // The string is legal according to RFC7239 which allows for just parameters (called forwarded-pairs) values.addValue("p=0.5,q=0.5"); // The QuotedCSV implementation is lenient and adopts the later interpretation and thus sees q=0.5 and p=0.5 both as parameters assertThat(results, contains("parsedValue: ", "parsedParam: p=0.5", "parsedValue: ", "parsedParam: q=0.5")); // However the QuotedQualityCSV only handles the q parameter and that is consumed from the parameter string. assertThat(values, contains("p=0.5", "")); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2018.02.27 at 12:33:13 PM MSK // package net.opengis.sampling._2; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import net.opengis.gml.v_3_2_1.AbstractFeatureType; import net.opengis.gml.v_3_2_1.FeaturePropertyType; import net.opengis.gml.v_3_2_1.ReferenceType; import net.opengis.om._2.NamedValuePropertyType; import net.opengis.om._2.OMObservationPropertyType; import net.opengis.samplingspatial._2.SFSpatialSamplingFeatureType; import org.isotc211._2005.gmd.LILineagePropertyType; /** * A "SamplingFeature" is a feature used primarily for taking * observations. * * <p>Java class for SF_SamplingFeatureType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SF_SamplingFeatureType"> * &lt;complexContent> * &lt;extension base="{http://www.opengis.net/gml/3.2}AbstractFeatureType"> * &lt;sequence> * &lt;group ref="{http://www.opengis.net/sampling/2.0}SF_CommonProperties"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SF_SamplingFeatureType", propOrder = { "type", "sampledFeature", "lineage", "relatedObservation", "relatedSamplingFeature", "parameter" }) @XmlSeeAlso({ SFSpatialSamplingFeatureType.class }) public class SFSamplingFeatureType extends AbstractFeatureType { protected ReferenceType type; @XmlElement(required = true, nillable = true) protected List<FeaturePropertyType> sampledFeature; protected LILineagePropertyType lineage; protected List<OMObservationPropertyType> relatedObservation; protected List<SamplingFeatureComplexPropertyType> relatedSamplingFeature; protected List<NamedValuePropertyType> parameter; /** * Gets the value of the type property. * * @return * possible object is * {@link ReferenceType } * */ public ReferenceType getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link ReferenceType } * */ public void setType(ReferenceType value) { this.type = value; } public boolean isSetType() { return (this.type!= null); } /** * Gets the value of the sampledFeature property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the sampledFeature property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSampledFeature().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FeaturePropertyType } * * */ public List<FeaturePropertyType> getSampledFeature() { if (sampledFeature == null) { sampledFeature = new ArrayList<FeaturePropertyType>(); } return this.sampledFeature; } public boolean isSetSampledFeature() { return ((this.sampledFeature!= null)&&(!this.sampledFeature.isEmpty())); } public void unsetSampledFeature() { this.sampledFeature = null; } /** * Gets the value of the lineage property. * * @return * possible object is * {@link LILineagePropertyType } * */ public LILineagePropertyType getLineage() { return lineage; } /** * Sets the value of the lineage property. * * @param value * allowed object is * {@link LILineagePropertyType } * */ public void setLineage(LILineagePropertyType value) { this.lineage = value; } public boolean isSetLineage() { return (this.lineage!= null); } /** * Gets the value of the relatedObservation property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the relatedObservation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRelatedObservation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link OMObservationPropertyType } * * */ public List<OMObservationPropertyType> getRelatedObservation() { if (relatedObservation == null) { relatedObservation = new ArrayList<OMObservationPropertyType>(); } return this.relatedObservation; } public boolean isSetRelatedObservation() { return ((this.relatedObservation!= null)&&(!this.relatedObservation.isEmpty())); } public void unsetRelatedObservation() { this.relatedObservation = null; } /** * Gets the value of the relatedSamplingFeature property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the relatedSamplingFeature property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRelatedSamplingFeature().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SamplingFeatureComplexPropertyType } * * */ public List<SamplingFeatureComplexPropertyType> getRelatedSamplingFeature() { if (relatedSamplingFeature == null) { relatedSamplingFeature = new ArrayList<SamplingFeatureComplexPropertyType>(); } return this.relatedSamplingFeature; } public boolean isSetRelatedSamplingFeature() { return ((this.relatedSamplingFeature!= null)&&(!this.relatedSamplingFeature.isEmpty())); } public void unsetRelatedSamplingFeature() { this.relatedSamplingFeature = null; } /** * Gets the value of the parameter property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the parameter property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParameter().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link NamedValuePropertyType } * * */ public List<NamedValuePropertyType> getParameter() { if (parameter == null) { parameter = new ArrayList<NamedValuePropertyType>(); } return this.parameter; } public boolean isSetParameter() { return ((this.parameter!= null)&&(!this.parameter.isEmpty())); } public void unsetParameter() { this.parameter = null; } }
package com.barassolutions; import com.barassolutions.util.BuiltIns; import com.barassolutions.util.Utils; public abstract class UnaryExpression extends Expression { /** * The operator. */ protected String operator; /** * The operand. */ protected Expression arg; /** * Construct an AST node for a unary expression given its line number, the * unary operator, and the operand. * * @param line * line in which the unary expression occurs in the source file. * @param operator * the unary operator. * @param arg * the operand. */ protected UnaryExpression(int line, String operator, Expression arg) { super(line); this.operator = operator; this.arg = arg; } @Override public void writeToStdOut(PrettyPrinter p) { p.printf("<UnaryExpression line=\"%d\" type=\"%s\" operator=\"%s\">\n", line(), ((type == null) ? "" : type .toString()), Utils.escapeSpecialXMLChars(operator)); p.indentRight(); p.printf("<Operand>\n"); p.indentRight(); arg.writeToStdOut(p); p.indentLeft(); p.printf("</Operand>\n"); p.indentLeft(); p.printf("</UnaryExpression>\n"); } } /** * The AST node for a unary negation (-) expression. */ class OperationNegate extends UnaryExpression { public OperationNegate(int line, Expression arg) { super(line, "-", arg); } /** * Analyzing the negation operation involves analyzing its operand, checking * its type and determining the result type. * * @param context * context in which names are resolved. * @return the analyzed (and possibly rewritten) AST subtree. */ @Override public Expression analyze(Context context) { arg = arg.analyze(context); arg.type().mustMatchExpected(line(), Type.INT, Type.FLOAT); type = arg.type(); return this; } @Override public void codegen(Emitter output) { output.token(TokenOz.WAVE); arg.codegen(output); } } /** * The AST node for a unary validation (+) expression. */ class OperationValidate extends UnaryExpression { public OperationValidate(int line, Expression arg) { super(line, "+", arg); } /** * Analyzing the validation operation involves analyzing its operand, checking * its type and determining the result type. * * @param context * context in which names are resolved. * @return the analyzed (and possibly rewritten) AST subtree. */ @Override public Expression analyze(Context context) { arg = arg.analyze(context); arg.type().mustMatchExpected(line(), Type.INT, Type.FLOAT); type = arg.type(); return this; } @Override public void codegen(Emitter output) { //output.token(TokenOz.PLUS); Not valid in Oz. But also not necessary... arg.codegen(output); } } /** * The AST node for a unary negation (-) expression. */ class OperationLogicalNot extends UnaryExpression { public OperationLogicalNot(int line, Expression arg) { super(line, "!", arg); } /** * Analyzing the negation operation involves analyzing its operand, checking * its type and determining the result type. * * @param context * context in which names are resolved. * @return the analyzed (and possibly rewritten) AST subtree. */ @Override public Expression analyze(Context context) { arg = arg.analyze(context); arg.type().mustMatchExpected(line(), Type.BOOLEAN); type = Type.BOOLEAN; return this; } @Override public void codegen(Emitter output) { output.token(TokenOz.LCURLY); output.literal(BuiltIns.not.ozString()); output.space(); arg.codegen(output); output.token(TokenOz.RCURLY); } }
package ru.v1as.tg.cat.service.clock; import static ru.v1as.tg.cat.tg.MdcTgContext.fromCurrentMdc; import static ru.v1as.tg.cat.utils.LogUtils.logExceptions; import java.util.Comparator; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.h2.util.DoneFuture; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import ru.v1as.tg.cat.utils.LogUtils; @Slf4j @Component @Profile("test") public class TestBotClock implements BotClock { private final Set<Task> tasks = new TreeSet<>(); private final AtomicLong ids = new AtomicLong(); @Override public Future<?> schedule(Runnable runnable, long delay, TimeUnit unit) { log.debug("Task '{}' scheduled in {} {}", runnable, delay, unit); if (delay == 0L) { log.debug("Immediately executing"); LogUtils.logExceptions(runnable).run(); return new DoneFuture<>(null); } final long id = ids.incrementAndGet(); runnable = fromCurrentMdc().wrap(logExceptions(runnable)); final Task task = new Task(id, runnable, unit.toNanos(delay)); synchronized (tasks) { tasks.add(task); log.debug("Scheduled task {} in {} {}", task, delay, unit); } log.debug("Actual tasks: {}", tasks); return task.getFeature(); } public void skip(long delay, TimeUnit timeUnit) { log.debug("Skip time {} {}", delay, timeUnit); final long nanos = timeUnit.toNanos(delay); Optional<Task> todo; Set<Task> oldTask; synchronized (tasks) { oldTask = new HashSet<>(tasks); tasks.forEach(t -> t.skip(nanos)); } do { synchronized (tasks) { todo = tasks.stream().filter(t -> t.getNanos() < 0).findFirst(); } if (todo.isPresent()) { final Task todoTask = todo.get(); log.debug("Running task {}", todoTask); todoTask.run(); synchronized (tasks) { tasks.remove(todoTask); tasks.stream() .filter(t -> !oldTask.contains(t)) .forEach(t -> t.skip(todoTask.getNanos() * -1)); } } } while (todo.isPresent()); } public void reset() { tasks.clear(); } @Data @EqualsAndHashCode(of = "id") @AllArgsConstructor private class Task implements Comparable<Task> { private final Comparator<Task> COMPARATOR = Comparator.comparing(Task::getNanos).thenComparing(Task::getId); private final long id; private final Runnable runnable; private long nanos; void run() { this.runnable.run(); } void skip(long deltaNanos) { this.nanos -= deltaNanos; } @Override public int compareTo(Task that) { return COMPARATOR.compare(this, that); } @Override public String toString() { return String.format("[%s:%s]", id, runnable); } public Future<?> getFeature() { return new TaskFuture(this); } } @RequiredArgsConstructor private class TaskFuture implements Future<Object> { private final Task task; private boolean canceled = false; @Override public boolean cancel(boolean mayInterruptIfRunning) { synchronized (tasks) { if (tasks.contains(task)) { tasks.remove(task); this.canceled = true; return true; } else { return false; } } } @Override public boolean isCancelled() { return canceled; } @Override public boolean isDone() { synchronized (tasks) { return !tasks.contains(this.task); } } @Override public Object get() throws InterruptedException, ExecutionException { throw new UnsupportedOperationException(); } @Override public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { throw new UnsupportedOperationException(); } } }
package com.midtrans.sdk.corekit.models.snap.payment; import com.google.gson.annotations.SerializedName; /** * @author rakawm */ public class BasePaymentRequest { @SerializedName("payment_type") protected String paymentType; public BasePaymentRequest(String paymentType) { this.paymentType = paymentType; } }
/* * MIT License * * Copyright (c) 2021 MASES s.r.l. * * 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. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.windows.automation.peers; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.windows.automation.peers.FrameworkElementAutomationPeer; import system.windows.controls.Calendar; import system.windows.automation.peers.PatternInterface; import system.windows.automation.provider.IRawElementProviderSimple; import system.windows.automation.provider.IRawElementProviderSimpleImplementation; import system.windows.automation.provider.IItemContainerProvider; import system.windows.automation.provider.IItemContainerProviderImplementation; /** * The base .NET class managing System.Windows.Automation.Peers.CalendarAutomationPeer, PresentationFramework, Version=5.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Automation.Peers.CalendarAutomationPeer" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Automation.Peers.CalendarAutomationPeer</a> */ public class CalendarAutomationPeer extends FrameworkElementAutomationPeer implements system.windows.automation.provider.IItemContainerProvider { /** * Fully assembly qualified name: PresentationFramework, Version=5.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 */ public static final String assemblyFullName = "PresentationFramework, Version=5.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; /** * Assembly name: PresentationFramework */ public static final String assemblyShortName = "PresentationFramework"; /** * Qualified class name: System.Windows.Automation.Peers.CalendarAutomationPeer */ public static final String className = "System.Windows.Automation.Peers.CalendarAutomationPeer"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public CalendarAutomationPeer(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link CalendarAutomationPeer}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link CalendarAutomationPeer} instance * @throws java.lang.Throwable in case of error during cast operation */ public static CalendarAutomationPeer cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new CalendarAutomationPeer(from.getJCOInstance()); } // Constructors section public CalendarAutomationPeer() throws Throwable { } public CalendarAutomationPeer(Calendar owner) throws Throwable, system.NotSupportedException, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.ArgumentException, system.InvalidOperationException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(owner == null ? null : owner.getJCOInstance())); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Methods section public NetObject GetPattern(PatternInterface patternInterface) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.NotSupportedException, system.IndexOutOfRangeException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPattern = (JCObject)classInstance.Invoke("GetPattern", patternInterface == null ? null : patternInterface.getJCOInstance()); return new NetObject(objGetPattern); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIGridProvider method available in IGridProvider to obtain an object with an invocable method */ @Deprecated public IRawElementProviderSimple GetItem(int row, int column) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIGridProvider to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIMultipleViewProvider method available in IMultipleViewProvider to obtain an object with an invocable method */ @Deprecated public int[] GetSupportedViews() throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIMultipleViewProvider to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIMultipleViewProvider method available in IMultipleViewProvider to obtain an object with an invocable method */ @Deprecated public java.lang.String GetViewName(int viewId) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIMultipleViewProvider to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIMultipleViewProvider method available in IMultipleViewProvider to obtain an object with an invocable method */ @Deprecated public void SetCurrentView(int viewId) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIMultipleViewProvider to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToISelectionProvider method available in ISelectionProvider to obtain an object with an invocable method */ @Deprecated public IRawElementProviderSimple[] GetSelection() throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToISelectionProvider to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToITableProvider method available in ITableProvider to obtain an object with an invocable method */ @Deprecated public IRawElementProviderSimple[] GetColumnHeaders() throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToITableProvider to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToITableProvider method available in ITableProvider to obtain an object with an invocable method */ @Deprecated public IRawElementProviderSimple[] GetRowHeaders() throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToITableProvider to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIItemContainerProvider method available in IItemContainerProvider to obtain an object with an invocable method */ @Deprecated public IRawElementProviderSimple FindItemByProperty(IRawElementProviderSimple startAfter, int propertyId, NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIItemContainerProvider to obtain the full interface."); } // Properties section // Instance Events section }
package com.compiler; import com.annotations.Command; import com.mapper.CommandsMap; import java.io.IOException; import java.io.Writer; import java.util.List; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; import static com.annotations.Command.NULL_DOUBLE; import static com.annotations.Command.NULL_FLOAT; import static com.annotations.Command.NULL_INTEGER; import static com.annotations.Command.NULL_LONG; import static com.annotations.Command.NULL_STRING; /** * working on the example in this link : * <p> * http://hannesdorfmann.com/annotation-processing/annotationprocessing101 * <p> * in the class : * <p> * public class FactoryGroupedClasses { * <p> * Created by Ahmed Adel Ismail on 7/16/2017. */ class CommandMapGenerator implements Consumer<TypeElement> { private static final String INDENT = " "; private static final String NEW_LINE = "\n"; private static final String END_LINE = ";\n"; private static final String START_BLOCK = "{\n"; private static final String END_BLOCK = "}\n"; private static final String END_METHOD_CALL = ");\n"; private final ProcessingEnvironment environment; CommandMapGenerator(ProcessingEnvironment environment) { this.environment = environment; } @Override public void accept(@NonNull TypeElement element) throws Exception { String generatedClassName = originalClassName(element) + CommandsMap.GENERATED_NAME; try { generateFile(generatedClassName, generateCode(element, generatedClassName)); } catch (IOException e) { // this occurs if the file already existing after its first run, this is normal } catch (Exception e) { environment.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage()); } } private String originalClassName(@NonNull TypeElement element) { return element.getSimpleName().toString(); } private void generateFile(String generatedClassName, StringBuilder stringBuilder) throws IOException { JavaFileObject source = environment.getFiler().createSourceFile(generatedClassName); Writer writer = source.openWriter(); writer.write(stringBuilder.toString()); writer.flush(); writer.close(); } private StringBuilder generateCode(@NonNull TypeElement element, String generatedClassName) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("package ") .append(packageName(element)) .append(END_LINE) .append(NEW_LINE); stringBuilder.append("import com.mapper.*") .append(END_LINE) .append(NEW_LINE); stringBuilder.append("public final class ") .append(generatedClassName) .append(" extends CommandsMap ") .append(START_BLOCK) .append(NEW_LINE); stringBuilder .append(INDENT) .append("public ") .append(generatedClassName) .append("()") .append(START_BLOCK) .append(NEW_LINE); Observable.fromIterable(element.getEnclosedElements()) .filter(byAnnotatedMethods()) .blockingForEach(addCommand(stringBuilder, originalClassName(element))); stringBuilder.append(INDENT) .append(END_BLOCK) .append(END_BLOCK) .append(NEW_LINE); return stringBuilder; } private String packageName(@NonNull TypeElement element) { return environment.getElementUtils().getPackageOf(element).getQualifiedName().toString(); } private Predicate<Element> byAnnotatedMethods() { return new Predicate<Element>() { @Override public boolean test(@NonNull Element element) throws Exception { return element.getAnnotation(Command.class) != null; } }; } private Consumer<? super Element> addCommand(final StringBuilder stringBuilder, final String className) { return new Consumer<Element>() { @Override public void accept(@NonNull Element element) throws Exception { ExecutableElement method = (ExecutableElement) element; List<?> parameters = method.getParameters(); if (parameters == null || parameters.isEmpty()) { addCommandBody(element, stringBuilder, zeroParameterBody(method, className)); } else { int parametersCount = parameters.size(); if (parametersCount == 1) { addCommandBody(element, stringBuilder, oneParameterBody(method, className)); } else if (parametersCount == 2) { addBiCommandBody(element, stringBuilder, twoParameterBody(method, className)); } } } }; } private void addCommandBody(@NonNull Element element, StringBuilder stringBuilder, String commandBody) { stringBuilder .append(INDENT) .append(INDENT) .append("addCommand(") .append(parseKeyFromCommandAnnotation(element)) .append(", ") .append("new Command(){") .append(NEW_LINE) .append(INDENT) .append(INDENT) .append(INDENT) .append("public void accept(Object o1){") .append(NEW_LINE) .append(commandBody) .append(INDENT) .append(INDENT) .append(INDENT) .append("}") .append(NEW_LINE) .append(INDENT) .append(INDENT) .append("}") .append(END_METHOD_CALL) .append(NEW_LINE); } private String zeroParameterBody(ExecutableElement element, String className) { Name methodName = element.getSimpleName(); return bodyPrefix(methodName, className) + "()" + END_LINE + bodyPostfix(methodName, className); } private String oneParameterBody(ExecutableElement element, String className) { Name methodName = element.getSimpleName(); String typeCast = element.getParameters().get(0).asType().toString(); return bodyPrefix(methodName, className) + "((" + typeCast + ")o1)" + END_LINE + bodyPostfix(methodName, className); } private void addBiCommandBody(Element element, StringBuilder stringBuilder, String commandBody) { stringBuilder.append(INDENT) .append(INDENT) .append("addBiCommand(") .append(parseKeyFromCommandAnnotation(element)) .append(", ") .append("new BiCommand(){") .append(NEW_LINE) .append(INDENT) .append(INDENT) .append(INDENT) .append("public void accept(Object o1, Object o2){") .append(NEW_LINE) .append(commandBody) .append(INDENT) .append(INDENT) .append(INDENT) .append("}") .append(NEW_LINE) .append(INDENT) .append(INDENT) .append("}") .append(END_METHOD_CALL) .append(NEW_LINE); } private String twoParameterBody(ExecutableElement element, String className) { Name methodName = element.getSimpleName(); String typeCastOne = element.getParameters().get(0).asType().toString(); String typeCastTwo = element.getParameters().get(1).asType().toString(); return bodyPrefix(methodName, className) + "((" + typeCastOne + ")o1, (" + typeCastTwo + ")o2)" + END_LINE + bodyPostfix(methodName, className); } private Object parseKeyFromCommandAnnotation(@NonNull Element element) { Command annotation = element.getAnnotation(Command.class); Object key = annotation.value(); if (!key.equals(NULL_INTEGER)) { return key; } key = annotation.keyString(); if (!key.equals(NULL_STRING)) { return "\"" + key + "\""; } key = annotation.keyLong(); if (!key.equals(NULL_LONG)) { return key + "L"; } key = annotation.keyDouble(); if (!key.equals(NULL_DOUBLE)) { return key + "D"; } key = annotation.keyFloat(); if (!key.equals(NULL_FLOAT)) { return key + "F"; } throw new IllegalArgumentException("@" + Command.class.getSimpleName() + " must have a value in : " + element.getSimpleName() + "()"); } private String bodyPrefix(Name methodName, String className) { return INDENT + INDENT + INDENT + INDENT + "if(getHostObject() != null){" + NEW_LINE + INDENT + INDENT + INDENT + INDENT + INDENT + "((" + className + ")getHostObject())." + methodName; } private String bodyPostfix(Name methodName, String className) { return INDENT + INDENT + INDENT + INDENT + "} else { " + NEW_LINE + INDENT + INDENT + INDENT + INDENT + INDENT + "java.lang.System.out.println(\" " + CommandsMap.class.getSimpleName() + " cleared for " + className + "." + methodName + "() \"); " + NEW_LINE + INDENT + INDENT + INDENT + INDENT + "}" + NEW_LINE; } }
package com.mprzybylak.minefields.jpa.relationships.manytoone.uni; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Computer { @Id private long id; public Computer() { } public Computer(long id) { this.id = id; } public long getId() { return id; } }
package com.daxiang.core.testng; import com.daxiang.core.DeviceHolder; import com.daxiang.model.UploadFile; import com.daxiang.server.ServerClient; import com.daxiang.model.action.Step; import com.daxiang.model.devicetesttask.DeviceTestTask; import com.daxiang.model.devicetesttask.Testcase; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.exception.ExceptionUtils; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.TestListenerAdapter; import java.util.Collections; import java.util.Date; import java.util.List; /** * Created by jiangyitao. */ @Slf4j public class TestCaseTestListener extends TestListenerAdapter { public static final String TEST_DESCRIPTION = "test_desc"; private static final ThreadLocal<Integer> CURRENT_TEST_CASE_ID = new ThreadLocal<>(); private static final ThreadLocal<String> CONFIG_FAIL_ERR_INFO = new ThreadLocal<>(); private static final ThreadLocal<Long> TEST_CASE_START_TIME = new ThreadLocal<>(); /** * 每个device开始测试调用的方法,这里可能有多个线程同时调用 * * @param testContext */ @Override public void onStart(ITestContext testContext) { TestDescription testDesc = TestDescription.create(testContext.getAllTestMethods()[0].getDescription()); log.info("[{}]onStart, deviceTestTaskId:{}", testDesc.getDeviceId(), testDesc.getDeviceTestTaskId()); testContext.setAttribute(TEST_DESCRIPTION, testDesc); DeviceTestTask deviceTestTask = new DeviceTestTask(); deviceTestTask.setId(testDesc.getDeviceTestTaskId()); deviceTestTask.setStartTime(new Date()); deviceTestTask.setStatus(DeviceTestTask.RUNNING_STATUS); ServerClient.getInstance().updateDeviceTestTask(deviceTestTask); } /** * 每个device结束测试调用的方法,这里可能有多个线程同时调用 * * @param testContext */ @Override public void onFinish(ITestContext testContext) { TestDescription testDesc = (TestDescription) testContext.getAttribute(TEST_DESCRIPTION); log.info("[{}]onFinish, deviceTestTaskId: {}", testDesc.getDeviceId(), testDesc.getDeviceTestTaskId()); CURRENT_TEST_CASE_ID.remove(); CONFIG_FAIL_ERR_INFO.remove(); TEST_CASE_START_TIME.remove(); DeviceTestTask deviceTestTask = new DeviceTestTask(); deviceTestTask.setId(testDesc.getDeviceTestTaskId()); deviceTestTask.setEndTime(new Date()); deviceTestTask.setStatus(DeviceTestTask.FINISHED_STATUS); ServerClient.getInstance().updateDeviceTestTask(deviceTestTask); } /** * 每个device执行每条测试用例前调用的方法,这里可能有多个线程同时调用 * * @param tr */ @Override public void onTestStart(ITestResult tr) { TestDescription testDesc = (TestDescription) tr.getTestContext().getAttribute(TEST_DESCRIPTION); Integer testcaseId = TestDescription.parseTestcaseId(tr.getMethod().getDescription()); testDesc.setTestcaseId(testcaseId); CURRENT_TEST_CASE_ID.set(testcaseId); log.info("[{}]onTestStart, testcaseId: {}", testDesc.getDeviceId(), testcaseId); Testcase testcase = new Testcase(); testcase.setId(testcaseId); Date now = new Date(); testcase.setStartTime(now); TEST_CASE_START_TIME.set(now.getTime()); ServerClient.getInstance().updateTestcase(testDesc.getDeviceTestTaskId(), testcase); // 当BeforeClass或dependsOnMethods执行失败 -> tr.getThrowable() != null // 不需要开启视频录制,因为testng会马上调用onTestSkip if (tr.getThrowable() == null && testDesc.getRecordVideo()) { try { log.info("[{}]testcaseId: {}, 开始录制视频...", testDesc.getDeviceId(), testcaseId); DeviceHolder.get(testDesc.getDeviceId()).startRecordingScreen(); } catch (Exception e) { log.error("[{}]testcaseId: {}, 启动录制视频失败", testDesc.getDeviceId(), testcaseId, e); testDesc.setRecordVideo(false); } } } @Override public void onTestSuccess(ITestResult tr) { TestDescription testDesc = (TestDescription) tr.getTestContext().getAttribute(TEST_DESCRIPTION); log.info("[{}]onTestSuccess, testcaseId: {}", testDesc.getDeviceId(), testDesc.getTestcaseId()); Testcase testcase = new Testcase(); testcase.setId(testDesc.getTestcaseId()); testcase.setEndTime(new Date()); testcase.setStatus(Testcase.PASS_STATUS); testcase.setVideoPath(uploadVideo(testDesc)); ServerClient.getInstance().updateTestcase(testDesc.getDeviceTestTaskId(), testcase); } @Override public void onTestFailure(ITestResult tr) { TestDescription testDesc = (TestDescription) tr.getTestContext().getAttribute(TEST_DESCRIPTION); log.error("[{}]onTestFailure, testcaseId: {}", testDesc.getDeviceId(), testDesc.getTestcaseId()); Testcase testcase = new Testcase(); testcase.setId(testDesc.getTestcaseId()); testcase.setEndTime(new Date()); testcase.setStatus(Testcase.FAIL_STATUS); testcase.setFailImgPath(uploadScreenshot(testDesc)); testcase.setFailInfo(ExceptionUtils.getStackTrace(tr.getThrowable())); testcase.setVideoPath(uploadVideo(testDesc)); testcase.setLogPath(uploadLog(testDesc)); ServerClient.getInstance().updateTestcase(testDesc.getDeviceTestTaskId(), testcase); } @Override public void onTestSkipped(ITestResult tr) { TestDescription testDesc = (TestDescription) tr.getTestContext().getAttribute(TEST_DESCRIPTION); log.warn("[{}]onTestSkipped, testcaseId: {}", testDesc.getDeviceId(), testDesc.getTestcaseId()); Testcase testcase = new Testcase(); testcase.setId(testDesc.getTestcaseId()); testcase.setEndTime(new Date()); testcase.setStatus(Testcase.SKIP_STATUS); if (CONFIG_FAIL_ERR_INFO.get() != null) { // BeforeClass执行失败 testcase.setFailInfo(CONFIG_FAIL_ERR_INFO.get()); } else if (tr.getThrowable() != null) { testcase.setFailInfo(ExceptionUtils.getStackTrace(tr.getThrowable())); testcase.setFailImgPath(uploadScreenshot(testDesc)); // setUp失败或手动throw SkipException if (tr.getThrowable() instanceof SkipException) { testcase.setVideoPath(uploadVideo(testDesc)); testcase.setLogPath(uploadLog(testDesc)); } } ServerClient.getInstance().updateTestcase(testDesc.getDeviceTestTaskId(), testcase); } /** * BeforeClass执行出错时,将进入该方法 * 进入该方法后,后续的testcase都将跳过。将直接调用onTestStart -> onTestSkipped,不会调用@Test * * @param tr */ @Override public void onConfigurationFailure(ITestResult tr) { TestDescription testDesc = (TestDescription) tr.getTestContext().getAttribute(TEST_DESCRIPTION); log.error("[{}]{}执行失败", testDesc.getDeviceId(), tr.getName(), tr.getThrowable()); CONFIG_FAIL_ERR_INFO.set(tr.getName() + "执行失败!\n\n" + ExceptionUtils.getStackTrace(tr.getThrowable())); } private String uploadScreenshot(TestDescription testDesc) { try { log.info("[{}]testcaseId: {}, 上传截图...", testDesc.getDeviceId(), testDesc.getTestcaseId()); return DeviceHolder.get(testDesc.getDeviceId()).screenshotAndUploadToServer().getFilePath(); } catch (Exception e) { log.error("[{}]testcaseId: {},截图并上传到server失败", testDesc.getDeviceId(), testDesc.getTestcaseId(), e); return null; } } private String uploadLog(TestDescription testDesc) { try { log.info("[{}]testcaseId: {}, 获取日志...", testDesc.getDeviceId(), testDesc.getTestcaseId()); long startTime = System.currentTimeMillis(); UploadFile uploadLogFile = DeviceHolder.get(testDesc.getDeviceId()).getLogAndUploadToServer(TEST_CASE_START_TIME.get()); if (uploadLogFile == null) { log.info("[{}]testcaseId: {}, 无法获取日志", testDesc.getDeviceId(), testDesc.getTestcaseId()); return null; } String uploadFilePath = uploadLogFile.getFilePath(); log.info("[{}]testcaseId: {}, 获取日志并上传到server完成, 耗时: {} ms", testDesc.getDeviceId(), testDesc.getTestcaseId(), System.currentTimeMillis() - startTime); return uploadFilePath; } catch (Exception e) { log.error("[{}]testcaseId: {},获取日志并上传到server失败", testDesc.getDeviceId(), testDesc.getTestcaseId(), e); return null; } } private String uploadVideo(TestDescription testDesc) { if (!testDesc.getRecordVideo()) { // server未开启录制视频 或 启动录制视频失败 return null; } try { log.info("[{}]testcaseId: {}, 停止录制视频...", testDesc.getDeviceId(), testDesc.getTestcaseId()); long startTime = System.currentTimeMillis(); String uploadFilePath = DeviceHolder.get(testDesc.getDeviceId()).stopRecordingScreenAndUploadToServer().getFilePath(); log.info("[{}]testcaseId: {}, 停止录制视频并上传到server完成, 耗时: {} ms", testDesc.getDeviceId(), testDesc.getTestcaseId(), System.currentTimeMillis() - startTime); return uploadFilePath; } catch (Exception e) { log.error("[{}]testcaseId: {},停止录制视频并上传到server失败", testDesc.getDeviceId(), testDesc.getTestcaseId(), e); return null; } } /** * 提供给actions.ftl调用,记录步骤的执行开始/结束时间 * flag start end * step 1 2 * setUp 3 4 * tearDown 5 6 */ public static void recordStepTime(Integer deviceTestTaskId, Integer actionId, Integer stepNumber, int flag) { Integer currentTestcaseId = CURRENT_TEST_CASE_ID.get(); // 只记录当前正在执行的测试用例里的步骤 if (!actionId.equals(currentTestcaseId)) { return; } Step step = new Step(); step.setNumber(stepNumber); if (flag == 1 || flag == 3 || flag == 5) { step.setStartTime(new Date()); } else if (flag == 2 || flag == 4 || flag == 6) { step.setEndTime(new Date()); } Testcase testcase = new Testcase(); testcase.setId(currentTestcaseId); List<Step> steps = Collections.singletonList(step); if (flag == 1 || flag == 2) { testcase.setSteps(steps); } else if (flag == 3 || flag == 4) { testcase.setSetUp(steps); } else if (flag == 5 || flag == 6) { testcase.setTearDown(steps); } ServerClient.getInstance().updateTestcase(deviceTestTaskId, testcase); } }
package org.nuclearfog.twidda.adapter; import static android.view.View.VISIBLE; import static androidx.recyclerview.widget.RecyclerView.NO_POSITION; import android.content.Context; import android.net.Uri; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView.Adapter; import androidx.recyclerview.widget.RecyclerView.ViewHolder; import org.nuclearfog.twidda.adapter.holder.Footer; import org.nuclearfog.twidda.adapter.holder.ImageHolder; import org.nuclearfog.twidda.database.GlobalSettings; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * custom {@link androidx.recyclerview.widget.RecyclerView} adapter implementation to show image previews * * @author nuclearfog * @see org.nuclearfog.twidda.ui.activities.ImageViewer */ public class ImageAdapter extends Adapter<ViewHolder> { /** * View type for an image item */ private static final int PICTURE = 0; /** * View type for a circle view */ private static final int LOADING = 1; private OnImageClickListener itemClickListener; private GlobalSettings settings; private List<Uri> imageUri = new ArrayList<>(5); private boolean loading = false; private boolean enableSaveButton = true; /** * @param itemClickListener click listener */ public ImageAdapter(Context context, OnImageClickListener itemClickListener) { this.itemClickListener = itemClickListener; this.settings = GlobalSettings.getInstance(context); } public void addAll(Uri[] uris) { imageUri.clear(); imageUri.addAll(Arrays.asList(uris)); notifyDataSetChanged(); } /** * add new image at the last position * * @param uri Uri of the image */ @MainThread public void addLast(@NonNull Uri uri) { int imagePos = imageUri.size(); if (imagePos == 0) loading = true; imageUri.add(uri); notifyItemInserted(imagePos); } /** * disable placeholder view */ @MainThread public void disableLoading() { loading = false; int circlePos = imageUri.size(); notifyItemRemoved(circlePos); } /** * disable save button on images */ public void disableSaveButton() { enableSaveButton = false; } /** * check if image adapter is empty * * @return true if there isn't any image */ public boolean isEmpty() { return imageUri.isEmpty(); } @Override public int getItemViewType(int position) { if (loading && position == imageUri.size()) return LOADING; return PICTURE; } @Override public int getItemCount() { if (loading) return imageUri.size() + 1; return imageUri.size(); } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, int viewType) { if (viewType == PICTURE) { final ImageHolder item = new ImageHolder(parent, settings); item.preview.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int pos = item.getLayoutPosition(); if (pos != NO_POSITION) { itemClickListener.onImageClick(imageUri.get(pos)); } } }); if (enableSaveButton) { item.saveButton.setVisibility(VISIBLE); item.saveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int pos = item.getLayoutPosition(); if (pos != NO_POSITION) { itemClickListener.onImageSave(imageUri.get(pos)); } } }); } return item; } else { return new Footer(parent, settings, true); } } @Override public void onBindViewHolder(@NonNull ViewHolder vh, int index) { if (vh instanceof ImageHolder) { ImageHolder item = (ImageHolder) vh; Uri uri = imageUri.get(index); item.preview.setImageURI(uri); } } /** * click listener for image items */ public interface OnImageClickListener { /** * called to select an image * * @param uri selected image uri */ void onImageClick(Uri uri); /** * called to save image to storage */ void onImageSave(Uri uri); } }
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation 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.tle.beans.item; public enum VersionSelection { FORCE_LATEST, FORCE_CURRENT, DEFAULT_TO_LATEST, DEFAULT_TO_CURRENT, // The following value is deprecated as it's not really valid. For courses // that currently store this in the database, they should really be using // "null" instead to indicate that the course doesn't have a preference. @Deprecated INSTITUTION_DEFAULT; }
/* * 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.druid.query.aggregation.histogram; import com.google.common.collect.Lists; import org.apache.druid.common.config.NullHandling; import org.apache.druid.data.input.MapBasedRow; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.java.util.common.guava.Sequence; import org.apache.druid.query.aggregation.AggregationTestHelper; import org.apache.druid.query.groupby.GroupByQueryConfig; import org.apache.druid.query.groupby.GroupByQueryRunnerTest; import org.junit.After; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** */ @RunWith(Parameterized.class) public class ApproximateHistogramAggregationTest { private AggregationTestHelper helper; @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); public ApproximateHistogramAggregationTest(final GroupByQueryConfig config) { ApproximateHistogramDruidModule module = new ApproximateHistogramDruidModule(); module.configure(null); helper = AggregationTestHelper.createGroupByQueryAggregationTestHelper( Lists.newArrayList(module.getJacksonModules()), config, tempFolder ); } @Parameterized.Parameters(name = "{0}") public static Collection<?> constructorFeeder() { final List<Object[]> constructors = new ArrayList<>(); for (GroupByQueryConfig config : GroupByQueryRunnerTest.testConfigs()) { constructors.add(new Object[]{config}); } return constructors; } @After public void teardown() throws IOException { helper.close(); } @Test public void testIngestWithNullsIgnoredAndQuery() throws Exception { MapBasedRow row = ingestAndQuery(true); Assert.assertEquals(92.782760, row.getMetric("index_min").floatValue(), 0.0001); Assert.assertEquals(135.109191, row.getMetric("index_max").floatValue(), 0.0001); Assert.assertEquals(133.69340, row.getMetric("index_quantile").floatValue(), 0.0001); } @Test public void testIngestWithNullsToZeroAndQuery() throws Exception { // Nulls are ignored and not replaced with default for SQL compatible null handling. // This is already tested in testIngestWithNullsIgnoredAndQuery() if (NullHandling.replaceWithDefault()) { MapBasedRow row = ingestAndQuery(false); Assert.assertEquals(0.0F, row.getMetric("index_min")); Assert.assertEquals(135.109191, row.getMetric("index_max").floatValue(), 0.0001); Assert.assertEquals(131.428176, row.getMetric("index_quantile").floatValue(), 0.0001); } } private MapBasedRow ingestAndQuery(boolean ignoreNulls) throws Exception { String ingestionAgg = ignoreNulls ? "approxHistogramFold" : "approxHistogram"; String metricSpec = "[{" + "\"type\": \"" + ingestionAgg + "\"," + "\"name\": \"index_ah\"," + "\"fieldName\": \"index\"" + "}]"; String parseSpec = "{" + "\"type\" : \"string\"," + "\"parseSpec\" : {" + " \"format\" : \"tsv\"," + " \"timestampSpec\" : {" + " \"column\" : \"timestamp\"," + " \"format\" : \"auto\"" + "}," + " \"dimensionsSpec\" : {" + " \"dimensions\": []," + " \"dimensionExclusions\" : []," + " \"spatialDimensions\" : []" + " }," + " \"columns\": [\"timestamp\", \"market\", \"quality\", \"placement\", \"placementish\", \"index\"]" + " }" + "}"; String query = "{" + "\"queryType\": \"groupBy\"," + "\"dataSource\": \"test_datasource\"," + "\"granularity\": \"ALL\"," + "\"dimensions\": []," + "\"aggregations\": [" + " { \"type\": \"approxHistogramFold\", \"name\": \"index_ah\", \"fieldName\": \"index_ah\" }" + "]," + "\"postAggregations\": [" + " { \"type\": \"min\", \"name\": \"index_min\", \"fieldName\": \"index_ah\"}," + " { \"type\": \"max\", \"name\": \"index_max\", \"fieldName\": \"index_ah\"}," + " { \"type\": \"quantile\", \"name\": \"index_quantile\", \"fieldName\": \"index_ah\", \"probability\" : 0.99 }" + "]," + "\"intervals\": [ \"1970/2050\" ]" + "}"; Sequence seq = helper.createIndexAndRunQueryOnSegment( this.getClass().getClassLoader().getResourceAsStream("sample.data.tsv"), parseSpec, metricSpec, 0, Granularities.NONE, 50000, query ); return (MapBasedRow) seq.toList().get(0); } }
/* * Copyright 2011 DTO Solutions, Inc. (http://dtosolutions.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * WFFirstWorkflowStrategy.java * * User: Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a> * Created: Aug 26, 2010 2:16:49 PM * $Id$ */ package com.dtolabs.rundeck.core.execution.workflow; import com.dtolabs.rundeck.core.Constants; import com.dtolabs.rundeck.core.NodesetEmptyException; import com.dtolabs.rundeck.core.common.Framework; import com.dtolabs.rundeck.core.common.IFramework; import com.dtolabs.rundeck.core.common.INodeEntry; import com.dtolabs.rundeck.core.common.NodesSelector; import com.dtolabs.rundeck.core.execution.ExecutionContext; import com.dtolabs.rundeck.core.execution.ExecutionContextImpl; import com.dtolabs.rundeck.core.execution.HasSourceResult; import com.dtolabs.rundeck.core.execution.StatusResult; import com.dtolabs.rundeck.core.execution.StepExecutionItem; import com.dtolabs.rundeck.core.execution.dispatch.Dispatchable; import com.dtolabs.rundeck.core.execution.dispatch.DispatcherException; import com.dtolabs.rundeck.core.execution.dispatch.DispatcherResult; import com.dtolabs.rundeck.core.execution.dispatch.DispatcherResultImpl; import com.dtolabs.rundeck.core.execution.service.ExecutionServiceException; import com.dtolabs.rundeck.core.execution.workflow.steps.FailureReason; import com.dtolabs.rundeck.core.execution.workflow.steps.NodeDispatchStepExecutor; import com.dtolabs.rundeck.core.execution.workflow.steps.StepExecutionResult; import com.dtolabs.rundeck.core.execution.workflow.steps.StepExecutor; import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException; import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepResult; import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepResultImpl; import org.apache.log4j.Logger; import java.util.*; /** * NodeFirstWorkflowStrategy Iterates over the matched nodes first, so that each node executes the full workflow * sequentially * * @author Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a> * @version $Revision$ * @deprecated */ public class NodeFirstWorkflowExecutor extends BaseWorkflowExecutor { static final Logger logger = Logger.getLogger(NodeFirstWorkflowExecutor.class.getName()); public NodeFirstWorkflowExecutor(final IFramework framework) { super(framework); } public WorkflowExecutionResult executeWorkflowImpl(final StepExecutionContext executionContext, final WorkflowExecutionItem item) { Exception exception = null; final IWorkflow workflow = item.getWorkflow(); WorkflowStatusResult wfresult= null; final ArrayList<StepExecutionResult> results = new ArrayList<>(); final Map<String, Collection<StepExecutionResult>> failures = new HashMap<>(); final Map<Integer, StepExecutionResult> stepFailures = new HashMap<>(); boolean workflowsuccess = true; String statusString=null; ControlBehavior controlBehavior = null; final WFSharedContext wfCurrentContext = WFSharedContext.withBase(executionContext.getSharedDataContext()); try { final NodesSelector nodeSelector = executionContext.getNodeSelector(); if (workflow.getCommands().size() < 1) { executionContext.getExecutionListener().log(Constants.WARN_LEVEL, "Workflow has 0 items"); } validateNodeSet(executionContext, nodeSelector); logger.debug("Begin loop"); //split workflow around non-node dispatched items, and loop //each dispatched sequence should be wrapped in a separate dispatch //and each non-dispatched step performed separately final List<IWorkflow> sections = splitWorkflowDispatchedSections(workflow); int stepCount = 1; if (sections.size() > 1) { logger.debug("Split workflow into " + sections.size() + " sections"); } assert sections.size() >= 1; if (sections.size() < 1) { throw new IllegalStateException(); } for (final IWorkflow flowsection : sections) { WorkflowStatusResult sectionSuccess; WorkflowDataResult sectionData; StepExecutor stepExecutor = getFramework().getStepExecutionService() .getExecutorForItem(flowsection.getCommands().get(0)); if (stepExecutor.isNodeDispatchStep(flowsection.getCommands().get(0))) { WorkflowStatusDataResult workflowStatusDataResult = executeWFSectionNodeDispatch( executionContext, stepCount, results, failures, stepFailures, flowsection, wfCurrentContext ); sectionSuccess = workflowStatusDataResult; sectionData = workflowStatusDataResult; } else { //run the Workflow Step section as a normal step-first strategy workflow //execute each item sequentially WorkflowExecutionItem innerLoopItem = createInnerLoopItem(flowsection); WorkflowExecutor executorForItem = getFramework().getWorkflowExecutionService().getExecutorForItem(innerLoopItem); WFSharedContext currentData = new WFSharedContext(wfCurrentContext); StepExecutionContext newContext = ExecutionContextImpl.builder(executionContext) .sharedDataContext(currentData) .stepNumber(stepCount) .build(); WorkflowExecutionResult workflowExecutionResult = executorForItem.executeWorkflow( newContext, innerLoopItem ); results.addAll(workflowExecutionResult.getResultSet()); mergeFailure(failures, workflowExecutionResult.getNodeFailures()); stepFailures.putAll(workflowExecutionResult.getStepFailures()); sectionSuccess = workflowExecutionResult; sectionData = workflowExecutionResult; } //combine output results for the section wfCurrentContext.merge(sectionData.getSharedContext()); wfresult = sectionSuccess; if(!sectionSuccess.isSuccess()) { workflowsuccess = false; } if (sectionSuccess.getControlBehavior() != null && sectionSuccess.getControlBehavior() != ControlBehavior.Continue) { controlBehavior = sectionSuccess.getControlBehavior(); } if(sectionSuccess.getStatusString() !=null) { statusString = sectionSuccess.getStatusString(); } if (!workflowsuccess && !item.getWorkflow().isKeepgoing() || controlBehavior == ControlBehavior.Halt) { break; } stepCount += flowsection.getCommands().size(); } wfresult = workflowResult(workflowsuccess, statusString, controlBehavior, wfCurrentContext); } catch (NodesetEmptyException e) { Boolean successOnEmptyNodeFilter = Boolean.valueOf(executionContext.getDataContext() .get("job") .get("successOnEmptyNodeFilter")); if (!successOnEmptyNodeFilter) { exception = e; e.printStackTrace(); executionContext.getExecutionListener().log(Constants.ERR_LEVEL, "Exception: " + e.getClass() + ": " + e .getMessage()); wfresult = WorkflowResultFailed; } else { logger.debug("No matched nodes"); wfresult = workflowResult(true, null, ControlBehavior.Continue, wfCurrentContext); } } catch (RuntimeException e) { exception = e; e.printStackTrace(); executionContext.getExecutionListener().log(Constants.ERR_LEVEL, "Exception: " + e.getClass() + ": " + e .getMessage()); wfresult = WorkflowResultFailed; } catch (DispatcherException | ExecutionServiceException e) { exception = e; executionContext.getExecutionListener().log(Constants.ERR_LEVEL, "Exception: " + e.getClass() + ": " + e .getMessage()); wfresult = WorkflowResultFailed; } final Exception fexception = exception; return new BaseWorkflowExecutionResult( results, failures, stepFailures, fexception, wfresult, wfCurrentContext ); } /** * Execute a workflow section that should be dispatched across nodes * * @return true if the section was succesful */ private WorkflowStatusDataResult executeWFSectionNodeDispatch( StepExecutionContext executionContext, int stepCount, List<StepExecutionResult> results, Map<String, Collection<StepExecutionResult>> failures, final Map<Integer, StepExecutionResult> stepFailures, IWorkflow flowsection, WFSharedContext sharedContext ) throws ExecutionServiceException, DispatcherException { logger.debug("Node dispatch for " + flowsection.getCommands().size() + " steps"); final DispatcherResult dispatch; final WorkflowExecutionItem innerLoopItem = createInnerLoopItem(flowsection); final Dispatchable dispatchedWorkflow = new DispatchedWorkflow( getFramework().getWorkflowExecutionService(), innerLoopItem, stepCount, executionContext.getStepContext() ); WFSharedContext dispatchSharedContext = new WFSharedContext(sharedContext); //dispatch the sequence of dispatched items to each node dispatch = getFramework().getExecutionService().dispatchToNodes( ExecutionContextImpl.builder(executionContext) .sharedDataContext(dispatchSharedContext) .stepNumber(stepCount) .build(), dispatchedWorkflow ); logger.debug("Node dispatch result: " + dispatch); WFSharedContext resultData = extractWFDispatcherResult( dispatch, results, failures, stepFailures, flowsection.getCommands().size(), stepCount ); return workflowResult(dispatch.isSuccess(), null, ControlBehavior.Continue, resultData); } /** * invert the result of a DispatcherResult where each NodeStepResult contains a WorkflowResult */ private WFSharedContext extractWFDispatcherResult( final DispatcherResult dispatcherResult, final List<StepExecutionResult> results, final Map<String, Collection<StepExecutionResult>> failures, final Map<Integer, StepExecutionResult> stepFailures, int index, int max ) { WFSharedContext wfSharedContext = new WFSharedContext(); ArrayList<HashMap<String, NodeStepResult>> mergedStepResults = new ArrayList<>(max); ArrayList<Boolean> successes = new ArrayList<>(max); HashMap<Integer, Map<String, NodeStepResult>> mergedStepFailures = new HashMap<>(); //Convert a dispatcher result to a list of StepExecutionResults. //each result for node in the dispatcheresult contains a workflow result //unroll each workflow result, append the result of each step into map of node results //merge each step result with the mergedStepResults //DispatcherResult contains map {nodename: NodeStepResult} for (final String nodeName : dispatcherResult.getResults().keySet()) { final NodeStepResult stepResult = dispatcherResult.getResults().get(nodeName); if (stepResult.getSharedContext() != null) { wfSharedContext.merge(stepResult.getSharedContext()); } //This NodeStepResult is produced by the DispatchedWorkflow wrapper WorkflowExecutionResult result = DispatchedWorkflow.extractWorkflowResult(stepResult); failures.computeIfAbsent(nodeName, k -> new ArrayList<>()); //extract failures for this node final Collection<StepExecutionResult> thisNodeFailures = result.getNodeFailures().get(nodeName); if (null != thisNodeFailures && thisNodeFailures.size() > 0) { failures.get(nodeName).addAll(thisNodeFailures); } //extract failures by step (for this node) Map<Integer, NodeStepResult> perStepFailures = DispatchedWorkflow.extractStepFailures(result, stepResult.getNode()); for (final Map.Entry<Integer, NodeStepResult> entry : perStepFailures.entrySet()) { Integer stepNum = entry.getKey(); NodeStepResult value = entry.getValue(); mergedStepFailures.computeIfAbsent(stepNum, k -> new HashMap<>()); mergedStepFailures.get(stepNum).put(nodeName, value); } if (result.getResultSet().size() < 1 && result.getNodeFailures().size() < 1 && result.getStepFailures() .size() < 1 && !result.isSuccess()) { //failure could be prior to any node step mergedStepFailures.computeIfAbsent(0, k -> new HashMap<>()); mergedStepFailures.get(0).put(nodeName, stepResult); } //The WorkflowExecutionResult has a list of StepExecutionResults produced by NodeDispatchStepExecutor List<NodeStepResult> results1 = DispatchedWorkflow.extractNodeStepResults(result, stepResult.getNode()); int i = 0; for (final NodeStepResult nodeStepResult : results1) { while (mergedStepResults.size() <= i) { mergedStepResults.add(new HashMap<>()); } while (successes.size() <= i) { successes.add(Boolean.TRUE); } HashMap<String, NodeStepResult> map = mergedStepResults.get(i); map.put(nodeName, nodeStepResult); if (!nodeStepResult.isSuccess()) { successes.set(i, false); // failures.get(nodeName).add(nodeStepResult); } i++; } } //add a new wrapped DispatcherResults for each original step int x = 0; for (final HashMap<String, NodeStepResult> map : mergedStepResults) { Boolean success = successes.get(x); DispatcherResult r = new DispatcherResultImpl(map, null != success ? success : false); results.add(NodeDispatchStepExecutor.wrapDispatcherResult(r)); x++; } //merge failures for each step for (final Integer integer : mergedStepFailures.keySet()) { Map<String, NodeStepResult> map = mergedStepFailures.get(integer); DispatcherResult r = new DispatcherResultImpl(map, false); stepFailures.put(integer, NodeDispatchStepExecutor.wrapDispatcherResult(r)); } return wfSharedContext; } private void mergeFailure(Map<String, Collection<StepExecutionResult>> destination, Map<String, Collection<StepExecutionResult>> source) { for (final String s : source.keySet()) { if (null == destination.get(s)) { destination.put(s, new ArrayList<>()); } destination.get(s).addAll(source.get(s)); } } private void validateNodeSet(ExecutionContext executionContext, NodesSelector nodeSelector) { if (0 == executionContext.getNodes().getNodes().size()) { throw new NodesetEmptyException(nodeSelector); } } static enum Reason implements FailureReason { WorkflowSequenceFailures, ExecutionServiceError } /** * Workflow execution logic to dispatch an entire workflow sequence to a single node. */ static class DispatchedWorkflow implements Dispatchable { WorkflowExecutionItem workflowItem; int beginStep; List<Integer> stack; WorkflowExecutionService workflowExecutionService; DispatchedWorkflow( WorkflowExecutionService workflowExecutionService, WorkflowExecutionItem workflowItem, int beginStep, List<Integer> stack ) { this.workflowExecutionService = workflowExecutionService; this.workflowItem = workflowItem; this.beginStep = beginStep; this.stack = stack; } public NodeStepResult dispatch(final ExecutionContext context, final INodeEntry node) { final ExecutionContextImpl newcontext = new ExecutionContextImpl.Builder(context) .singleNodeContext(node, true) .stepNumber(beginStep) .stepContext(stack) .build(); final WorkflowExecutor executor; try { executor = workflowExecutionService.getExecutorForItem(workflowItem); } catch (ExecutionServiceException e) { return new NodeStepResultImpl( e, Reason.ExecutionServiceError, "Exception: " + e.getClass() + ": " + e.getMessage(), node ); } WorkflowExecutionResult result = executor.executeWorkflow(newcontext, workflowItem); NodeStepResultImpl result1; if (result.isSuccess()) { result1 = new NodeStepResultImpl(node); } else { result1 = new NodeStepResultImpl(result.getException(), Reason.WorkflowSequenceFailures, null == result.getException() ? "Sequence failed" : "Exception: " + result.getException() .getClass() + ": " + result.getException().getMessage(), node); } result1.setSharedContext(result.getSharedContext()); result1.setSourceResult(result); return result1; } static WorkflowExecutionResult extractWorkflowResult(NodeStepResult dispatcherResult) { assert dispatcherResult instanceof HasSourceResult; if (!(dispatcherResult instanceof HasSourceResult)) { throw new IllegalArgumentException("Cannot extract source result from dispatcher result"); } HasSourceResult sourced = (HasSourceResult) dispatcherResult; StatusResult sourceResult = sourced.getSourceResult(); while (!(sourceResult instanceof WorkflowExecutionResult) && (sourceResult instanceof HasSourceResult)) { sourceResult = ((HasSourceResult) sourceResult).getSourceResult(); } if (!(sourceResult instanceof WorkflowExecutionResult)) { throw new IllegalArgumentException("Cannot extract workflow result from dispatcher result: " + sourceResult.getClass().getName()); } WorkflowExecutionResult wfresult = (WorkflowExecutionResult) sourceResult; return wfresult; } static List<NodeStepResult> extractNodeStepResults(WorkflowExecutionResult result, INodeEntry node) { ArrayList<NodeStepResult> results = new ArrayList<>(); for (final StepExecutionResult executionResult : result.getResultSet()) { if (NodeDispatchStepExecutor.isWrappedDispatcherResult(executionResult)) { DispatcherResult dispatcherResult = NodeDispatchStepExecutor.extractDispatcherResult(executionResult); NodeStepResult stepResult = dispatcherResult.getResults().get(node.getNodename()); if(null!=stepResult){ results.add(stepResult); } }else if (NodeDispatchStepExecutor.isWrappedDispatcherException(executionResult)) { DispatcherException exception = NodeDispatchStepExecutor.extractDispatcherException(executionResult); NodeStepException nodeStepException = exception.getNodeStepException(); if (null != nodeStepException) { results.add(nodeStepResultFromNodeStepException(node, nodeStepException)); } } } return results; } static Map<Integer,NodeStepResult> extractStepFailures(WorkflowExecutionResult result, INodeEntry node) { Map<Integer, NodeStepResult> results = new HashMap<>(); for (final Map.Entry<Integer, StepExecutionResult> entry : result.getStepFailures().entrySet()) { int num = entry.getKey(); StepExecutionResult executionResult = entry.getValue(); if (NodeDispatchStepExecutor.isWrappedDispatcherResult(executionResult)) { DispatcherResult dispatcherResult = NodeDispatchStepExecutor.extractDispatcherResult(executionResult); NodeStepResult stepResult = dispatcherResult.getResults().get(node.getNodename()); if (null != stepResult) { results.put(num, stepResult); } } else if (NodeDispatchStepExecutor.isWrappedDispatcherException(executionResult)) { DispatcherException exception = NodeDispatchStepExecutor.extractDispatcherException(executionResult); NodeStepException nodeStepException = exception.getNodeStepException(); if (null != nodeStepException) { results.put( num, nodeStepResultFromNodeStepException(node, nodeStepException) ); } } } return results; } } /** * Splits a workflow into a sequence of sub-workflows, separated along boundaries of node-dispatch sets. */ private List<IWorkflow> splitWorkflowDispatchedSections(IWorkflow workflow) throws ExecutionServiceException { ArrayList<StepExecutionItem> dispatchItems = new ArrayList<>(); ArrayList<IWorkflow> sections = new ArrayList<>(); for (final StepExecutionItem item : workflow.getCommands()) { StepExecutor executor = getFramework().getStepExecutionService().getExecutorForItem(item); if (executor.isNodeDispatchStep(item)) { dispatchItems.add(item); } else { if (dispatchItems.size() > 0) { //add workflow section sections.add(new WorkflowImpl(dispatchItems, workflow.getThreadcount(), workflow.isKeepgoing(), workflow.getStrategy())); dispatchItems = new ArrayList<>(); } sections.add(new WorkflowImpl(Collections.singletonList(item), workflow.getThreadcount(), workflow.isKeepgoing(), workflow.getStrategy())); } } if (null != dispatchItems && dispatchItems.size() > 0) { //add workflow section sections.add(new WorkflowImpl(dispatchItems, workflow.getThreadcount(), workflow.isKeepgoing(), workflow.getStrategy())); } return sections; } /** * Create workflowExecutionItem suitable for inner loop of node-first strategy * @param item workflow item * @return inner loop */ public static WorkflowExecutionItem createInnerLoopItem(IWorkflow item) { return new WorkflowExecutionItemImpl(new StepFirstWrapper(item)); } }
package ch.epfl.sweng.swissaffinity.gui; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.Arrays; import java.util.List; import ch.epfl.sweng.swissaffinity.EventActivity; import ch.epfl.sweng.swissaffinity.MainActivity; import ch.epfl.sweng.swissaffinity.R; import ch.epfl.sweng.swissaffinity.events.Event; import ch.epfl.sweng.swissaffinity.utilities.parsers.DateParser; /** * Representation of an expandable list adapter for the events. */ public class EventExpandableListAdapter extends AbstractExpandableListAdapter<String, Event> { /** * Constructor of the class. * * @param context the context {@link Context} */ public EventExpandableListAdapter(Context context) { super(context); } @Override public View getGroupView( int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String title = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(mContext); convertView = inflater.inflate(R.layout.list_group, parent, false); } TextView textView = (TextView) convertView.findViewById(R.id.groupEvents); textView.setText(title); return convertView; } @Override public View getChildView( int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final Event event = (Event) getChild(groupPosition, childPosition); if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(mContext); convertView = inflater.inflate(R.layout.list_item, parent, false); } convertView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), EventActivity.class); intent.putExtra(MainActivity.EXTRA_EVENT, event.getId()); v.getContext().startActivity(intent); } }); String name = event.getName(); String location = event.getLocation().getName(); String dateBegin = DateParser.dateToString(event.getDateBegin()); ((TextView) convertView.findViewById(R.id.rowEventName)).setText(name); ((TextView) convertView.findViewById(R.id.rowEventLocation)).setText(location); ((TextView) convertView.findViewById(R.id.rowEventDateBegin)).setText(dateBegin); return convertView; } public void setData(List<List<Event>> children) { if (children == null || children.size() > 2) { throw new IllegalArgumentException(); } super.setData(getGroups(), children); } private List<String> getGroups() { String myEvents = mContext.getString(R.string.my_events); String upcomingEvents = mContext.getString(R.string.upcoming_events); return Arrays.asList(myEvents, upcomingEvents); } }
package physique; public class Collision { private final Physique source, cible; public Collision(Physique source, Physique cible) { this.source = source; this.cible = cible; } public Physique getSource() { return source; } public Physique getCible() { return cible; } @Override public String toString() { return "Collision entre " + source + " et " + cible; } }