answer
stringlengths
17
10.2M
package retrofit.http; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpUriRequest; import javax.inject.Provider; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; /** * Converts Java method calls to Rest calls. * * @author Bob Lee (bob@squareup.com) */ public class RestAdapter { private static final Logger LOGGER = Logger.getLogger(RestAdapter.class.getName()); static final ThreadLocal<DateFormat> DATE_FORMAT = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("HH:mm:ss"); } }; private final Server server; private final Provider<HttpClient> httpClientProvider; private final Executor executor; private final MainThread mainThread; private final Headers headers; private final Converter converter; private final HttpProfiler profiler; public RestAdapter(Server server, Provider<HttpClient> httpClientProvider, Executor executor, MainThread mainThread, Headers headers, Converter converter, HttpProfiler profiler) { this.server = server; this.httpClientProvider = httpClientProvider; this.executor = executor; this.mainThread = mainThread; this.headers = headers; this.converter = converter; this.profiler = profiler; } /** * Adapts a Java interface to a REST API. HTTP requests happen in a background thread. Callbacks * happen in the UI thread. * * <p>Gets the relative path for a given method from a {@link GET}, {@link POST}, {@link PUT}, or * {@link DELETE} annotation on the method. Gets the names of URL parameters from {@link * javax.inject.Named} annotations on the method parameters. * * <p>The last method parameter should be of type {@link Callback}. The JSON HTTP response will be * converted to the callback's parameter type using GSON. If the callback parameter type uses a * wildcard, the lower bound will be used as the conversion type. * * <p>For example: * * <pre> * public interface MyApi { * &#64;POST("go") public void go(@Named("a") String a, @Named("b") int b, * Callback&lt;? super MyResult> callback); * } * </pre> * * @param type to implement */ @SuppressWarnings("unchecked") public <T> T create(Class<T> type) { return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, new RestHandler()); } private class RestHandler implements InvocationHandler { private final Map<Method, Type> responseTypeCache = new HashMap<Method, Type>(); @Override public Object invoke(Object proxy, final Method method, final Object[] args) { // Determine whether or not the execution will be synchronous. boolean isSynchronousInvocation = methodWantsSynchronousInvocation(method); if (isSynchronousInvocation) { // TODO support synchronous invocations! throw new UnsupportedOperationException("Synchronous invocation not supported."); } // Construct HTTP request. final Callback<?> callback = UiCallback.create((Callback<?>) args[args.length - 1], mainThread); String url = server.apiUrl(); String startTime = "NULL"; try { // Build the request and headers. final HttpUriRequest request = new HttpRequestBuilder(converter) .setMethod(method) .setArgs(args) .setApiUrl(server.apiUrl()) .setHeaders(headers) .build(); url = request.getURI().toString(); // Determine deserialization type by method return type or generic parameter to Callback argument. Type type = responseTypeCache.get(method); if (type == null) { type = getResponseObjectType(method, isSynchronousInvocation); responseTypeCache.put(method, type); } LOGGER.fine("Sending " + request.getMethod() + " to " + request.getURI()); final Date start = new Date(); startTime = DATE_FORMAT.get().format(start); ResponseHandler<Void> rh = new CallbackResponseHandler(callback, type, converter, url, start, DATE_FORMAT); // Optionally wrap the response handler for server call profiling. if (profiler != HttpProfiler.NONE) { rh = createProfiler(rh, (HttpProfiler<?>) profiler, getRequestInfo(method, request), start); } // Execute HTTP request in the background. final String finalUrl = url; final String finalStartTime = startTime; final ResponseHandler<Void> finalResponseHandler = rh; executor.execute(new Runnable() { @Override public void run() { invokeRequest(request, finalResponseHandler, callback, finalUrl, finalStartTime); } }); } catch (Throwable t) { LOGGER.log(Level.WARNING, t.getMessage() + " from " + url + " at " + startTime, t); callback.unexpectedError(t); } // Methods should return void. return null; } private HttpProfiler.RequestInformation getRequestInfo(Method method, HttpUriRequest request) { RequestLine requestLine = RequestLine.fromMethod(method); HttpMethodType httpMethod = requestLine.getHttpMethod(); HttpProfiler.Method profilerMethod = httpMethod.profilerMethod(); long contentLength = 0; String contentType = null; if (request instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityReq = (HttpEntityEnclosingRequestBase) request; HttpEntity entity = entityReq.getEntity(); contentLength = entity.getContentLength(); Header entityContentType = entity.getContentType(); contentType = entityContentType != null ? entityContentType.getValue() : null; } return new HttpProfiler.RequestInformation(profilerMethod, server.apiUrl(), requestLine.getRelativePath(), contentLength, contentType); } private void invokeRequest(HttpUriRequest request, ResponseHandler<Void> rh, Callback<?> callback, String url, String startTime) { try { httpClientProvider.get().execute(request, rh); } catch (IOException e) { LOGGER.log(Level.WARNING, e.getMessage() + " from " + url + " at " + startTime, e); callback.networkError(); } catch (Throwable t) { LOGGER.log(Level.WARNING, t.getMessage() + " from " + url + " at " + startTime, t); callback.unexpectedError(t); } } /** Wraps a {@code GsonResponseHandler} with a {@code ProfilingResponseHandler}. */ private <T> ProfilingResponseHandler<T> createProfiler(ResponseHandler<Void> handlerToWrap, HttpProfiler<T> profiler, HttpProfiler.RequestInformation requestInfo, Date start) { ProfilingResponseHandler<T> responseHandler = new ProfilingResponseHandler<T>(handlerToWrap, profiler, requestInfo, start.getTime()); responseHandler.beforeCall(); return responseHandler; } } static boolean methodWantsSynchronousInvocation(Method method) { boolean hasReturnType = method.getReturnType() != void.class; Class<?>[] parameterTypes = method.getParameterTypes(); boolean hasCallback = parameterTypes.length > 0 && Callback.class.isAssignableFrom(parameterTypes[parameterTypes.length - 1]); if ((hasReturnType && hasCallback) || (!hasReturnType && !hasCallback)) { throw new IllegalArgumentException("Method must have either a return type or Callback as last argument."); } return hasReturnType; } /** Get the callback parameter types. */ static Type getResponseObjectType(Method method, boolean isSynchronousInvocation) { if (isSynchronousInvocation) { return method.getGenericReturnType(); } Type[] parameterTypes = method.getGenericParameterTypes(); Type callbackType = parameterTypes[parameterTypes.length - 1]; Class<?> callbackClass; if (callbackType instanceof Class) { callbackClass = (Class<?>) callbackType; } else if (callbackType instanceof ParameterizedType) { callbackClass = (Class<?>) ((ParameterizedType) callbackType).getRawType(); } else { throw new ClassCastException( String.format("Last parameter of %s must be a Class or ParameterizedType", method)); } if (Callback.class.isAssignableFrom(callbackClass)) { callbackType = Types.getGenericSupertype(callbackType, callbackClass, Callback.class); if (callbackType instanceof ParameterizedType) { Type[] types = ((ParameterizedType) callbackType).getActualTypeArguments(); for (int i = 0; i < types.length; i++) { Type type = types[i]; if (type instanceof WildcardType) { types[i] = ((WildcardType) type).getUpperBounds()[0]; } } return types[0]; } } throw new IllegalArgumentException( String.format("Last parameter of %s must be of type Callback<X,Y,Z> or Callback<? super X,..,..>.", method)); } /** Sends server call times and response status codes to {@link HttpProfiler}. */ private static class ProfilingResponseHandler<T> implements ResponseHandler<Void> { private final ResponseHandler<Void> delegate; private final HttpProfiler<T> profiler; private final HttpProfiler.RequestInformation requestInfo; private final long startTime; private final AtomicReference<T> beforeCallData = new AtomicReference<T>(); /** Wraps the delegate response handler. */ private ProfilingResponseHandler(ResponseHandler<Void> delegate, HttpProfiler<T> profiler, HttpProfiler.RequestInformation requestInfo, long startTime) { this.delegate = delegate; this.profiler = profiler; this.requestInfo = requestInfo; this.startTime = startTime; } public void beforeCall() { try { beforeCallData.set(profiler.beforeCall()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error occurred in HTTP profiler beforeCall().", e); } } @Override public Void handleResponse(HttpResponse httpResponse) throws IOException { // Intercept the response and send data to profiler. long elapsedTime = System.currentTimeMillis() - startTime; int statusCode = httpResponse.getStatusLine().getStatusCode(); try { profiler.afterCall(requestInfo, elapsedTime, statusCode, beforeCallData.get()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error occurred in HTTP profiler afterCall().", e); } // Pass along the response to the normal handler. return delegate.handleResponse(httpResponse); } } }
package com.dx168.patchserver.manager.service; import com.dx168.patchserver.core.domain.Tester; import com.dx168.patchserver.core.utils.StreamUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.util.DigestUtils; import org.springframework.web.multipart.MultipartFile; import com.dx168.patchserver.core.domain.AppInfo; import com.dx168.patchserver.core.domain.PatchInfo; import com.dx168.patchserver.core.domain.VersionInfo; import com.dx168.patchserver.core.mapper.PatchInfoMapper; import com.dx168.patchserver.core.utils.BizException; import javax.mail.*; import javax.mail.internet.MimeMessage; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @Service public class PatchService { private static final Logger LOG = LoggerFactory.getLogger(FacadeService.class); @Value("${file_storage_path}") private String fileStoragePath; @Value("${patch-static-url}") private String patchStaticUrl; @Value("${tm-manager-url}") private String managerUrl; @Autowired private PatchInfoMapper patchInfoMapper; @Autowired private AppService appService; @Autowired private FacadeService facadeService; @Autowired private TesterService testerService; @Autowired private AccountService accountService; @Autowired private JavaMailSender javaMailSender; private ExecutorService executorService = Executors.newFixedThreadPool(20); public List<PatchInfo> findByUidAndVersionName(String appUid,String versionName) { return patchInfoMapper.findByUidAndVersionName(appUid,versionName); } public PatchInfo savePatch(AppInfo appInfo, VersionInfo versionInfo, String description, MultipartFile multipartFile) { List<PatchInfo> patchInfoList = patchInfoMapper.findByUidAndVersionName(appInfo.getUid(),versionInfo.getVersionName()); int maxPatchVersion = getMaxPatchVersion(patchInfoList) + 1; String childPath = appInfo.getUid() + "/" + versionInfo.getVersionName() + "/" + maxPatchVersion + "/"; PatchInfo patchInfo = new PatchInfo(); try { String fileHash = DigestUtils.md5DigestAsHex(multipartFile.getBytes()); File path = new File(new File(fileStoragePath), childPath); File tmpPatchFile = new File(path,fileHash + "_patch.tmp.zip"); File patchFile = null; String fileHashJiagu = fileHash; File patchFileJiagu = null; if (!path.exists() && !path.mkdirs()) { throw new BizException(""); } multipartFile.transferTo(tmpPatchFile); ZipFile zipFile = new ZipFile(tmpPatchFile); ZipEntry entry = zipFile.getEntry("FULL_PATCH"); if (entry == null) { patchFile = new File(path,fileHash + "_patch.zip"); if (!tmpPatchFile.renameTo(patchFile)) { if (tmpPatchFile.exists()) { tmpPatchFile.delete(); } throw new BizException(""); } } else { //patch.zip entry = zipFile.getEntry("patch.apk"); if (entry == null) { throw new BizException(""); } InputStream inputStream = null; try { inputStream = zipFile.getInputStream(entry); byte[] bytes = StreamUtil.readStream(inputStream); fileHash = DigestUtils.md5DigestAsHex(bytes); patchFile = new File(path,fileHash + "_patch.zip"); StreamUtil.writeTo(bytes,patchFile); patchFileJiagu = new File(path,fileHashJiagu + "_patch_jiagu.zip"); if (!tmpPatchFile.renameTo(patchFileJiagu)) { if (tmpPatchFile.exists()) { tmpPatchFile.delete(); } throw new BizException(""); } } finally { if (inputStream != null) { inputStream.close(); } } } zipFile.close(); patchInfo.setUserId(appInfo.getUserId()); patchInfo.setAppUid(appInfo.getUid()); patchInfo.setUid(UUID.randomUUID().toString().replaceAll("-", "")); patchInfo.setVersionName(versionInfo.getVersionName()); patchInfo.setPatchVersion(maxPatchVersion); patchInfo.setPatchSize(patchFile.length()); patchInfo.setFileHash(fileHash); patchInfo.setDescription(description); patchInfo.setStoragePath(patchFile.getAbsolutePath()); patchInfo.setDownloadUrl(getDownloadUrl(patchStaticUrl,childPath + patchFile.getName())); if (patchFileJiagu != null) { patchInfo.setFileHashJiagu(fileHashJiagu); patchInfo.setPatchSizeJiagu(patchFileJiagu.length()); patchInfo.setDownloadUrlJiagu(getDownloadUrl(patchStaticUrl,childPath + patchFileJiagu.getName())); } patchInfo.setCreatedAt(new Date()); patchInfo.setUpdatedAt(new Date()); Integer id = patchInfoMapper.insert(patchInfo); patchInfo.setId(id); } catch (IOException e) { e.printStackTrace(); throw new BizException(""); } facadeService.clearCache(); return patchInfo; } private String getDownloadUrl(String patchStaticUrl, String rel) { if (!patchStaticUrl.endsWith("/") && !rel.startsWith("/")) { patchStaticUrl = patchStaticUrl + "/"; } return patchStaticUrl + rel; } private int getMaxPatchVersion(List<PatchInfo> patchInfoList) { int result = 0; if (patchInfoList != null) { for (PatchInfo patchInfo : patchInfoList) { if (patchInfo.getPatchVersion() > result) { result = patchInfo.getPatchVersion(); } } } return result; } public PatchInfo findByIdAndAppUid(Integer id, String appUid) { return patchInfoMapper.findByIdAndAppUid(id,appUid); } public void updateStatus(final PatchInfo patchInfo) { final PatchInfo oldInfo = patchInfoMapper.findById(patchInfo.getId()); patchInfo.setUpdatedAt(new Date()); patchInfoMapper.updateStatus(patchInfo); executorService.submit(new Runnable() { @Override public void run() { try { notifyPatchStatusChanged(oldInfo,patchInfo); } catch (Throwable e) { LOG.error(": " + e.getMessage()); } } }); } private void notifyPatchStatusChanged(PatchInfo oldInfo, PatchInfo patchInfo) { //facade facadeService.clearCache(); if (patchInfo.getTags() == null) { return; } List<Tester> testerList = null; try { testerList = testerService.findAllByAppUid(patchInfo.getAppUid()); } catch (Throwable e) { e.printStackTrace(); } if (testerList == null || testerList.isEmpty()) { return; } List<String> emailList = new ArrayList<>(); for (Tester tester : testerList) { if (patchInfo.getTags().contains(tester.getTag())) { emailList.add(tester.getEmail()); } } if (emailList.isEmpty()) { return; } AppInfo appInfo = appService.findByUid(patchInfo.getAppUid()); String[] sendTo = new String[emailList.size()]; for (int i = 0; i < emailList.size(); i++) { sendTo[i] = emailList.get(i); } StringBuilder sb = new StringBuilder(); sb.append(": " + appInfo.getAppname()); sb.append("\n"); sb.append(": " + patchInfo.getVersionName()); sb.append("\n"); sb.append(": " + patchInfo.getPatchVersion()); sb.append("\n"); sb.append(": " + patchInfo.getDescription()); sb.append("\n"); sb.append(": " + oldInfo.getStatusDesc() + " => " + patchInfo.getStatusDesc()); sb.append("\n"); if (patchInfo.getStatus() != PatchInfo.STATUS_UNPUBLISHED) { sb.append(": " + patchInfo.getPublishTypeDesc()); sb.append("\n"); } sb.append(": " + accountService.findById(patchInfo.getUserId()).getUsername()); sb.append("\n"); sb.append(": " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); sb.append("\n"); sb.append(managerUrl); try { MimeMessage mail = javaMailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(mail, true); helper.setTo(sendTo); helper.setSubject("[Tinker-]-"); helper.setText(sb.toString()); } catch (MessagingException e) { e.printStackTrace(); } javaMailSender.send(mail); } catch (Throwable e) { e.printStackTrace(); } //TODO patch } public void deletePatch(PatchInfo patchInfo) { patchInfoMapper.deleteById(patchInfo.getId()); // File file = new File(patchInfo.getStoragePath()); // try { // file.delete(); // } catch (Exception e) { facadeService.clearCache(); } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.crowd.chat.client; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.samskivert.util.Collections; import com.samskivert.util.HashIntMap; import com.samskivert.util.ObserverList; import com.samskivert.util.ResultListener; import com.samskivert.util.StringUtil; import com.threerings.presents.client.BasicDirector; import com.threerings.presents.client.Client; import com.threerings.presents.data.ClientObject; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.MessageEvent; import com.threerings.presents.dobj.MessageListener; import com.threerings.util.MessageBundle; import com.threerings.util.MessageManager; import com.threerings.util.Name; import com.threerings.util.TimeUtil; import com.threerings.crowd.Log; import com.threerings.crowd.client.LocationObserver; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.crowd.chat.data.ChatMessage; import com.threerings.crowd.chat.data.SystemMessage; import com.threerings.crowd.chat.data.TellFeedbackMessage; import com.threerings.crowd.chat.data.UserMessage; /** * The chat director is the client side coordinator of all chat related * services. It handles both place constrained chat as well as direct * messaging. */ public class ChatDirector extends BasicDirector implements ChatCodes, LocationObserver, MessageListener { /** * An interface to receive information about the {@link #MAX_CHATTERS} * most recent users that we've been chatting with. */ public static interface ChatterObserver { /** * Called when the list of chatters has been changed. */ public void chattersUpdated (Iterator chatternames); } /** * An interface for those who would like to validate whether usernames * may be added to the chatter list. */ public static interface ChatterValidator { /** * Returns whether the username may be added to the chatters list. */ public boolean isChatterValid (Name username); } /** * Used to implement a slash command (e.g. <code>/who</code>). */ public static abstract class CommandHandler { /** * Handles the specified chat command. * * @param speakSvc an optional SpeakService object representing * the object to send the chat message on. * @param command the slash command that was used to invoke this * handler (e.g. <code>/tell</code>). * @param args the arguments provided along with the command (e.g. * <code>Bob hello</code>) or <code>null</code> if no arguments * were supplied. * @param history an in/out parameter that allows the command to * modify the text that will be appended to the chat history. If * this is set to null, nothing will be appended. * * @return an untranslated string that will be reported to the * chat box to convey an error response to the user, or {@link * ChatCodes#SUCCESS}. */ public abstract String handleCommand ( SpeakService speakSvc, String command, String args, String[] history); /** * Returns true if this user should have access to this chat * command. */ public boolean checkAccess (BodyObject user) { return true; } } /** * Creates a chat director and initializes it with the supplied * context. The chat director will register itself as a location * observer so that it can automatically process place constrained * chat. * * @param msgmgr the message manager via which we do our translations. * @param bundle the message bundle from which we obtain our * chat-related translation strings. */ public ChatDirector (CrowdContext ctx, MessageManager msgmgr, String bundle) { super(ctx); // keep the context around _ctx = ctx; _msgmgr = msgmgr; _bundle = bundle; // register ourselves as a location observer _ctx.getLocationDirector().addLocationObserver(this); // register our default chat handlers MessageBundle msg = _msgmgr.getBundle(_bundle); registerCommandHandler(msg, "help", new HelpHandler()); registerCommandHandler(msg, "clear", new ClearHandler()); registerCommandHandler(msg, "speak", new SpeakHandler()); registerCommandHandler(msg, "emote", new EmoteHandler()); registerCommandHandler(msg, "think", new ThinkHandler()); } /** * Adds the supplied chat display to the chat display list. It will * subsequently be notified of incoming chat messages as well as tell * responses. */ public void addChatDisplay (ChatDisplay display) { _displays.add(display); } /** * Removes the specified chat display from the chat display list. The * display will no longer receive chat related notifications. */ public void removeChatDisplay (ChatDisplay display) { _displays.remove(display); } /** * Adds the specified chat filter to the list of filters. All * chat requests and receipts will be filtered with all filters * before they being sent or dispatched locally. */ public void addChatFilter (ChatFilter filter) { _filters.add(filter); } /** * Removes the specified chat validator from the list of chat validators. */ public void removeChatFilter (ChatFilter filter) { _filters.remove(filter); } /** * Adds an observer that watches the chatters list, and updates it * immediately. */ public void addChatterObserver (ChatterObserver co) { _chatterObservers.add(co); co.chattersUpdated(_chatters.listIterator()); } /** * Removes an observer from the list of chatter observers. */ public void removeChatterObserver (ChatterObserver co) { _chatterObservers.remove(co); } /** * Sets the validator that decides if a username is valid to be * added to the chatter list, or null if no such filtering is desired. */ public void setChatterValidator (ChatterValidator validator) { _chatterValidator = validator; } /** * Registers a chat command handler. * * @param msg the message bundle via which the slash command will be * translated (as <code>c.</code><i>command</i>). If no translation * exists the command will be <code>/</code><i>command</i>. * @param command the name of the command that will be used to invoke * this handler (e.g. <code>tell</code> if the command will be invoked * as <code>/tell</code>). * @param handler the chat command handler itself. */ public void registerCommandHandler ( MessageBundle msg, String command, CommandHandler handler) { String key = "c." + command; if (msg.exists(key)) { StringTokenizer st = new StringTokenizer(msg.get(key)); while (st.hasMoreTokens()) { _handlers.put(st.nextToken(), handler); } } else { // fall back to just using the English command _handlers.put(command, handler); } } /** * Return the current size of the history. */ public int getCommandHistorySize () { return _history.size(); } /** * Get the chat history entry at the specified index, * with 0 being the oldest. */ public String getCommandHistory (int index) { return (String)_history.get(index); } /** * Clear the chat command history. */ public void clearCommandHistory () { _history.clear(); } /** * Requests that all chat displays clear their contents. */ public void clearDisplays () { _displays.apply(new ObserverList.ObserverOp() { public boolean apply (Object observer) { ((ChatDisplay)observer).clear(); return true; } }); } /** * Display a system INFO message as if it had come from the server. * The localtype of the message will be PLACE_CHAT_TYPE. * * Info messages are sent when something happens that was neither * directly triggered by the user, nor requires direct action. */ public void displayInfo (String bundle, String message) { displaySystem(bundle, message, SystemMessage.INFO, PLACE_CHAT_TYPE); } /** * Display a system INFO message as if it had come from the server. * * Info messages are sent when something happens that was neither * directly triggered by the user, nor requires direct action. */ public void displayInfo (String bundle, String message, String localtype) { displaySystem(bundle, message, SystemMessage.INFO, localtype); } /** * Display a system FEEDBACK message as if it had come from the server. * The localtype of the message will be PLACE_CHAT_TYPE. * * Feedback messages are sent in direct response to a user action, * usually to indicate success or failure of the user's action. */ public void displayFeedback (String bundle, String message) { displaySystem( bundle, message, SystemMessage.FEEDBACK, PLACE_CHAT_TYPE); } /** * Display a system ATTENTION message as if it had come from the server. * The localtype of the message will be PLACE_CHAT_TYPE. * * Attention messages are sent when something requires user action * that did not result from direct action by the user. */ public void displayAttention (String bundle, String message) { displaySystem( bundle, message, SystemMessage.ATTENTION, PLACE_CHAT_TYPE); } /** * Dispatches the provided message to our chat displays. */ public void dispatchMessage (ChatMessage message) { _displayMessageOp.setMessage(message); _displays.apply(_displayMessageOp); } /** * Parses and delivers the supplied chat message. Slash command * processing and mogrification are performed and the message is added * to the chat history if appropriate. * * @param speakSvc the SpeakService representing the target dobj of * the speak or null if we should speak in the "default" way. * @param text the text to be parsed and sent. * @param record if text is a command, should it be added to the history? * * @return <code>ChatCodes#SUCCESS</code> if the message was parsed * and sent correctly, a translatable error string if there was some * problem. */ public String requestChat ( SpeakService speakSvc, String text, boolean record) { if (text.startsWith("/")) { // split the text up into a command and arguments String command = text.substring(1).toLowerCase(); String[] hist = new String[1]; String args = ""; int sidx = text.indexOf(" "); if (sidx != -1) { command = text.substring(1, sidx).toLowerCase(); args = text.substring(sidx+1).trim(); } HashMap possibleCommands = getCommandHandlers(command); switch (possibleCommands.size()) { case 0: StringTokenizer tok = new StringTokenizer(text); return MessageBundle.tcompose( "m.unknown_command", tok.nextToken()); case 1: Iterator itr = possibleCommands.entrySet().iterator(); Map.Entry entry = (Map.Entry) itr.next(); String cmdName = (String) entry.getKey(); CommandHandler cmd = (CommandHandler) entry.getValue(); String result = cmd.handleCommand(speakSvc, cmdName, args, hist); if (!result.equals(ChatCodes.SUCCESS)) { return result; } if (record) { // get the final history-ready command string hist[0] = "/" + ((hist[0] == null) ? command : hist[0]); // remove from history if it was present and // add it to the end addToHistory(hist[0]); } return result; default: String alternativeCommands = ""; itr = Collections.getSortedIterator(possibleCommands.keySet()); while (itr.hasNext()) { cmdName = (String)itr.next(); alternativeCommands += " /" + cmdName; } return MessageBundle.tcompose( "m.unspecific_command", alternativeCommands); } } // if not a command then just speak String message = text.trim(); if (StringUtil.blank(message)) { // report silent failure for now return ChatCodes.SUCCESS; } return deliverChat(speakSvc, message, ChatCodes.DEFAULT_MODE); } /** * Requests that a speak message with the specified mode be generated * and delivered via the supplied speak service instance (which will * be associated with a particular "speak object"). The message will * first be validated by all registered {@link ChatFilter}s (and * possibly vetoed) before being dispatched. * * @param speakService the speak service to use when generating the * speak request or null if we should speak in the current "place". * @param message the contents of the speak message. * @param mode a speech mode that will be interpreted by the {@link * ChatDisplay} implementations that eventually display this speak * message. */ public void requestSpeak ( SpeakService speakService, String message, byte mode) { if (speakService == null) { if (_place == null) { return; } speakService = _place.speakService; } // make sure they can say what they want to say message = filter(message, null, true); if (message == null) { return; } // dispatch a speak request using the supplied speak service speakService.speak(_ctx.getClient(), message, mode); } /** * Requests to send a site-wide broadcast message. * * @param message the contents of the message. */ public void requestBroadcast (String message) { message = filter(message, null, true); if (message == null) { displayFeedback(_bundle, MessageBundle.compose("m.broadcast_failed", "m.filtered")); return; } _cservice.broadcast( _ctx.getClient(), message, new ChatService.InvocationListener() { public void requestFailed (String reason) { reason = MessageBundle.compose( "m.broadcast_failed", reason); displayFeedback(_bundle, reason); } }); } /** * Requests that a tell message be delivered to the specified target * user. * * @param target the username of the user to which the tell message * should be delivered. * @param msg the contents of the tell message. * @param rl an optional result listener if you'd like to be notified * of success or failure. */ public void requestTell (final Name target, String msg, final ResultListener rl) { // make sure they can say what they want to say final String message = filter(msg, target, true); if (message == null) { if (rl != null) { rl.requestFailed(null); } return; } // create a listener that will report success or failure ChatService.TellListener listener = new ChatService.TellListener() { public void tellSucceeded (long idletime, String awayMessage) { success(xlate(_bundle, MessageBundle.tcompose( "m.told_format", target, message))); // if they have an away message, report that if (awayMessage != null) { awayMessage = filter(awayMessage, target, false); if (awayMessage != null) { String msg = MessageBundle.tcompose( "m.recipient_afk", target, awayMessage); displayFeedback(_bundle, msg); } } // if they are idle, report that if (idletime > 0L) { // adjust by the time it took them to become idle idletime += _ctx.getConfig().getValue( IDLE_TIME_KEY, DEFAULT_IDLE_TIME); String msg = MessageBundle.compose( "m.recipient_idle", MessageBundle.taint(target), TimeUtil.getTimeOrderString(idletime, TimeUtil.MINUTE)); displayFeedback(_bundle, msg); } } protected void success (String feedback) { dispatchMessage(new TellFeedbackMessage(feedback)); addChatter(target); if (rl != null) { rl.requestCompleted(target); } } public void requestFailed (String reason) { String msg = MessageBundle.compose( "m.tell_failed", MessageBundle.taint(target), reason); displayFeedback(_bundle, msg); if (rl != null) { rl.requestFailed(null); } } }; _cservice.tell(_ctx.getClient(), target, message, listener); } /** * Configures a message that will be automatically reported to anyone * that sends a tell message to this client to indicate that we are * busy or away from the keyboard. */ public void setAwayMessage (String message) { if (message != null) { message = filter(message, null, true); if (message == null) { // they filtered away their own away message.. // change it to something message = "..."; } } // pass the buck right on along _cservice.away(_ctx.getClient(), message); } /** * Adds an additional object via which chat messages may arrive. The * chat director assumes the caller will be managing the subscription * to this object and will remain subscribed to it for as long as it * remains in effect as an auxiliary chat source. * * @param localtype a type to be associated with all chat messages * that arrive on the specified DObject. */ public void addAuxiliarySource (DObject source, String localtype) { source.addListener(this); _auxes.put(source.getOid(), localtype); } /** * Removes a previously added auxiliary chat source. */ public void removeAuxiliarySource (DObject source) { source.removeListener(this); _auxes.remove(source.getOid()); } /** * Run a message through all the currently registered filters. */ public String filter (String msg, Name otherUser, boolean outgoing) { _filterMessageOp.setMessage(msg, otherUser, outgoing); _filters.apply(_filterMessageOp); return _filterMessageOp.getMessage(); } /** * Runs the supplied message through the various chat mogrifications. */ public String mogrifyChat (String text) { return mogrifyChat(text, false, true); } // documentation inherited public boolean locationMayChange (int placeId) { // we accept all location change requests return true; } // documentation inherited public void locationDidChange (PlaceObject place) { if (_place != null) { // unlisten to our old object _place.removeListener(this); } // listen to the new object _place = place; if (_place != null) { _place.addListener(this); } } // documentation inherited public void locationChangeFailed (int placeId, String reason) { // nothing we care about } // documentation inherited public void messageReceived (MessageEvent event) { if (CHAT_NOTIFICATION.equals(event.getName())) { ChatMessage msg = (ChatMessage) event.getArgs()[0]; String localtype = getLocalType(event.getTargetOid()); String message = msg.message; String autoResponse = null; // if the message came from a user, make sure we want to hear it if (msg instanceof UserMessage) { UserMessage umsg = (UserMessage)msg; Name speaker = umsg.speaker; if ((message = filter(message, speaker, false)) == null) { return; } if (USER_CHAT_TYPE.equals(localtype) && umsg.mode == ChatCodes.DEFAULT_MODE) { // if it was a tell, add the speaker as a chatter addChatter(speaker); // note whether or not we have an auto-response BodyObject self = (BodyObject) _ctx.getClient().getClientObject(); if (!StringUtil.blank(self.awayMessage)) { autoResponse = self.awayMessage; } } } // initialize the client-specific fields of the message msg.setClientInfo(xlate(msg.bundle, message), localtype); // and send it off! dispatchMessage(msg); // if we auto-responded, report as much if (autoResponse != null) { Name teller = ((UserMessage) msg).speaker; String amsg = MessageBundle.tcompose( "m.auto_responded", teller, autoResponse); displayFeedback(_bundle, amsg); } } } // documentation inherited public void clientDidLogon (Client client) { super.clientDidLogon(client); // listen on the client object for tells addAuxiliarySource(_clobj = client.getClientObject(), USER_CHAT_TYPE); } // documentation inherited public void clientObjectDidChange (Client client) { super.clientObjectDidChange(client); // change what we're listening to for tells removeAuxiliarySource(_clobj); addAuxiliarySource(_clobj = client.getClientObject(), USER_CHAT_TYPE); clearDisplays(); } // documentation inherited public void clientDidLogoff (Client client) { super.clientDidLogoff(client); // stop listening to it for tells if (_clobj != null) { removeAuxiliarySource(_clobj); _clobj = null; } // in fact, clear out all auxiliary sources _auxes.clear(); clearDisplays(); // clear out the list of people we've chatted with _chatters.clear(); notifyChatterObservers(); // clear the _place locationDidChange(null); // clear our service _cservice = null; } /** * Called to determine whether we are permitted to post the supplied * chat message. Derived classes may wish to throttle chat or restrict * certain types in certain circumstances for whatever reason. * * @return null if the chat is permitted, SUCCESS if the chat is permitted * and has already been dealt with, or a translatable string * indicating the reason for rejection if not. */ protected String checkCanChat ( SpeakService speakSvc, String message, byte mode) { return null; } /** * Delivers a plain chat message (not a slash command) on the * specified speak service in the specified mode. The message will be * mogrified and filtered prior to delivery. * * @return {@link ChatCodes#SUCCESS} if the message was delivered or a * string indicating why it failed. */ protected String deliverChat ( SpeakService speakSvc, String message, byte mode) { // run the message through our mogrification process message = mogrifyChat(message, true, mode != ChatCodes.EMOTE_MODE); // mogrification may result in something being turned into a slash // command, in which case we have to run everything through again // from the start if (message.startsWith("/")) { return requestChat(speakSvc, message, false); } // make sure this client is not restricted from performing this // chat message for some reason or other String errmsg = checkCanChat(speakSvc, message, mode); if (errmsg != null) { return errmsg; } // speak on the specified service requestSpeak(speakSvc, message, mode); return ChatCodes.SUCCESS; } /** * Add the specified command to the history. */ protected void addToHistory (String cmd) { // remove any previous instance of this command _history.remove(cmd); // append it to the end _history.add(cmd); // prune the history once it extends beyond max size if (_history.size() > MAX_COMMAND_HISTORY) { _history.remove(0); } } /** * Mogrify common literary crutches into more appealing chat or * commands. * * @param transformsAllowed if true, the chat may transformed into a * different mode. (lol -> /emote laughs) * @param capFirst if true, the first letter of the text is * capitalized. This is not desired if the chat is already an emote. */ protected String mogrifyChat ( String text, boolean transformsAllowed, boolean capFirst) { int tlen = text.length(); if (tlen == 0) { return text; // check to make sure there aren't too many caps } else if (tlen > 7) { // count caps int caps = 0; for (int ii=0; ii < tlen; ii++) { if (Character.isUpperCase(text.charAt(ii))) { caps++; if (caps > (tlen / 2)) { // lowercase the whole string if there are text = text.toLowerCase(); break; } } } } StringBuffer buf = new StringBuffer(text); buf = mogrifyChat(buf, transformsAllowed, capFirst); return buf.toString(); } /** Helper function for {@link #mogrifyChat}. */ protected StringBuffer mogrifyChat ( StringBuffer buf, boolean transformsAllowed, boolean capFirst) { // do the generic mogrifications and translations buf = translatedReplacements("x.mogrifies", buf); // perform themed expansions and transformations if (transformsAllowed) { buf = translatedReplacements("x.transforms", buf); } /* // capitalize the first letter if (capFirst) { buf.setCharAt(0, Character.toUpperCase(buf.charAt(0))); } // and capitalize any letters after a sentence-ending punctuation Pattern p = Pattern.compile("([^\\.][\\.\\?\\!](\\s)+\\p{Ll})"); Matcher m = p.matcher(buf); if (m.find()) { buf = new StringBuffer(); m.appendReplacement(buf, m.group().toUpperCase()); while (m.find()) { m.appendReplacement(buf, m.group().toUpperCase()); } m.appendTail(buf); } */ return buf; } /** * Do all the replacements (mogrifications) specified in the * translation string specified by the key. */ protected StringBuffer translatedReplacements (String key, StringBuffer buf) { MessageBundle bundle = _msgmgr.getBundle(_bundle); if (!bundle.exists(key)) { return buf; } StringTokenizer st = new StringTokenizer(bundle.get(key), " // apply the replacements to each mogrification that matches while (st.hasMoreTokens()) { String pattern = st.nextToken(); String replace = st.nextToken(); Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE). matcher(buf); if (m.find()) { buf = new StringBuffer(); m.appendReplacement(buf, replace); // they may match more than once while (m.find()) { m.appendReplacement(buf, replace); } m.appendTail(buf); } } return buf; } /** * Returns a hashmap containing all command handlers that match the * specified command (i.e. the specified command is a prefix of their * registered command string). */ protected HashMap getCommandHandlers (String command) { HashMap matches = new HashMap(); BodyObject user = (BodyObject)_ctx.getClient().getClientObject(); Iterator itr = _handlers.entrySet().iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); String cmd = (String) entry.getKey(); if (!cmd.startsWith(command)) { continue; } CommandHandler handler = (CommandHandler)entry.getValue(); if (!handler.checkAccess(user)) { continue; } matches.put(cmd, handler); } return matches; } /** * Adds a chatter to our list of recent chatters. */ protected void addChatter (Name name) { // check to see if the chatter validator approves.. if ((_chatterValidator != null) && (!_chatterValidator.isChatterValid(name))) { return; } boolean wasthere = _chatters.remove(name); _chatters.addFirst(name); if (!wasthere) { if (_chatters.size() > MAX_CHATTERS) { _chatters.removeLast(); } notifyChatterObservers(); } } /** * Notifies all registered {@link ChatterObserver}s that the list of * chatters has changed. */ protected void notifyChatterObservers () { _chatterObservers.apply(new ObserverList.ObserverOp() { public boolean apply (Object observer) { ((ChatterObserver)observer).chattersUpdated( _chatters.listIterator()); return true; } }); } /** * Translates the specified message using the specified bundle. */ protected String xlate (String bundle, String message) { if (bundle != null && _msgmgr != null) { MessageBundle msgb = _msgmgr.getBundle(bundle); if (msgb == null) { Log.warning( "No message bundle available to translate message " + "[bundle=" + bundle + ", message=" + message + "]."); } else { message = msgb.xlate(message); } } return message; } /** * Display the specified system message as if it had come from the server. */ protected void displaySystem ( String bundle, String message, byte attLevel, String localtype) { // nothing should be untranslated, so pass the default bundle if need if (bundle == null) { bundle = _bundle; } SystemMessage msg = new SystemMessage(); msg.attentionLevel = attLevel; msg.setClientInfo(xlate(bundle, message), localtype); dispatchMessage(msg); } /** * Looks up and returns the message type associated with the specified * oid. */ protected String getLocalType (int oid) { String type = (String)_auxes.get(oid); return (type == null) ? PLACE_CHAT_TYPE : type; } /** * Used to assign unique ids to all speak requests. */ protected synchronized int nextRequestId () { return _requestId++; } // documentation inherited from interface protected void fetchServices (Client client) { // get a handle on our chat service _cservice = (ChatService)client.requireService(ChatService.class); } /** * An operation that checks with all chat filters to properly filter * a message prior to sending to the server or displaying. */ protected static class FilterMessageOp implements ObserverList.ObserverOp { public void setMessage (String msg, Name otherUser, boolean outgoing) { _msg = msg; _otherUser = otherUser; _out = outgoing; } public boolean apply (Object observer) { if (_msg != null) { _msg = ((ChatFilter) observer).filter(_msg, _otherUser, _out); } return true; } public String getMessage () { return _msg; } protected Name _otherUser; protected String _msg; protected boolean _out; } /** * An observer op used to dispatch ChatMessages on the client. */ protected static class DisplayMessageOp implements ObserverList.ObserverOp { public void setMessage (ChatMessage message) { _message = message; } public boolean apply (Object observer) { ((ChatDisplay)observer).displayMessage(_message); return true; } protected ChatMessage _message; } /** Implements <code>/help</code>. */ protected class HelpHandler extends CommandHandler { public String handleCommand ( SpeakService speakSvc, String command, String args, String[] history) { String hcmd = ""; // grab the command they want help on if (!StringUtil.blank(args)) { hcmd = args; int sidx = args.indexOf(" "); if (sidx != -1) { hcmd = args.substring(0, sidx); } } // let the user give commands with or with the / if (hcmd.startsWith("/")) { hcmd = hcmd.substring(1); } // handle "/help help" and "/help someboguscommand" HashMap possibleCommands = getCommandHandlers(hcmd); if (hcmd.equals("help") || possibleCommands.isEmpty()) { possibleCommands = getCommandHandlers(""); possibleCommands.remove("help"); // remove help from the list } // if there is only one possible command display its usage switch (possibleCommands.size()) { case 1: Iterator itr = possibleCommands.keySet().iterator(); // this is a little funny, but we display the feeback // message by hand and return SUCCESS so that the chat // entry field doesn't think that we've failed and // preserve our command text displayFeedback(null, "m.usage_" + (String)itr.next()); return ChatCodes.SUCCESS; default: Object[] commands = possibleCommands.keySet().toArray(); Arrays.sort(commands); String commandList = ""; for (int ii = 0; ii < commands.length; ii++) { commandList += " /" + commands[ii]; } return MessageBundle.tcompose("m.usage_help", commandList); } } } /** Implements <code>/clear</code>. */ protected class ClearHandler extends CommandHandler { public String handleCommand ( SpeakService speakSvc, String command, String args, String[] history) { clearDisplays(); return ChatCodes.SUCCESS; } } /** Implements <code>/speak</code>. */ protected class SpeakHandler extends CommandHandler { public String handleCommand ( SpeakService speakSvc, String command, String args, String[] history) { if (StringUtil.blank(args)) { return "m.usage_speak"; } // note the command to be stored in the history history[0] = command + " "; return requestChat(null, args, true); } } /** Implements <code>/emote</code>. */ protected class EmoteHandler extends CommandHandler { public String handleCommand ( SpeakService speakSvc, String command, String args, String[] history) { if (StringUtil.blank(args)) { return "m.usage_emote"; } // note the command to be stored in the history history[0] = command + " "; return deliverChat(speakSvc, args, ChatCodes.EMOTE_MODE); } } /** Implements <code>/think</code>. */ protected class ThinkHandler extends CommandHandler { public String handleCommand ( SpeakService speakSvc, String command, String args, String[] history) { if (StringUtil.blank(args)) { return "m.usage_think"; } // note the command to be stored in the history history[0] = command + " "; return deliverChat(speakSvc, args, ChatCodes.THINK_MODE); } } /** Our active chat context. */ protected CrowdContext _ctx; /** Provides access to chat-related server-side services. */ protected ChatService _cservice; /** The message manager. */ protected MessageManager _msgmgr; /** The bundle to use for our own internal messages. */ protected String _bundle; /** The place object that we currently occupy. */ protected PlaceObject _place; /** The client object that we're listening to for tells. */ protected ClientObject _clobj; /** A list of registered chat displays. */ protected ObserverList _displays = new ObserverList(ObserverList.FAST_UNSAFE_NOTIFY); /** A list of registered chat filters. */ protected ObserverList _filters = new ObserverList(ObserverList.FAST_UNSAFE_NOTIFY); /** A mapping from auxiliary chat objects to the types under which * they are registered. */ protected HashIntMap _auxes = new HashIntMap(); /** Validator of who may be added to the chatters list. */ protected ChatterValidator _chatterValidator; /** Usernames of users we've recently chatted with. */ protected LinkedList _chatters = new LinkedList(); /** Observers that are watching our chatters list. */ protected ObserverList _chatterObservers = new ObserverList(ObserverList.FAST_UNSAFE_NOTIFY); /** Registered chat command handlers. */ protected static HashMap _handlers = new HashMap(); /** A history of chat commands. */ protected static ArrayList _history = new ArrayList(); /** Used by {@link #nextRequestId}. */ protected int _requestId; /** Operation used to filter chat messages. */ protected FilterMessageOp _filterMessageOp = new FilterMessageOp(); /** Operation used to display chat messages. */ protected DisplayMessageOp _displayMessageOp = new DisplayMessageOp(); /** The maximum number of chatter usernames to track. */ protected static final int MAX_CHATTERS = 6; /** The maximum number of commands to keep in the chat history. */ protected static final int MAX_COMMAND_HISTORY = 10; }
// Nenya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.media.animation; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.Transparency; import com.threerings.media.sprite.Sprite; import com.threerings.media.sprite.SpriteManager; import com.threerings.media.util.LinearTimeFunction; import com.threerings.media.util.TimeFunction; /** * Washes all non-transparent pixels in a sprite with a particular color * (by compositing them with the solid color with progressively higher * alpha values) and then back again. */ public class GleamAnimation extends Animation { /** * Creates a gleam animation with the supplied sprite. The sprite will be faded to the * specified color and then back again. * * @param fadeIn if true, the sprite itself will be faded in as we fade up to the gleam color * and the gleam color will fade out, leaving just the sprite imagery. */ public GleamAnimation (Sprite sprite, Color color, int upmillis, int downmillis, boolean fadeIn) { this(null, sprite, color, upmillis, downmillis, fadeIn, 750, 0); } /** * Creates a gleam animation with the supplied sprite. The sprite will be faded to the * specified color and then back again. The sprite may be already added to the supplied sprite * manager or not, but when the animation is complete, it will have been added. * * @param fadeIn if true, the sprite itself will be faded in as we fade up to the gleam color * and the gleam color will fade out, leaving just the sprite imagery. */ public GleamAnimation (SpriteManager spmgr, Sprite sprite, Color color, int upmillis, int downmillis, boolean fadeIn) { this(spmgr, sprite, color, upmillis, downmillis, fadeIn, 750, 0); } /** * Creates a gleam animation with the supplied sprite. The sprite will be faded to the * specified color and then back again. The sprite may be already added to the supplied sprite * manager or not, but when the animation is complete, it will have been added. * * @param fadeIn if true, the sprite itself will be faded in as we fade up to the gleam color * and the gleam color will fade out, leaving just the sprite imagery. * @param maxAlpha the maximum alpha value to scale the color to. * @param millisBetweenUpdates milliseconds to wait between actually updating the alpha and * redrawing */ public GleamAnimation (SpriteManager spmgr, Sprite sprite, Color color, int upmillis, int downmillis, boolean fadeIn, int maxAlpha, int millisBetweenUpdates) { this(spmgr, sprite, color, upmillis, downmillis, fadeIn, 750, 0, 0); } /** * Creates a gleam animation with the supplied sprite. The sprite will be faded to the * specified color and then back again. The sprite may be already added to the supplied sprite * manager or not, but when the animation is complete, it will have been added. * * @param fadeIn if true, the sprite itself will be faded in as we fade up to the gleam color * and the gleam color will fade out, leaving just the sprite imagery. * @param maxAlpha the maximum alpha value to scale the color to. * @param millisBetweenUpdates milliseconds to wait between actually updating the alpha and * redrawing * @param minAlpha the minimum alpha value to scale the color to. */ public GleamAnimation (SpriteManager spmgr, Sprite sprite, Color color, int upmillis, int downmillis, boolean fadeIn, int maxAlpha, int millisBetweenUpdates, int minAlpha) { super(new Rectangle(sprite.getBounds())); _spmgr = spmgr; _sprite = sprite; _color = color; _upmillis = upmillis; _downmillis = downmillis; _maxAlpha = maxAlpha; _upfunc = new LinearTimeFunction(_minAlpha, _maxAlpha, upmillis); _downfunc = new LinearTimeFunction(_maxAlpha, _minAlpha, downmillis); _fadeIn = fadeIn; _millisBetweenUpdates = millisBetweenUpdates; } @Override // documentation inherited public void tick (long timestamp) { if (timestamp - _lastUpdate < _millisBetweenUpdates) { return; } _lastUpdate = timestamp; int alpha; if (_upfunc != null) { if ((alpha = _upfunc.getValue(timestamp)) >= _maxAlpha) { _upfunc = null; } } else if (_downfunc != null) { if ((alpha = _downfunc.getValue(timestamp)) <= _minAlpha) { _downfunc = null; } } else { _finished = true; return; } // if the sprite is moved or changed size while we're gleaming it, // track those changes if (!_bounds.equals(_sprite.getBounds())) { Rectangle obounds = new Rectangle(_bounds); _bounds.setBounds(_sprite.getBounds()); invalidateAfterChange(obounds); } if (_alpha != alpha) { _alpha = alpha; invalidate(); } } @Override // documentation inherited public void fastForward (long timeDelta) { if (_upfunc != null) { _upfunc.fastForward(timeDelta); } else if (_downfunc != null) { _downfunc.fastForward(timeDelta); } } @Override // documentation inherited public void paint (Graphics2D gfx) { // TODO: recreate our off image if the sprite bounds changed; we // also need to change the bounds of our animation which might // require some jockeying (especially if we shrink) if (_offimg == null) { _offimg = gfx.getDeviceConfiguration().createCompatibleImage(_bounds.width, _bounds.height, Transparency.TRANSLUCENT); } // create a mask image with our sprite and the appropriate color Graphics2D ogfx = (Graphics2D)_offimg.getGraphics(); try { ogfx.setColor(_color); ogfx.fillRect(0, 0, _bounds.width, _bounds.height); ogfx.setComposite(AlphaComposite.DstAtop); ogfx.translate(-_sprite.getX(), -_sprite.getY()); _sprite.paint(ogfx); } finally { ogfx.dispose(); } Composite ocomp = null; Composite ncomp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, _alpha / 1000f); // if we're fading the sprite in on the way up, set our alpha // composite before we render the sprite if (_fadeIn && _upfunc != null) { ocomp = gfx.getComposite(); gfx.setComposite(ncomp); } // next render the sprite _sprite.paint(gfx); // if we're not fading in, we still need to alpha the white bits if (ocomp == null) { ocomp = gfx.getComposite(); gfx.setComposite(ncomp); } // now alpha composite our mask atop the sprite gfx.drawImage(_offimg, _sprite.getX(), _sprite.getY(), null); gfx.setComposite(ocomp); } @Override // documentation inherited protected void willStart (long tickStamp) { super.willStart(tickStamp); // remove the sprite we're fiddling with from the manager; we'll // add it back when we're done if (_spmgr != null && _spmgr.isManaged(_sprite)) { _spmgr.removeSprite(_sprite); } } @Override //documentation inherited protected void shutdown () { super.shutdown(); if (_spmgr != null && !_spmgr.isManaged(_sprite)) { _spmgr.addSprite(_sprite); } } protected SpriteManager _spmgr; protected Sprite _sprite; protected Color _color; protected Image _offimg; protected boolean _fadeIn; protected TimeFunction _upfunc; protected TimeFunction _downfunc; protected int _upmillis; protected int _downmillis; protected int _maxAlpha; protected int _minAlpha; protected int _alpha = -1; protected long _lastUpdate; protected int _millisBetweenUpdates; }
// Vilya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.parlor.game.server; import com.threerings.presents.dobj.AttributeChangeListener; import com.threerings.presents.dobj.AttributeChangedEvent; import com.threerings.crowd.server.PlaceManager; import com.threerings.parlor.game.data.GameObject; /** * An abstract convenience class used server-side to keep an eye on a game and perform a one-time * game-over activity when the game ends. Classes that care to make use of the game watcher should * create an instance with their newly created {@link GameObject} and implement * {@link #gameDidEnd}. */ public abstract class GameWatcher<T extends GameObject> implements AttributeChangeListener { public void init (PlaceManager plmgr) { @SuppressWarnings("unchecked") T gameobj = (T)plmgr.getPlaceObject(); init(gameobj); } public void init (T gameobj) { _gameobj = gameobj; _gameobj.addListener(this); } public T getGameObject () { return _gameobj; } public void attributeChanged (AttributeChangedEvent event) { if (event.getName().equals(GameObject.STATE)) { // if we transitioned to a non-in-play state, the game has completed if (!_gameobj.isInPlay()) { try { gameDidEnd(_gameobj); } finally { _gameobj.removeListener(this); _gameobj = null; } } } } /** * Called when the game ends to give derived classes a chance to engage in their game-over * antics. */ protected abstract void gameDidEnd (T gameobj); /** The game object we're observing. */ protected T _gameobj; }
package de.plushnikov.intellij.plugin; import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.options.AnnotationProcessorsConfigurable; import com.intellij.notification.Notification; import com.intellij.notification.NotificationDisplayType; import com.intellij.notification.NotificationGroup; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.components.AbstractProjectComponent; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderEntry; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiPackage; import de.plushnikov.intellij.plugin.settings.ProjectSettings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.event.HyperlinkEvent; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Shows notifications about project setup issues, that make the plugin not working. * * @author Alexej Kubarev */ public class LombokPluginProjectValidatorComponent extends AbstractProjectComponent { private Project project; public LombokPluginProjectValidatorComponent(Project project) { super(project); this.project = project; } @NotNull @Override public String getComponentName() { return "lombok.ProjectValidatorComponent"; } @Override public void projectOpened() { // If plugin is not enabled - no point to continue if (!ProjectSettings.isLombokEnabledInProject(project)) { return; } NotificationGroup group = NotificationGroup.findRegisteredGroup(Version.PLUGIN_NAME); if (group == null) { group = new NotificationGroup(Version.PLUGIN_NAME, NotificationDisplayType.BALLOON, true); } // Lombok dependency check boolean hasLombokLibrary = hasLombokLibrary(project); // If dependency is missing and missing dependency notification setting is enabled (defaults to disabled) if (!hasLombokLibrary && ProjectSettings.isEnabled(project, ProjectSettings.IS_MISSING_LOMBOK_CHECK_ENABLED, false)) { Notification notification = group.createNotification(LombokBundle.message("config.warn.dependency.missing.title"), LombokBundle.message("config.warn.dependency.missing.message", project.getName()), NotificationType.ERROR, NotificationListener.URL_OPENING_LISTENER); Notifications.Bus.notify(notification, project); } // If dependency is present and out of date notification setting is enabled (defaults to disabled) if (hasLombokLibrary && ProjectSettings.isEnabled(project, ProjectSettings.IS_LOMBOK_VERSION_CHECK_ENABLED, false)) { final ModuleManager moduleManager = ModuleManager.getInstance(project); for (Module module : moduleManager.getModules()) { String lombokVersion = parseLombokVersion(findLombokEntry(ModuleRootManager.getInstance(module))); if (null != lombokVersion && compareVersionString(lombokVersion, Version.LAST_LOMBOK_VERSION) < 0) { Notification notification = group.createNotification(LombokBundle.message("config.warn.dependency.outdated.title"), LombokBundle.message("config.warn.dependency.outdated.message", project.getName(), module.getName(), lombokVersion, Version.LAST_LOMBOK_VERSION), NotificationType.WARNING, NotificationListener.URL_OPENING_LISTENER); Notifications.Bus.notify(notification, project); } } } // Annotation Processing check boolean annotationProcessorsEnabled = hasAnnotationProcessorsEnabled(project); if (!annotationProcessorsEnabled) { String annotationProcessorsConfigName = new AnnotationProcessorsConfigurable(project).getDisplayName(); Notification notification = group.createNotification(LombokBundle.message("config.warn.annotation-processing.disabled.title"), LombokBundle.message("config.warn.annotation-processing.disabled.message", project.getName()), NotificationType.ERROR, new SettingsOpeningListener(project, annotationProcessorsConfigName)); Notifications.Bus.notify(notification, project); } } private boolean hasAnnotationProcessorsEnabled(Project project) { final CompilerConfiguration config = CompilerConfiguration.getInstance(project); boolean enabled = true; final ModuleManager moduleManager = ModuleManager.getInstance(project); for (Module module : moduleManager.getModules()) { if (ModuleRootManager.getInstance(module).getSourceRoots().length > 0) { enabled &= config.getAnnotationProcessingConfiguration(module).isEnabled(); } } return enabled; } private boolean hasLombokLibrary(Project project) { PsiPackage lombokPackage = JavaPsiFacade.getInstance(project).findPackage("lombok"); return lombokPackage != null; } @Nullable private OrderEntry findLombokEntry(@NotNull ModuleRootManager moduleRootManager) { final OrderEntry[] orderEntries = moduleRootManager.getOrderEntries(); for (OrderEntry orderEntry : orderEntries) { if (orderEntry.getPresentableName().contains("lombok")) { return orderEntry; } } return null; } @Nullable protected String parseLombokVersion(@Nullable OrderEntry orderEntry) { String result = null; if (null != orderEntry) { final String presentableName = orderEntry.getPresentableName(); Pattern pattern = Pattern.compile("(.*:)([\\d\\.]+)(.*)"); final Matcher matcher = pattern.matcher(presentableName); if (matcher.find()) { result = matcher.group(2); } } return result; } protected int compareVersionString(@NotNull String firstVersionOne, @NotNull String secondVersion) { String[] firstVersionParts = firstVersionOne.split("\\."); String[] secondVersionParts = secondVersion.split("\\."); int length = Math.max(firstVersionParts.length, secondVersionParts.length); for (int i = 0; i < length; i++) { int firstPart = i < firstVersionParts.length && !firstVersionParts[i].isEmpty() ? Integer.parseInt(firstVersionParts[i]) : 0; int secondPart = i < secondVersionParts.length && !secondVersionParts[i].isEmpty() ? Integer.parseInt(secondVersionParts[i]) : 0; if (firstPart < secondPart) { return -1; } if (firstPart > secondPart) { return 1; } } return 0; } /** * Simple {@link NotificationListener.Adapter} that opens Settings Page for correct dialog. */ private static class SettingsOpeningListener extends NotificationListener.Adapter { private final Project project; private final String nameToSelect; SettingsOpeningListener(Project project, String nameToSelect) { this.project = project; this.nameToSelect = nameToSelect; } @Override protected void hyperlinkActivated(@NotNull final Notification notification, @NotNull final HyperlinkEvent e) { if (!project.isDisposed()) { ShowSettingsUtil.getInstance().showSettingsDialog(project, nameToSelect); } } } }
package at.ac.tuwien.inso.entity; import javax.persistence.*; @Entity public class Feedback { @Id @GeneratedValue private Long id; @Column(nullable = false) private Type type; @ManyToOne private Student student; @ManyToOne private Course course; protected Feedback() {} public Feedback(Student student, Course course, Type type) { this.student = student; this.course = course; this.type = type; } public Feedback(Student student, Course course) { this(student, course, Type.LIKE); } public Long getId() { return id; } public Student getStudent() { return student; } public Course getCourse() { return course; } public Type getType() { return type; } public Feedback setType(Type type) { this.type = type; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Feedback feedback = (Feedback) o; if (id != null ? !id.equals(feedback.id) : feedback.id != null) return false; if (type != feedback.type) return false; if (student != null ? !student.equals(feedback.student) : feedback.student != null) return false; return course != null ? course.equals(feedback.course) : feedback.course == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (student != null ? student.hashCode() : 0); result = 31 * result + (course != null ? course.hashCode() : 0); return result; } @Override public String toString() { return "Feedback{" + "id=" + id + ", type=" + type + ", student=" + student + ", course=" + course + '}'; } public enum Type { LIKE, DISLIKE } }
// $Id: CompiledConfigParser.java,v 1.2 2002/03/08 09:40:21 mdb Exp $ package com.threerings.yohoho.tools.xml; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.Serializable; import org.xml.sax.SAXException; import org.apache.commons.digester.Digester; import com.threerings.yohoho.util.CompiledConfig; import com.threerings.yohoho.tools.CompiledConfigTask; /** * An abstract base implementation of a parser that is used to compile * configuration definitions into config objects for use by the client and * server. * * @see CompiledConfig * @see CompiledConfigTask */ public abstract class CompiledConfigParser { /** * Parses the supplied configuration file into a serializable * configuration object. */ public Serializable parseConfig (File source) throws IOException, SAXException { Digester digester = new Digester(); Serializable config = createConfigObject(); addRules(digester); digester.push(config); digester.parse(new FileInputStream(source)); return config; } /** * Creates the config object instance that will be populated during * the parsing process. */ protected abstract Serializable createConfigObject (); /** * Adds the necessary digester rules for parsing the config object. */ protected abstract void addRules (Digester digester); }
package edu.yu.einstein.wasp.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.support.SessionStatus; import edu.yu.einstein.wasp.model.Job; import edu.yu.einstein.wasp.model.Lab; import edu.yu.einstein.wasp.model.LabUser; import edu.yu.einstein.wasp.model.Labmeta; import edu.yu.einstein.wasp.model.MetaAttribute; import edu.yu.einstein.wasp.model.MetaAttribute.Country; import edu.yu.einstein.wasp.model.MetaAttribute.State; import edu.yu.einstein.wasp.model.MetaUtil; import edu.yu.einstein.wasp.model.Role; import edu.yu.einstein.wasp.model.User; import edu.yu.einstein.wasp.service.DepartmentService; import edu.yu.einstein.wasp.service.LabService; import edu.yu.einstein.wasp.service.LabUserService; import edu.yu.einstein.wasp.service.LabmetaService; import edu.yu.einstein.wasp.service.RoleService; import edu.yu.einstein.wasp.service.UserService; import edu.yu.einstein.wasp.service.EmailService; import edu.yu.einstein.wasp.taglib.MessageTag; @Controller @Transactional @RequestMapping("/lab") public class LabController extends WaspController { public static final MetaAttribute.Area AREA = MetaAttribute.Area.lab; @Autowired private LabService labService; @Autowired private LabUserService labUserService; @Autowired private RoleService roleService; @Autowired HttpServletRequest request; @Autowired private LabmetaService labmetaService; @Autowired private DepartmentService deptService; @Autowired private UserService userService; @Autowired private BeanValidator validator; @Autowired private EmailService emailService; @InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(validator); } @RequestMapping("/list") @PreAuthorize("hasRole('god')") public String list(ModelMap m) { List<Lab> labList = this.labService.findAll(); m.addAttribute("lab", labList); return "lab/list"; } @RequestMapping(value = "/create/form.do", method = RequestMethod.GET) @PreAuthorize("hasRole('god')") public String showEmptyForm(ModelMap m) { Lab lab = new Lab(); lab.setLabmeta(MetaUtil.getMasterList(Labmeta.class, AREA)); m.addAttribute(AREA.name(), lab); prepareSelectListData(m); return AREA + "/detail_rw"; } @RequestMapping(value = "/detail_rw/{labId}.do", method = RequestMethod.GET) @PreAuthorize("hasRole('god') or hasRole('lu-' + #labId)") public String detailRW(@PathVariable("labId") Integer labId, ModelMap m) { return detail(labId,m,true); } @RequestMapping(value = "/detail_ro/{labId}.do", method = RequestMethod.GET) @PreAuthorize("hasRole('god') or hasRole('lu-' + #labId)") public String detailRO(@PathVariable("labId") Integer labId, ModelMap m) { return detail(labId,m,false); } private String detail(Integer labId, ModelMap m, boolean isRW) { Lab lab = this.labService.getById(labId); lab.setLabmeta(MetaUtil.syncWithMaster(lab.getLabmeta(), AREA, Labmeta.class)); MetaUtil.setAttributesAndSort(lab.getLabmeta(), AREA); List<LabUser> labUserList = lab.getLabUser(); labUserList.size(); List<Job> jobList = lab.getJob(); jobList.size(); m.addAttribute(AREA.name(), lab); prepareSelectListData(m); return isRW?"lab/detail_rw":"lab/detail_ro"; } @RequestMapping(value = "/create/form.do", method = RequestMethod.POST) @PreAuthorize("hasRole('god')") public String create(@Valid Lab labForm, BindingResult result, SessionStatus status, ModelMap m) { // read properties from form List<Labmeta> labmetaList = MetaUtil.getMetaFromForm(request, AREA, Labmeta.class); // set property attributes and sort them according to "position" MetaUtil.setAttributesAndSort(labmetaList, AREA); labForm.setLabmeta(labmetaList); // manually validate login and password List<String> validateList = new ArrayList<String>(); for (Labmeta meta : labmetaList) { if (meta.getProperty() != null && meta.getProperty().getConstraint() != null) { validateList.add(meta.getK()); validateList.add(meta.getProperty().getConstraint()); } } MetaValidator validator = new MetaValidator( validateList.toArray(new String[] {})); validator.validate(labmetaList, result, AREA); if (result.hasErrors()) { prepareSelectListData(m); MessageTag.addMessage(request.getSession(), "lab.created.error"); return "lab/detail_rw"; } labForm.setLastUpdTs(new Date()); Lab labDb = this.labService.save(labForm); for (Labmeta um : labmetaList) { um.setLabId(labDb.getLabId()); } ; labmetaService.updateByLabId(labDb.getLabId(), labmetaList); status.setComplete(); MessageTag.addMessage(request.getSession(), "lab.created.success"); return "redirect:/lab/detail_rw/" + labDb.getLabId() + ".do"; } @RequestMapping(value = "/detail_rw/{labId}.do", method = RequestMethod.POST) @PreAuthorize("hasRole('god') or hasRole('lm-' + #labId)") public String updateDetail(@PathVariable("labId") Integer labId, @Valid Lab labForm, BindingResult result, SessionStatus status, ModelMap m) { List<Labmeta> labmetaList = MetaUtil.getMetaFromForm(request, AREA, Labmeta.class); for (Labmeta meta : labmetaList) { meta.setLabId(labId); } MetaUtil.setAttributesAndSort(labmetaList, AREA); labForm.setLabmeta(labmetaList); List<String> validateList = new ArrayList<String>(); for (Labmeta meta : labmetaList) { if (meta.getProperty() != null && meta.getProperty().getConstraint() != null) { validateList.add(meta.getK()); validateList.add(meta.getProperty().getConstraint()); } } MetaValidator validator = new MetaValidator( validateList.toArray(new String[] {})); validator.validate(labmetaList, result, AREA); if (result.hasErrors()) { prepareSelectListData(m); MessageTag.addMessage(request.getSession(), "lab.updated.error"); return "lab/detail_rw"; } Lab labDb = this.labService.getById(labId); labDb.setName(labForm.getName()); labDb.setDepartmentId(labForm.getDepartmentId()); labDb.setPrimaryUserId(labForm.getPrimaryUserId()); labDb.setLastUpdTs(new Date()); this.labService.merge(labDb); labmetaService.updateByLabId(labId, labmetaList); status.setComplete(); MessageTag.addMessage(request.getSession(), "lab.updated.success"); return "redirect:" + labId + ".do"; } @RequestMapping(value = "/user/{labId}.do", method = RequestMethod.GET) @PreAuthorize("hasRole('god') or hasRole('lu-' + #labId)") public String userList(@PathVariable("labId") Integer labId, ModelMap m) { Lab lab = this.labService.getById(labId); List<LabUser> labUser = lab.getLabUser(); m.addAttribute("lab", lab); m.addAttribute("labuser", labUser); return "lab/user"; } @RequestMapping(value = "/user/role/{labId}/{userId}/{roleName}.do", method = RequestMethod.GET) @PreAuthorize("hasRole('god') or hasRole('lm-' + #labId)") public String userDetail ( @PathVariable("labId") Integer labId, @PathVariable("userId") Integer userId, @PathVariable("roleName") String roleName, ModelMap m) { LabUser labUser = labUserService.getLabUserByLabIdUserId(labId, userId); Role role = roleService.getRoleByRoleName(roleName); labUser.setRoleId(role.getRoleId()); labUserService.merge(labUser); return "redirect:/lab/user/" + labId + ".do"; } @RequestMapping(value = "/request.do", method = RequestMethod.GET) public String showRequestAccessForm(ModelMap m) { return "lab/request"; } @RequestMapping(value = "/request.do", method = RequestMethod.POST) public String requestAccess( @RequestParam("primaryuseremail") String primaryuseremail, ModelMap m) { // check existance of primaryUser/lab User primaryUser = userService.getUserByEmail(primaryuseremail); if (primaryUser.getUserId() == 0) { MessageTag.addMessage(request.getSession(), "labuser.request.primaryuser.error"); return "redirect:/lab/request.do"; } Lab lab = labService.getLabByPrimaryUserId(primaryUser.getUserId()); if (lab.getLabId() == 0) { MessageTag.addMessage(request.getSession(), "labuser.request.primaryuser.error"); return "redirect:/lab/request.do"; } // check existance of primaryUser/lab User user = this.getAuthenticatedUser(); LabUser labUser = labUserService.getLabUserByLabIdUserId(lab.getLabId(), user.getUserId()); ArrayList<String> alreadyPendingRoles = new ArrayList(); alreadyPendingRoles.add("lp"); ArrayList<String> alreadyAccessRoles = new ArrayList(); alreadyPendingRoles.add("pi"); alreadyPendingRoles.add("lm"); alreadyPendingRoles.add("lu"); if (labUser.getLabUserId() != 0) { if (alreadyPendingRoles.contains(labUser.getRole().getRoleName())) { MessageTag.addMessage(request.getSession(), "labuser.request.alreadypending.error"); } if (alreadyAccessRoles.contains(labUser.getRole().getRoleName())) { MessageTag.addMessage(request.getSession(), "labuser.request.alreadyaccess.error"); } return "redirect:/lab/request.do"; } Role role = roleService.getRoleByRoleName("lp"); labUser.setLabId(lab.getLabId()); labUser.setUserId(user.getUserId()); labUser.setRoleId(role.getRoleId()); labUserService.save(labUser); labUserService.refresh(labUser); emailService.sendPendingLabUser(labUser); MessageTag.addMessage(request.getSession(), "labuser.request.success"); return "redirect:/lab/request.do"; // return "redirect:/dashboard.do"; } @RequestMapping(value = "/pendinglab/list/{departmentId}.do", method = RequestMethod.GET) @PreAuthorize("hasRole('god') or hasRole('da-' + $departmentId)") public String pendingLabList(@PathVariable("departmentId") Integer departmentId, ModelMap m) { return "lab/pendinglab/list"; } @RequestMapping(value = "/pendinglab/{departmentId}/{labId}/{newStatus}.do", method = RequestMethod.GET) @PreAuthorize("hasRole('god') or hasRole('da-' + #departmentId)") public String pendingLab ( @PathVariable("departmentId") Integer departmentId, @PathVariable("labId") Integer labId, @PathVariable("newStatus") String newStatus, ModelMap m) { return "redirect:/lab/pendinglab/list"; } @RequestMapping(value = "/pendinguser/list/{labId}.do", method = RequestMethod.GET) @PreAuthorize("hasRole('god') or hasRole('lm-' + #labId)") public String pendingLabUserList ( @PathVariable("labId") Integer labId, ModelMap m) { return "redirect:/lab/pendinguser/list"; } @RequestMapping(value = "/pendinguser/detail/{labId}/{userId}/{roleName}.do", method = RequestMethod.GET) @PreAuthorize("hasRole('god') or hasRole('lm-' + #labId)") public String pendingLabUserDetail ( @PathVariable("labId") Integer labId, @PathVariable("userId") Integer userId, @PathVariable("roleName") String roleName, ModelMap m) { LabUser labUser = labUserService.getLabUserByLabIdUserId(labId, userId); Role role = roleService.getRoleByRoleName(roleName); labUser.setRoleId(role.getRoleId()); labUserService.merge(labUser); return "redirect:/lab/user/" + labId + ".do"; } private void prepareSelectListData(ModelMap m) { m.addAttribute("pusers", userService.findAll()); m.addAttribute("countries", Country.getList()); m.addAttribute("states", State.getList()); m.addAttribute("departments", deptService.findAll()); } }
package krasa.formatter.plugin; import org.jetbrains.annotations.NotNull; import com.intellij.lang.ImportOptimizer; import com.intellij.lang.java.JavaImportOptimizer; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.psi.*; import krasa.formatter.exception.FileDoesNotExistsException; import krasa.formatter.exception.ParsingFailedException; import krasa.formatter.settings.ProjectComponent; import krasa.formatter.settings.Settings; import krasa.formatter.settings.provider.ImportOrderProvider; import krasa.formatter.utils.FileUtils; /** * @author Vojtech Krasa */ public class EclipseImportOptimizer implements ImportOptimizer { private static final Logger LOG = Logger.getInstance("#krasa.formatter.plugin.processor.ImportOrderProcessor"); private Notifier notifier = new Notifier(); @NotNull @Override public Runnable processFile(final PsiFile file) { if (!(file instanceof PsiJavaFile)) { return EmptyRunnable.getInstance(); } final PsiJavaFile dummyFile = (PsiJavaFile) file.copy(); final Runnable intellijRunnable = new JavaImportOptimizer().processFile(dummyFile); if (!(file instanceof PsiJavaFile)) { return intellijRunnable; } if (!isEnabled(file)) { return intellijRunnable; } return new Runnable() { @Override public void run() { intellijRunnable.run(); try { Settings settings = ProjectComponent.getSettings(file); if (isEnabled(settings)) { optimizeImportsByEclipse((PsiJavaFile) file, settings, dummyFile); } } catch (ParsingFailedException e) { notifier.configurationError(e, file.getProject()); LOG.info("Eclipse Import Optimizer failed", e); } catch (FileDoesNotExistsException e) { notifier.configurationError(e, file.getProject()); LOG.info("Eclipse Import Optimizer failed", e); } catch (IndexNotReadyException e) { throw e; } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { LOG.error("Eclipse Import Optimizer failed", e); } } }; } private void optimizeImportsByEclipse(PsiJavaFile psiFile, Settings settings, PsiJavaFile dummy) { ImportSorterAdapter importSorter = null; try { importSorter = getImportSorter(settings); PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(psiFile.getProject()); commitDocument(psiFile, psiDocumentManager); importSorter.sortImports(psiFile, dummy); // commitDocumentAndSave(psiFile, psiDocumentManager); } catch (ParsingFailedException e) { throw e; } catch (IndexNotReadyException e) { throw e; } catch (ProcessCanceledException e) { throw e; } catch (FileDoesNotExistsException e) { throw e; } catch (Throwable e) { final PsiImportList oldImportList = (psiFile).getImportList(); StringBuilder stringBuilder = new StringBuilder(); if (oldImportList != null) { PsiImportStatementBase[] allImportStatements = oldImportList.getAllImportStatements(); for (PsiImportStatementBase allImportStatement : allImportStatements) { String text = allImportStatement.getText(); stringBuilder.append(text); } } String message = "imports: " + stringBuilder.toString() + ", settings: " + (importSorter != null ? importSorter.getImportsOrderAsString() : null); throw new ImportSorterException(message, e); } } private void commitDocument(PsiJavaFile psiFile, PsiDocumentManager psiDocumentManager) { Document document = psiDocumentManager.getDocument(psiFile); if (document != null) { psiDocumentManager.commitDocument(document); } } /** * was needed for #87+#94 - saveDocument un-blues changed files - where content is equal, but now not changing PSI when imports are not changed (#179) makes it obsolete */ private void commitDocumentAndSave(PsiJavaFile psiFile, PsiDocumentManager psiDocumentManager) { Document document = psiDocumentManager.getDocument(psiFile); if (document != null) { psiDocumentManager.doPostponedOperationsAndUnblockDocument(document); psiDocumentManager.commitDocument(document); FileDocumentManager.getInstance().saveDocument(document); } } protected ImportSorterAdapter getImportSorter(Settings settings) { if (settings.isImportOrderFromFile()) { final ImportOrderProvider importOrderProviderFromFile = settings.getImportOrderProvider(); return new ImportSorterAdapter(settings.getImportOrdering(), importOrderProviderFromFile.get()); } else { return new ImportSorterAdapter(settings.getImportOrdering(), ImportOrderProvider.toList(settings.getImportOrder())); } } @Override public boolean supports(PsiFile file) { return FileUtils.isJava(file) && isEnabled(file); } private boolean isEnabled(Settings settings) { return settings.isEnabled() && settings.isEnableJavaFormatting() && settings.isOptimizeImports(); } private boolean isEnabled(PsiFile file) { Settings settings = ProjectComponent.getSettings(file); return isEnabled(settings); } }
package ch.sportchef; import ch.sportchef.business.RuntimeExceptionMapper; import ch.sportchef.business.WebApplicationExceptionMapper; import ch.sportchef.business.admin.boundary.AdminResource; import ch.sportchef.business.authentication.boundary.AuthenticationResource; import ch.sportchef.business.event.boundary.EventsResource; import ch.sportchef.business.user.boundary.UsersResource; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import io.dropwizard.Application; import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.setup.Environment; import lombok.SneakyThrows; import javax.validation.constraints.NotNull; public class SportChefApplication extends Application<SportChefConfiguration> { @SneakyThrows public static void main(@NotNull final String... args) { new SportChefApplication().run(args); } @Override public void run(@NotNull final SportChefConfiguration configuration, @NotNull final Environment environment) { registerModules(environment.getObjectMapper()); final Injector injector = createInjector(configuration, environment); registerResources(environment, injector); registerExceptionMapper(environment); } private void registerModules(@NotNull final ObjectMapper objectMapper) { objectMapper.registerModule(new Jdk8Module()); objectMapper.registerModule(new JavaTimeModule()); objectMapper.registerModule(new GuavaModule()); } private Injector createInjector(@NotNull final SportChefConfiguration configuration, @NotNull final Environment environment) { return Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(SportChefConfiguration.class).toInstance(configuration); bind(HealthCheckRegistry.class).toInstance(environment.healthChecks()); bind(MetricRegistry.class).toInstance(environment.metrics()); } }); } private void registerResources(@NotNull final Environment environment, @NotNull final Injector injector) { final JerseyEnvironment jersey = environment.jersey(); jersey.register(injector.getInstance(AdminResource.class)); jersey.register(injector.getInstance(AuthenticationResource.class)); jersey.register(injector.getInstance(EventsResource.class)); jersey.register(injector.getInstance(UsersResource.class)); } private void registerExceptionMapper(@NotNull final Environment environment) { final JerseyEnvironment jersey = environment.jersey(); jersey.register(new WebApplicationExceptionMapper()); jersey.register(new RuntimeExceptionMapper()); } }
package org.apache.commons.lang.builder; import java.io.Serializable; import java.util.Collection; import java.util.Map; import org.apache.commons.lang.SystemUtils; /** * <p><code>ToStringStyle</code> works with <code>ToStringBuilder</code> * to create a <code>toString</code>. The main public interface is always * via <code>ToStringBuilder</code>.</p> * * <p>These classes are intended to be used as <code>Singletons</code>. * There is no need to instantiate a new style each time. A program * will generally use one of the predefined constants on this class. * Alternatively, the {@link StandardToStringStyle} class can be used * to set the individual settings. Thus most styles can be achieved * without subclassing.</p> * * <p>If required, a subclass can override as many or as few of the * methods as it requires. Each object type (from <code>boolean</code> * to <code>long</code> to <code>Object</code> to <code>int[]</code>) has * its own methods to output it. Most have two versions, detail and summary. * * <p>For example, the detail version of the array based methods will * output the whole array, whereas the summary method will just output * the array length.</p> * * @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a> * @version $Id: ToStringStyle.java,v 1.6 2002/11/22 21:16:24 scolebourne Exp $ */ public abstract class ToStringStyle implements Serializable { /** * The default toString style. */ public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle(); /** * The multi line toString style. */ public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle(); /** * The no field names toString style. */ public static final ToStringStyle NO_FIELD_NAMES_STYLE = new NoFieldNameToStringStyle(); /** * The simple toString style. */ public static final ToStringStyle SIMPLE_STYLE = new SimpleToStringStyle(); /** * Whether to use the field names, the default is <code>true</code>. */ private boolean useFieldNames = true; /** * Whether to use the class name, the default is <code>true</code>. */ private boolean useClassName = true; /** * Whether to use short class names, the default is <code>false</code>. */ private boolean useShortClassName = false; /** * Whether to use the identity hash code, the default is <code>true</code>. */ private boolean useIdentityHashCode = true; /** * The content start <code>'['</code>. */ private String contentStart = "["; /** * The content end <code>']'</code>. */ private String contentEnd = "]"; /** * The field name value separator <code>'='</code>. */ private String fieldNameValueSeparator = "="; /** * The field separator <code>','</code>. */ private String fieldSeparator = ","; /** * The array start <code>'{'</code>. */ private String arrayStart = "{"; /** * The array separator <code>','</code>. */ private String arraySeparator = ","; /** * The detail for array content */ private boolean arrayContentDetail = true; /** * The array end <code>'}'</code>. */ private String arrayEnd = "}"; /** * The value to use when fullDetail is <code>null</code>, * the default value is <code>true</code>. */ private boolean defaultFullDetail = true; /** * The <code>null</code> text <code>'&lt;null&gt;'</code>. */ private String nullText = "<null>"; /** * The summary size text start <code>'<size'</code>. */ private String sizeStartText = "<size="; /** * The summary size text start <code>'>'</code>. */ private String sizeEndText = ">"; /** * The summary object text start <code>'<'</code>. */ private String summaryObjectStartText = "<"; /** * The summary object text start <code>'>'</code>. */ private String summaryObjectEndText = ">"; /** * <p>Constructor.</p> */ protected ToStringStyle() { super(); } /** * <p>Append the start of data indicator.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param object the <code>Object</code> to build a * <code>toString</code> for, must not be <code>null</code> */ public void appendStart(StringBuffer buffer, Object object) { appendClassName(buffer, object); appendIdentityHashCode(buffer, object); appendContentStart(buffer); } /** * <p>Append the end of data indicator.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param object the <code>Object</code> to build a * <code>toString</code> for, must not be <code>null</code> */ public void appendEnd(StringBuffer buffer, Object object) { appendContentEnd(buffer); } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value, printing the full <code>toString</code> of the * <code>Object</code> passed in.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info, <code>null</code> for style decides */ public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (value == null) { appendNullText(buffer, fieldName); } else { appendInternal(buffer, fieldName, value, isFullDetail(fullDetail)); } appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> an <code>Object</code>, * correctly interpretting its type.</p> * * <p>This method performs the main lookup by Class type to correctly * route arrays, <code>Collections</code>, <code>Maps</code> and * <code>Objects</code> to the appropriate method.</p> * * <p>Either detail or summary views can be specified.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code>, * not <code>null</code> * @param detail output detail or not */ protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) { if (value instanceof Collection) { if (detail) { appendDetail(buffer, fieldName, (Collection) value); } else { appendSummarySize(buffer, fieldName, ((Collection) value).size()); } } else if (value instanceof Map) { if (detail) { appendDetail(buffer, fieldName, (Map) value); } else { appendSummarySize(buffer, fieldName, ((Map) value).size()); } } else if (value instanceof long[]) { if (detail) { appendDetail(buffer, fieldName, (long[]) value); } else { appendSummary(buffer, fieldName, (long[]) value); } } else if (value instanceof int[]) { if (detail) { appendDetail(buffer, fieldName, (int[]) value); } else { appendSummary(buffer, fieldName, (int[]) value); } } else if (value instanceof short[]) { if (detail) { appendDetail(buffer, fieldName, (short[]) value); } else { appendSummary(buffer, fieldName, (short[]) value); } } else if (value instanceof byte[]) { if (detail) { appendDetail(buffer, fieldName, (byte[]) value); } else { appendSummary(buffer, fieldName, (byte[]) value); } } else if (value instanceof char[]) { if (detail) { appendDetail(buffer, fieldName, (char[]) value); } else { appendSummary(buffer, fieldName, (char[]) value); } } else if (value instanceof double[]) { if (detail) { appendDetail(buffer, fieldName, (double[]) value); } else { appendSummary(buffer, fieldName, (double[]) value); } } else if (value instanceof float[]) { if (detail) { appendDetail(buffer, fieldName, (float[]) value); } else { appendSummary(buffer, fieldName, (float[]) value); } } else if (value instanceof boolean[]) { if (detail) { appendDetail(buffer, fieldName, (boolean[]) value); } else { appendSummary(buffer, fieldName, (boolean[]) value); } } else if (value.getClass().isArray()) { if (detail) { appendDetail(buffer, fieldName, (Object[]) value); } else { appendSummary(buffer, fieldName, (Object[]) value); } } else { if (detail) { appendDetail(buffer, fieldName, (Object) value); } else { appendSummary(buffer, fieldName, (Object) value); } } } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value, printing the full detail of the <code>Object</code>.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { buffer.append(value); } /** * <p>Append to the <code>toString</code> a <code>Collection</code>.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param coll the <code>Collection</code> to add to the * <code>toString</code>, not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, Collection coll) { buffer.append(coll); } /** * <p>Append to the <code>toString</code> a <code>Map<code>.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param map the <code>Map</code> to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, Map map) { buffer.append(map); } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value, printing a summary of the Object.</P> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code>, * not <code>null</code> */ protected void appendSummary(StringBuffer buffer, String fieldName, Object value) { buffer.append(summaryObjectStartText); buffer.append(getShortClassName(value.getClass())); buffer.append(summaryObjectEndText); } /** * <p>Append to the <code>toString</code> a <code>long</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param value the value to add to the <code>toString</code> */ public void append(StringBuffer buffer, String fieldName, long value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> a <code>long</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, long value) { buffer.append(value); } /** * <p>Append to the <code>toString</code> an <code>int</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param value the value to add to the <code>toString</code> */ public void append(StringBuffer buffer, String fieldName, int value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> an <code>int</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, int value) { buffer.append(value); } /** * <p>Append to the <code>toString</code> a <code>short</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param value the value to add to the <code>toString</code> */ public void append(StringBuffer buffer, String fieldName, short value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> a <code>short</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, short value) { buffer.append(value); } /** * <p>Append to the <code>toString</code> a <code>byte</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param value the value to add to the <code>toString</code> */ public void append(StringBuffer buffer, String fieldName, byte value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> a <code>byte</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, byte value) { buffer.append(value); } /** * <p>Append to the <code>toString</code> a <code>char</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param value the value to add to the <code>toString</code> */ public void append(StringBuffer buffer, String fieldName, char value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> a <code>char</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, char value) { buffer.append(value); } /** * <p>Append to the <code>toString</code> a <code>double</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param value the value to add to the <code>toString</code> */ public void append(StringBuffer buffer, String fieldName, double value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> a <code>double</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, double value) { buffer.append(value); } /** * <p>Append to the <code>toString</code> a <code>float</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param value the value to add to the <code>toString</code> */ public void append(StringBuffer buffer, String fieldName, float value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> a <code>float</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, float value) { buffer.append(value); } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param value the value to add to the <code>toString</code> */ public void append(StringBuffer buffer, String fieldName, boolean value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * value.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the <code>toString</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) { buffer.append(value); } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info, <code>null</code> for style decides */ public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> the detail of an * <code>Object</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { Object item = array[i]; if (i > 0) { buffer.append(arraySeparator); } if (item == null) { appendNullText(buffer, fieldName); } else { appendInternal(buffer, fieldName, item, arrayContentDetail); } } buffer.append(arrayEnd); } /** * <p>Append to the <code>toString</code> a summary of an * <code>Object</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) { appendSummarySize(buffer, fieldName, array.length); } /** * <p>Append to the <code>toString</code> a <code>long</code> * array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info, <code>null</code> for style decides */ public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> the detail of a * <code>long</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** * <p>Append to the <code>toString</code> a summary of a * <code>long</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) { appendSummarySize(buffer, fieldName, array.length); } /** * <p>Append to the <code>toString</code> an <code>int</code> * array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info, <code>null</code> for style decides */ public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> the detail of an * <code>int</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** * <p>Append to the <code>toString</code> a summary of an * <code>int</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) { appendSummarySize(buffer, fieldName, array.length); } /** * <p>Append to the <code>toString</code> a <code>short</code> * array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info, <code>null</code> for style decides */ public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> the detail of a * <code>short</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** * <p>Append to the <code>toString</code> a summary of a * <code>short</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) { appendSummarySize(buffer, fieldName, array.length); } /** * <p>Append to the <code>toString</code> a <code>byte</code> * array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info, <code>null</code> for style decides */ public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> the detail of a * <code>byte</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** * <p>Append to the <code>toString</code> a summary of a * <code>byte</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) { appendSummarySize(buffer, fieldName, array.length); } /** * <p>Append to the <code>toString</code> a <code>char</code> * array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info, <code>null</code> for style decides */ public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> the detail of a * <code>char</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** * <p>Append to the <code>toString</code> a summary of a * <code>char</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) { appendSummarySize(buffer, fieldName, array.length); } /** * <p>Append to the <code>toString</code> a <code>double</code> * array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info, <code>null</code> for style decides */ public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> the detail of a * <code>double</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** * <p>Append to the <code>toString</code> a summary of a * <code>double</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) { appendSummarySize(buffer, fieldName, array.length); } /** * <p>Append to the <code>toString</code> a <code>float</code> * array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info, <code>null</code> for style decides */ public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> the detail of a * <code>float</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** * <p>Append to the <code>toString</code> a summary of a * <code>float</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) { appendSummarySize(buffer, fieldName, array.length); } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info, <code>null</code> for style decides */ public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** * <p>Append to the <code>toString</code> the detail of a * <code>boolean</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** * <p>Append to the <code>toString</code> a summary of a * <code>boolean</code> array.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the <code>toString</code>, * not <code>null</code> */ protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) { appendSummarySize(buffer, fieldName, array.length); } /** * <p>Append the class name.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param object the <code>Object</code> whose name to output */ protected void appendClassName(StringBuffer buffer, Object object) { if (useClassName) { if (useShortClassName) { buffer.append(getShortClassName(object.getClass())); } else { buffer.append(object.getClass().getName()); } } } /** * <p>Append the {@link System#identityHashCode(java.lang.Object)}.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param object the <code>Object</code> whose id to output */ protected void appendIdentityHashCode(StringBuffer buffer, Object object) { if (useIdentityHashCode) { buffer.append('@'); buffer.append(Integer.toHexString(System.identityHashCode(object))); } } /** * <p>Append the content start to the buffer.</p> * * @param buffer the <code>StringBuffer</code> to populate */ protected void appendContentStart(StringBuffer buffer) { buffer.append(contentStart); } /** * <p>Append the content end to the buffer.</p> * * @param buffer the <code>StringBuffer</code> to populate */ protected void appendContentEnd(StringBuffer buffer) { int len = buffer.length(); int sepLen = fieldSeparator.length(); if (len > 0 && sepLen > 0 && len >= sepLen && buffer.charAt(len - 1) == fieldSeparator.charAt(sepLen - 1)) { buffer.setLength(len - sepLen); } buffer.append(contentEnd); } /** * <p>Append an indicator for <code>null</code> to the buffer.</p> * * <p>The default indicator is <code>'&lt;null&gt;'</code>.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended */ protected void appendNullText(StringBuffer buffer, String fieldName) { buffer.append(nullText); } /** * <p>Append the field separator to the buffer.</p> * * @param buffer the <code>StringBuffer</code> to populate */ protected void appendFieldSeparator(StringBuffer buffer) { buffer.append(fieldSeparator); } /** * <p>Append the field start to the buffer.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name */ protected void appendFieldStart(StringBuffer buffer, String fieldName) { if (useFieldNames && fieldName != null) { buffer.append(fieldName); buffer.append(fieldNameValueSeparator); } } /** * <p>Append the field end to the buffer.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended */ protected void appendFieldEnd(StringBuffer buffer, String fieldName) { appendFieldSeparator(buffer); } /** * <p>Append to the <code>toString</code> a size summary.</p> * * <p>The size summary is used to summarize the contents of * <code>Collections</code>, <code>Maps</code> and arrays.</p> * * <p>The output consists of a prefix, the passed in size * and a suffix.</p> * * <p>The default format is <code>'&lt;size=n&gt;'<code>.</p> * * @param buffer the <code>StringBuffer</code> to populate * @param fieldName the field name, typically not used as already appended * @param size the size to append */ protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) { buffer.append(sizeStartText); buffer.append(size); buffer.append(sizeEndText); } /** * <p>Is this field to be output in full detail.</p> * * <p>This method converts a detail request into a detail level. * The calling code may request full detail (<code>true</code>), * but a subclass might ignore that and always return * <code>false</code>. The calling code may pass in * <code>null</code> indicating that it doesn't care about * the detail level. In this case the default detail level is * used.</p> * * @param fullDetailRequest the detail level requested * @return whether full detail is to be shown */ protected boolean isFullDetail(Boolean fullDetailRequest) { if (fullDetailRequest == null) { return defaultFullDetail; } return fullDetailRequest.booleanValue(); } /** * <p>Gets the short class name for a class.</p> * * <p>The short class name is the classname excluding * the package name.</p> * * @param cls the <code>Class</code> to get the short name of * @return the short name */ protected String getShortClassName(Class cls) { String name = cls.getName(); int pos = name.lastIndexOf('.'); if (pos == -1) { return name; } return name.substring(pos + 1); } // Setters and getters for the customizable parts of the style // These methods are not expected to be overridden, except to make public // (They are not public so that immutable subclasses can be written) /** * <p>Gets whether to use the class name.</p> * * @return the current useClassName flag */ protected boolean isUseClassName() { return useClassName; } /** * <p>Sets whether to use the class name.</p> * * @param useClassName the new useClassName flag */ protected void setUseClassName(boolean useClassName) { this.useClassName = useClassName; } /** * <p>Gets whether to output short or long class names.</p> * * @return the current shortClassName flag */ protected boolean isShortClassName() { return useShortClassName; } /** * <p>Sets whether to output short or long class names.</p> * * @param shortClassName the new shortClassName flag */ protected void setShortClassName(boolean shortClassName) { this.useShortClassName = shortClassName; } /** * <p>Gets whether to use the identity hash code.</p> * * @return the current useIdentityHashCode flag */ protected boolean isUseIdentityHashCode() { return useIdentityHashCode; } /** * <p>Sets whether to use the identity hash code.</p> * * @param useIdentityHashCode the new useIdentityHashCode flag */ protected void setUseIdentityHashCode(boolean useIdentityHashCode) { this.useIdentityHashCode = useIdentityHashCode; } /** * <p>Gets whether to use the field names passed in.</p> * * @return the current useFieldNames flag */ protected boolean isUseFieldNames() { return useFieldNames; } /** * <p>Sets whether to use the field names passed in.</p> * * @param useFieldNames the new useFieldNames flag */ protected void setUseFieldNames(boolean useFieldNames) { this.useFieldNames = useFieldNames; } /** * <p>Gets whether to use full detail when the caller doesn't * specify.</p> * * @return the current defaultFullDetail flag */ protected boolean isDefaultFullDetail() { return defaultFullDetail; } /** * <p>Sets whether to use full detail when the caller doesn't * specify.</p> * * @param defaultFullDetail the new defaultFullDetail flag */ protected void setDefaultFullDetail(boolean defaultFullDetail) { this.defaultFullDetail = defaultFullDetail; } /** * <p>Gets whether to output array content detail.</p> * * @return the current array content detail setting */ protected boolean isArrayContentDetail() { return arrayContentDetail; } /** * <p>Sets whether to output array content detail.</p> * * @param arrayContentDetail the new arrayContentDetail flag */ protected void setArrayContentDetail(boolean arrayContentDetail) { this.arrayContentDetail = arrayContentDetail; } /** * <p>Gets the array start text.</p> * * @return the current array start text */ protected String getArrayStart() { return arrayStart; } /** * <p>Sets the array start text.</p> * * <p><code>Null</code> is accepted, but will be converted to * a emptry String.</p> * * @param arrayStart the new array start text */ protected void setArrayStart(String arrayStart) { if (arrayStart == null) { arrayStart = ""; } this.arrayStart = arrayStart; } /** * <p>Gets the array end text.</p> * * @return the current array end text */ protected String getArrayEnd() { return arrayEnd; } /** * <p>Sets the array end text.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param arrayEnd the new array end text */ protected void setArrayEnd(String arrayEnd) { if (arrayStart == null) { arrayStart = ""; } this.arrayEnd = arrayEnd; } /** * <p>Gets the array separator text.</p> * * @return the current array separator text */ protected String getArraySeparator() { return arraySeparator; } /** * <p>Sets the array separator text.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param arraySeparator the new array separator text */ protected void setArraySeparator(String arraySeparator) { if (arraySeparator == null) { arraySeparator = ""; } this.arraySeparator = arraySeparator; } /** * <p>Gets the content start text.</p> * * @return the current content start text */ protected String getContentStart() { return contentStart; } /** * <p>Sets the content start text.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param contentStart the new content start text */ protected void setContentStart(String contentStart) { if (contentStart == null) { contentStart = ""; } this.contentStart = contentStart; } /** * <p>Gets the content end text.</p> * * @return the current content end text */ protected String getContentEnd() { return contentEnd; } /** * <p>Sets the content end text.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param contentEnd the new content end text */ protected void setContentEnd(String contentEnd) { if (contentEnd == null) { contentEnd = ""; } this.contentEnd = contentEnd; } /** * <p>Gets the field name value separator text.</p> * * @return the current field name value separator text */ protected String getFieldNameValueSeparator() { return fieldNameValueSeparator; } /** * <p>Sets the field name value separator text.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param fieldNameValueSeparator the new field name value separator text */ protected void setFieldNameValueSeparator(String fieldNameValueSeparator) { if (fieldNameValueSeparator == null) { fieldNameValueSeparator = ""; } this.fieldNameValueSeparator = fieldNameValueSeparator; } /** * <p>Gets the field separator text.</p> * * @return the current field separator text */ protected String getFieldSeparator() { return fieldSeparator; } /** * <p>Sets the field separator text.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param fieldSeparator the new field separator text */ protected void setFieldSeparator(String fieldSeparator) { if (fieldSeparator == null) { fieldSeparator = ""; } this.fieldSeparator = fieldSeparator; } /** * <p>Gets the text to output when <code>null</code> found.</p> * * @return the current text to output when null found */ protected String getNullText() { return nullText; } /** * <p>Sets the text to output when <code>null</code> found.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param nullText the new text to output when null found */ protected void setNullText(String nullText) { if (nullText == null) { nullText = ""; } this.nullText = nullText; } /** * <p>Gets the text to output when a <code>Collection</code>, * <code>Map</code> or array size is output.</p> * * <p>This is output before the size value.</p> * * @return the current start of size text */ protected String getSizeStartText() { return sizeStartText; } /** * <p>Sets the text to output when a <code>Collection</code>, * <code>Map</code> or array size is output.</p> * * <p>This is output before the size value.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param sizeStartText the new start of size text */ protected void setSizeStartText(String sizeStartText) { if (sizeStartText == null) { sizeStartText = ""; } this.sizeStartText = sizeStartText; } /** * <p>Gets the text to output when a <code>Collection</code>, * <code>Map</code> or array size is output.</p> * * <p>This is output after the size value.</p> * * @return the current end of size text */ protected String getSizeEndText() { return sizeEndText; } /** * <p>Sets the text to output when a <code>Collection</code>, * <code>Map</code> or array size is output.</p> * * <p>This is output after the size value.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param sizeEndText the new end of size text */ protected void setSizeEndText(String sizeEndText) { if (sizeEndText == null) { sizeEndText = ""; } this.sizeEndText = sizeEndText; } /** * <p>Gets the text to output when an <code>Object</code> is * output in summary mode.</p> * * <p>This is output before the size value.</p> * * @return the current start of summary text */ protected String getSummaryObjectStartText() { return summaryObjectStartText; } /** * <p>Sets the text to output when an <code>Object</code> is * output in summary mode.</p> * * <p>This is output before the size value.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param summaryObjectStartText the new start of summary text */ protected void setSummaryObjectStartText(String summaryObjectStartText) { if (summaryObjectStartText == null) { summaryObjectStartText = ""; } this.summaryObjectStartText = summaryObjectStartText; } /** * <p>Gets the text to output when an <code>Object</code> is * output in summary mode.</p> * * <p>This is output after the size value.</p> * * @return the current end of summary text */ protected String getSummaryObjectEndText() { return summaryObjectEndText; } /** * <p>Sets the text to output when an <code>Object</code> is * output in summary mode.</p> * * <p>This is output after the size value.</p> * * <p><code>Null</code> is accepted, but will be converted to * a empty String.</p> * * @param summaryObjectEndText the new end of summary text */ protected void setSummaryObjectEndText(String summaryObjectEndText) { if (summaryObjectEndText == null) { summaryObjectEndText = ""; } this.summaryObjectEndText = summaryObjectEndText; } /** * <p>Default <code>ToStringStyle</code>.</p> * * <p>This is an inner class rather than using * <code>StandardToStringStyle</code> to ensure its immutability.</p> */ static final class DefaultToStringStyle extends ToStringStyle { /** * <p>Constructor</p> * * <p>Use the static constant rather than instantiating.</p> */ DefaultToStringStyle() { super(); } /** * <p>Ensure <code>Singleton</code> after serialization.</p> * * @return the singleton */ private Object readResolve() { return ToStringStyle.DEFAULT_STYLE; } } /** * <p><code>ToStringStyle</code> that does not print out * the field names.</p> * * <p>This is an inner class rather than using * <code>StandardToStringStyle</code> to ensure its immutability. */ static final class NoFieldNameToStringStyle extends ToStringStyle { /** * <p>Constructor</p> * * <p>Use the static constant rather than instantiating.</p> */ NoFieldNameToStringStyle() { super(); setUseFieldNames(false); } /** * <p>Ensure <code>Singleton</code> after serialization.</p> * * @return the singleton */ private Object readResolve() { return ToStringStyle.NO_FIELD_NAMES_STYLE; } } /** * <p><code>ToStringStyle</code> that does not print out the * classname, identity hashcode, content start or field name.</p> * * <p>This is an inner class rather than using * <code>StandardToStringStyle</code> to ensure its immutability.</p> */ static final class SimpleToStringStyle extends ToStringStyle { /** * <p>Constructor</p> * * <p>Use the static constant rather than instantiating.</p> */ SimpleToStringStyle() { super(); setUseClassName(false); setUseIdentityHashCode(false); setUseFieldNames(false); setContentStart(""); setContentEnd(""); } /** * <p>Ensure <code>Singleton</ode> after serialization.</p> * @return the singleton */ private Object readResolve() { return ToStringStyle.SIMPLE_STYLE; } } /** * <p><code>ToStringStyle</code> that outputs on multiple lines.</p> * * <p>This is an inner class rather than using * <code>StandardToStringStyle</code> to ensure its immutability.</p> */ static final class MultiLineToStringStyle extends ToStringStyle { /** * <p>Constructor</p> * * <p>Use the static constant rather than instantiating.</p> */ MultiLineToStringStyle() { super(); setContentStart("[" + SystemUtils.LINE_SEPARATOR + " "); setFieldSeparator(SystemUtils.LINE_SEPARATOR + " "); setContentEnd(SystemUtils.LINE_SEPARATOR + "]"); } /** * <p>Ensure <code>Singleton</code> after serialization.</p> * * @return the singleton */ private Object readResolve() { return ToStringStyle.MULTI_LINE_STYLE; } } // Removed, as the XML style needs more work for escaping characters, arrays, // collections, maps and embedded beans. // /** // * ToStringStyle that outputs in XML style // */ // private static class XMLToStringStyle extends ToStringStyle { // /** // * Constructor - use the static constant rather than instantiating. // */ // private XMLToStringStyle() { // super(); // nullText = "null"; // sizeStartText = "size="; // sizeEndText = ""; // /** // * @see ToStringStyle#appendStart(StringBuffer, Object) // */ // public void appendStart(StringBuffer buffer, Object object) { // buffer.append('<'); // buffer.append(getShortClassName(object.getClass())); // buffer.append(" class=\""); // appendClassName(buffer, object); // buffer.append("\" hashCode=\""); // appendIdentityHashCode(buffer, object); // buffer.append("\">"); // buffer.append(SystemUtils.LINE_SEPARATOR); // buffer.append(" "); // /** // * @see ToStringStyle#appendFieldStart(StringBuffer, String) // */ // protected void appendFieldStart(StringBuffer buffer, String fieldName) { // buffer.append('<'); // buffer.append(fieldName); // buffer.append('>'); // /** // * @see ToStringStyle#appendFieldEnd(StringBuffer, String) // */ // protected void appendFieldEnd(StringBuffer buffer, String fieldName) { // buffer.append("</"); // buffer.append(fieldName); // buffer.append('>'); // buffer.append(SystemUtils.LINE_SEPARATOR); // buffer.append(" "); // /** // * @see ToStringStyle#appendEnd(StringBuffer, Object) // */ // public void appendEnd(StringBuffer buffer, Object object) { // int len = buffer.length(); // if (len > 2 && buffer.charAt(len - 1) == ' ' && buffer.charAt(len - 2) == ' ') { // buffer.setLength(len - 2); // buffer.append("</"); // buffer.append(getShortClassName(object.getClass())); // buffer.append("\">"); }
package co.yiiu.pybbs.config; import co.yiiu.pybbs.interceptor.CommonInterceptor; import co.yiiu.pybbs.interceptor.UserApiInterceptor; import co.yiiu.pybbs.interceptor.UserInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import java.util.Locale; @Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { @Autowired private CommonInterceptor commonInterceptor; @Autowired private UserInterceptor userInterceptor; @Autowired private UserApiInterceptor userApiInterceptor; @Override protected void addCorsMappings(CorsRegistry registry) { super.addCorsMappings(registry);
import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.common.collect.Lists; import edu.emory.mathcs.backport.java.util.Collections; @SuppressWarnings("all") public class PRMC_Sample { private static PRMC_Sample SAMPLE1; private static PRMC_Sample SAMPLE2; String data; String[] array1; String[] array2; public boolean test1(Calendar c) { Date d = c.getTime(); long l = d.getTime(); Date e = c.getTime(); long j = e.getTime(); return l == j; } public void rmcFP(ByteBuffer bb) { int i = bb.getInt(); int j = bb.getInt(); } @Override public boolean equals(Object o) { PRMC_Sample rmc = (PRMC_Sample) o; if (data.equals("INF") || rmc.data.equals("INF")) { return false; } return data.equals(rmc.data); } public void staticPRMC() { Factory.getInstance().fee(); Factory.getInstance().fi(); Factory.getInstance().fo(); Factory.getInstance().fum(); } public void repeatedEmptyArrays() { System.out.println(Arrays.asList(new Integer[0])); System.out.println(Arrays.asList(new Integer[0])); } static class Factory { private static Factory f = new Factory(); private Factory() { } public static Factory getInstance() { return f; } public void fee() { } public void fi() { } public void fo() { } public void fum() { } } public long fpCurrentTimeMillis(Object o) { long time = -System.currentTimeMillis(); o.hashCode(); time += System.currentTimeMillis(); return time; } public void fpEnumToString(FPEnum e) { Set<String> s = new HashSet<String>(); s.add(FPEnum.fee.toString()); s.add(FPEnum.fi.toString()); s.add(FPEnum.fo.toString()); s.add(FPEnum.fum.toString()); } public void emptyList() { List l = Collections.emptyList(); List o = Collections.emptyList(); List p = Collections.emptyList(); } enum FPEnum { fee, fi, fo, fum }; public boolean validChainedFields(Chain c1) { return c1.chainedField.toString().equals(c1.chainedField.toString()); } public boolean fpChainedFieldsOfDiffBases(Chain c1, Chain c2) { return c1.chainedField.toString().equals(c2.chainedField.toString()); } public void fpMultipleStatics() { SAMPLE1 = new PRMC_Sample(); SAMPLE1.setValue(5); SAMPLE2 = new PRMC_Sample(); SAMPLE2.setValue(5); } public void fpWithGuava() { List<String> l = Lists.newArrayList(); List<String> ll = Lists.newArrayList(); } public void fpAsListLiterals() { System.out.println(Arrays.asList("foo")); System.out.println(Arrays.asList("bar")); } public void setValue(int i) { } class Chain { public Chain chainedField; @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" sb.append("XX"); sb.append(" sb.append("XX"); sb.append(" sb.append("XX"); sb.append(" sb.append("XX"); sb.append(" sb.append("XX"); sb.append(" return sb.toString(); } } class SFIssue71 { protected String[] inc = new String[0]; protected String[] dec = new String[0]; public void fplog() { System.out.println(Arrays.toString(inc)); System.out.println(Arrays.toString(dec)); } }}
package com.andrsam.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.approval.ApprovalStore; import org.springframework.security.oauth2.provider.approval.TokenApprovalStore; import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler; import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private ClientDetailsService clientDetailsService; @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception {
package org.apache.velocity.runtime.directive; import java.io.Writer; import java.io.IOException; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; import org.apache.velocity.Context; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.util.ClassUtils; import org.apache.velocity.util.ArrayIterator; import org.apache.velocity.runtime.parser.Token; import org.apache.velocity.runtime.parser.node.Node; import org.apache.velocity.runtime.exception.ReferenceException; /** * Foreach directive used for moving through arrays, * or objects that provide an Iterator. */ public class Foreach extends Directive { private final static int ARRAY = 1; private final static int ITERATOR = 2; private final static String COUNTER_IDENTIFIER = Runtime.getString(Runtime.COUNTER_NAME); private final static int COUNTER_INITIAL_VALUE = new Integer(Runtime.getString(Runtime.COUNTER_INITIAL_VALUE)).intValue(); private String elementKey; private Object listObject; private Object tmp; private int iterator; public String getName() { return "foreach"; } public int getType() { return BLOCK; } public void init(Context context, Node node) throws Exception { Object sampleElement = null; elementKey = node.jjtGetChild(0).getFirstToken().image.substring(1); // This is a refence node and it needs to // be inititialized. node.jjtGetChild(2).init(context, null); listObject = node.jjtGetChild(2).value(context); // If the listObject is null then we know that this // whole foreach directive is useless. We need to // throw a ReferenceException which is caught by // the SimpleNode.init() and logged. But we also need // to set a flag so that the rendering of this node // is ignored as the output would be useless. if (listObject == null) { node.setInvalid(); throw new ReferenceException("#foreach", node.jjtGetChild(2)); } // Figure out what type of object the list // element is so that we don't have to do it // everytime the node is traversed. if (listObject instanceof Object[]) { node.setInfo(ARRAY); sampleElement = ((Object[]) listObject)[0]; } else if (ClassUtils.implementsMethod(listObject, "iterator")) { node.setInfo(ITERATOR); sampleElement = ((Collection) listObject).iterator().next(); } // This is a little trick so that we can initialize // all the blocks in the foreach properly given // that there are references that refer to the // elementKey name. if (sampleElement != null) { context.put(elementKey, sampleElement); super.init(context, node); context.remove(elementKey); } } public boolean render(Context context, Writer writer, Node node) throws IOException { if (node.isInvalid()) return false; Iterator i; listObject = node.jjtGetChild(2).value(context); if (node.getInfo() == ARRAY) i = new ArrayIterator((Object[]) listObject); else i = ((Collection) listObject).iterator(); iterator = COUNTER_INITIAL_VALUE; while (i.hasNext()) { context.put(COUNTER_IDENTIFIER, new Integer(iterator)); context.put(elementKey,i.next()); node.jjtGetChild(3).render(context, writer); iterator++; } context.remove(COUNTER_IDENTIFIER); context.remove(elementKey); return true; } }
package com.opengamma.financial.security.cds; import java.io.Serializable; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import com.google.common.collect.ImmutableSortedSet; import com.opengamma.util.ArgumentChecker; /** * Immutable set of {@link CreditDefaultSwapIndexComponent} that represents the CreditDefaultSwapIndexSecurity components * <p> * It uses a comparator based on the ObligorCode of each components as suppose to natural ordering of weight and name * */ public final class CDSIndexComponentBundle implements Iterable<CreditDefaultSwapIndexComponent>, Serializable { /** Serialization version. */ private static final long serialVersionUID = 1L; /** * Comparator to use for sorting */ private static final Comparator<CreditDefaultSwapIndexComponent> s_obligorComparator = new CDSIndexComponentObligorComparator(); /** * The set of cdsIndex components. */ private final ImmutableSortedSet<CreditDefaultSwapIndexComponent> _components; /** * Creates a cdsIndex components bundle from a set of cdsIndex component. * * @param tenors the set of tenors, assigned, not null */ private CDSIndexComponentBundle(ImmutableSortedSet<CreditDefaultSwapIndexComponent> components) { _components = components; } /** * Obtains a {@link CDSIndexComponentBundle} from a {@link CreditDefaultSwapIndexComponent}. * * @param component the cdsindex component to warp in the bundle, not null * @return the cdsIndex components bundle, not null */ public static CDSIndexComponentBundle of(CreditDefaultSwapIndexComponent component) { ArgumentChecker.notNull(component, "component"); return new CDSIndexComponentBundle(ImmutableSortedSet.of(component)); } /** * Obtains a {@link CDSIndexComponentBundle} from a collection of CreditDefaultSwapIndexComponents. * * @param components the collection of components, no nulls, not null * @return the cdsIndex components bundle, not null */ public static CDSIndexComponentBundle of(Iterable<CreditDefaultSwapIndexComponent> components) { return create(components); } /** * Obtains a {@link CDSIndexComponentBundle} from an array of CreditDefaultSwapIndexComponents. * * @param components an array of components, no nulls, not null * @return the cdsIndex components bundle, not null */ public static CDSIndexComponentBundle of(CreditDefaultSwapIndexComponent... components) { return create(Arrays.asList(components)); } /** * Obtains an {@link CDSIndexComponentBundle} from a collection of {@link CreditDefaultSwapIndexComponent}. * * @param components the collection of components * @return the bundle, not null */ private static CDSIndexComponentBundle create(Iterable<CreditDefaultSwapIndexComponent> components) { ArgumentChecker.notEmpty(components, "components"); ArgumentChecker.noNulls(components, "components"); return new CDSIndexComponentBundle(ImmutableSortedSet.copyOf(s_obligorComparator, components)); } /** * Gets the set of {@link CreditDefaultSwapIndexComponent} in the cdsIndex components bundle. * * @return the tenor set, unmodifiable, not null */ public Set<CreditDefaultSwapIndexComponent> getComponents() { return _components; } /** * Returns a new {@link CDSIndexComponentBundle} with the specified {@link CreditDefaultSwapIndexComponent} added. This instance is immutable and unaffected by this method call. * * @param component the cdsindex component to add to the returned bundle, not null * @return the new bundle, not null */ public CDSIndexComponentBundle withCDSIndexComponent(final CreditDefaultSwapIndexComponent component) { ArgumentChecker.notNull(component, "component"); final Set<CreditDefaultSwapIndexComponent> components = new HashSet<>(_components); if (components.add(component) == false) { return this; } return create(components); } /** * Returns a new {@link CDSIndexComponentBundle} with the specified {@link CreditDefaultSwapIndexComponent}s added. This instance is immutable and unaffected by this method call. * * @param components the identifiers to add to the returned bundle, not null * @return the new bundle, not null */ public CDSIndexComponentBundle withCDSIndexComponents(final Iterable<CreditDefaultSwapIndexComponent> components) { ArgumentChecker.notNull(components, "components"); final Set<CreditDefaultSwapIndexComponent> toAdd = ImmutableSortedSet.copyOf(components); final Set<CreditDefaultSwapIndexComponent> latest = new HashSet<CreditDefaultSwapIndexComponent>(_components); if (latest.addAll(toAdd) == false) { return this; } return create(latest); } /** * Returns a new bundle using a custom comparator for ordering. Primarily useful for display. * * @param comparator comparator specifying how to order the ExternalIds * @return the new copy of the bundle, ordered by the comparator */ public CDSIndexComponentBundle withCustomIdOrdering(final Comparator<CreditDefaultSwapIndexComponent> comparator) { return new CDSIndexComponentBundle(ImmutableSortedSet.orderedBy(comparator).addAll(_components).build()); } /** * Gets the number of components in the bundle. * * @return the bundle size, zero or greater */ public int size() { return _components.size(); } /** * Returns true if this bundle contains no components. * * @return true if this bundle contains no components, false otherwise */ public boolean isEmpty() { return _components.isEmpty(); } /** * Returns an iterator over the components in the bundle. * * @return the components in the bundle, not null */ @Override public Iterator<CreditDefaultSwapIndexComponent> iterator() { return _components.iterator(); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } private static class CDSIndexComponentObligorComparator implements Comparator<CreditDefaultSwapIndexComponent> { @Override public int compare(final CreditDefaultSwapIndexComponent left, final CreditDefaultSwapIndexComponent right) { return left.getObligorRedCode().compareTo(right.getObligorRedCode()); } } }
package org.apache.velocity.runtime.directive; import java.io.Writer; import java.io.IOException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.Map; import java.util.Vector; import org.apache.velocity.context.InternalContextAdapter; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.util.ArrayIterator; import org.apache.velocity.runtime.parser.Token; import org.apache.velocity.runtime.parser.ParserTreeConstants; import org.apache.velocity.runtime.parser.node.Node; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.util.introspection.Introspector; import org.apache.velocity.util.introspection.IntrospectionCacheData; /** * Foreach directive used for moving through arrays, * or objects that provide an Iterator. * * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a> * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @version $Id: Foreach.java,v 1.34 2001/03/19 23:52:41 geirm Exp $ */ public class Foreach extends Directive { /** * Return name of this directive. */ public String getName() { return "foreach"; } /** * Return type of this directive. */ public int getType() { return BLOCK; } private final static int UNKNOWN = -1; /** * Flag to indicate that the list object being used * in an array. */ private final static int INFO_ARRAY = 1; /** * Flag to indicate that the list object being used * provides an Iterator. */ private final static int INFO_ITERATOR = 2; /** * Flag to indicate that the list object being used * is a Map. */ private final static int INFO_MAP = 3; /** * Flag to indicate that the list object being used * is a Collection. */ private final static int INFO_COLLECTION = 4; /** * The name of the variable to use when placing * the counter value into the context. Right * now the default is $velocityCount. */ private final static String COUNTER_NAME = Runtime.getString(Runtime.COUNTER_NAME); /** * What value to start the loop counter at. */ private final static int COUNTER_INITIAL_VALUE = Runtime.getInt(Runtime.COUNTER_INITIAL_VALUE); /** * The reference name used to access each * of the elements in the list object. It * is the $item in the following: * * #foreach ($item in $list) * * This can be used class wide because * it is immutable. */ private String elementKey; /** * simple init - init the tree and get the elementKey from * the AST */ public void init( InternalContextAdapter context, Node node) throws Exception { super.init( context, node ); /* * this is really the only thing we can do here as everything * else is context sensitive */ elementKey = node.jjtGetChild(0).getFirstToken().image.substring(1); } /** * returns an Iterator to the collection in the #foreach() * * @param context current context * @param node AST node * @return Iterator to do the dataset */ private Iterator getIterator( InternalContextAdapter context, Node node ) throws MethodInvocationException { /* * get our list object, and punt if it's null. */ Object listObject = node.jjtGetChild(2).value(context); if (listObject == null) return null; /* * See if we already know what type this is. Use the introspection cache */ int type = UNKNOWN; IntrospectionCacheData icd = context.icacheGet( this ); Class c = listObject.getClass(); /* * if we have an entry in the cache, and the Class we have * cached is the same as the Class of the data object * then we are ok */ if ( icd != null && icd.contextData == c ) { /* dig the type out of the cata object */ type = ((Integer) icd.thingy ).intValue(); } /* * If we still don't know what this is, * figure out what type of object the list * element is, and get the iterator for it */ if ( type == UNKNOWN ) { if (listObject instanceof Object[]) type = INFO_ARRAY; else if ( listObject instanceof Collection) type = INFO_COLLECTION; else if ( listObject instanceof Map ) type = INFO_MAP; else if ( listObject instanceof Iterator ) type = INFO_ITERATOR; /* * if we did figure it out, cache it */ if ( type != UNKNOWN ) { icd = new IntrospectionCacheData(); icd.thingy = new Integer( type ); icd.contextData = c; context.icachePut( this, icd ); } } /* * now based on the type from either cache or examination... */ switch( type ) { case INFO_COLLECTION : return ( (Collection) listObject).iterator(); case INFO_ITERATOR : Runtime.warn ("Warning! The reference " + node.jjtGetChild(2).getFirstToken().image + " is an Iterator in the #foreach() loop at [" + getLine() + "," + getColumn() + "]" + " in template " + context.getCurrentTemplateName() + ". If used in more than once, this may lead to unexpected results."); return ( (Iterator) listObject); case INFO_ARRAY: return new ArrayIterator( (Object [] ) listObject ); case INFO_MAP: return ( (Map) listObject).values().iterator(); default: /* we have no clue what this is */ Runtime.warn ("Could not determine type of iterator in " + "#foreach loop for " + node.jjtGetChild(2).getFirstToken().image + " at [" + getLine() + "," + getColumn() + "]" + " in template " + context.getCurrentTemplateName() ); return null; } } /** * renders the #foreach() block */ public boolean render( InternalContextAdapter context, Writer writer, Node node) throws IOException, MethodInvocationException { /* * do our introspection to see what our collection is */ Iterator i = getIterator( context, node ); if ( i == null ) return false; int counter = COUNTER_INITIAL_VALUE; /* * save the element key if there is one, * and the loop counter */ Object o = context.get( elementKey ); Object ctr = context.get( COUNTER_NAME ); while (i.hasNext()) { context.put(COUNTER_NAME, new Integer(counter)); context.put(elementKey,i.next()); node.jjtGetChild(3).render(context, writer); counter++; } /* * restores the loop counter (if we were nested) * if we have one, else just removes */ if( ctr != null) { context.put( COUNTER_NAME, ctr ); } else { context.remove(COUNTER_NAME); } /* * restores element key if exists * otherwise just removes */ if (o != null) { context.put( elementKey, o ); } else { context.remove(elementKey); } return true; } }
package com.opengamma.integration.regression; import java.io.IOException; import java.util.Collection; import java.util.Set; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.opengamma.bbg.referencedata.ReferenceData; import com.opengamma.bbg.referencedata.impl.InMemoryCachingReferenceDataProvider; import com.opengamma.id.UniqueId; import com.opengamma.id.UniqueIdentifiable; import com.opengamma.integration.tool.IntegrationToolContext; import com.opengamma.master.AbstractDocument; import com.opengamma.master.AbstractMaster; import com.opengamma.master.config.ConfigDocument; import com.opengamma.master.config.ConfigMaster; import com.opengamma.master.config.impl.DataTrackingConfigMaster; import com.opengamma.master.convention.ConventionDocument; import com.opengamma.master.convention.ConventionMaster; import com.opengamma.master.convention.impl.DataTrackingConventionMaster; import com.opengamma.master.exchange.ExchangeDocument; import com.opengamma.master.exchange.ExchangeMaster; import com.opengamma.master.exchange.impl.DataTrackingExchangeMaster; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesInfoDocument; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesMaster; import com.opengamma.master.historicaltimeseries.impl.DataTrackingHistoricalTimeSeriesMaster; import com.opengamma.master.holiday.HolidayDocument; import com.opengamma.master.holiday.HolidayMaster; import com.opengamma.master.holiday.impl.DataTrackingHolidayMaster; import com.opengamma.master.legalentity.LegalEntityDocument; import com.opengamma.master.legalentity.LegalEntityMaster; import com.opengamma.master.legalentity.impl.DataTrackingLegalEntityMaster; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotDocument; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotMaster; import com.opengamma.master.marketdatasnapshot.impl.DataTrackingMarketDataSnapshotMaster; import com.opengamma.master.portfolio.PortfolioDocument; import com.opengamma.master.portfolio.PortfolioMaster; import com.opengamma.master.portfolio.impl.DataTrackingPortfolioMaster; import com.opengamma.master.position.PositionDocument; import com.opengamma.master.position.PositionMaster; import com.opengamma.master.position.impl.DataTrackingPositionMaster; import com.opengamma.master.security.SecurityDocument; import com.opengamma.master.security.SecurityMaster; import com.opengamma.master.security.impl.DataTrackingSecurityMaster; /** * Executes a DB dump, only including the records which have been accessed. */ class GoldenCopyDumpCreator { public static final String DB_DUMP_ZIP = "dbdump.zip"; private final RegressionIO _regressionIO; private final DataTrackingSecurityMaster _securityMaster; private final DataTrackingPositionMaster _positionMaster; private final DataTrackingPortfolioMaster _portfolioMaster; private final DataTrackingConfigMaster _configMaster; private final DataTrackingHistoricalTimeSeriesMaster _timeSeriesMaster; private final DataTrackingHolidayMaster _holidayMaster; private final DataTrackingExchangeMaster _exchangeMaster; private final DataTrackingMarketDataSnapshotMaster _snapshotMaster; private final DataTrackingLegalEntityMaster _legalEntityMaster; private final DataTrackingConventionMaster _conventionMaster; private InMemoryCachingReferenceDataProvider _referenceDataProvider; public GoldenCopyDumpCreator(RegressionIO regressionIO, IntegrationToolContext tc) { _regressionIO = regressionIO; _securityMaster = (DataTrackingSecurityMaster) tc.getSecurityMaster(); _positionMaster = (DataTrackingPositionMaster) tc.getPositionMaster(); _portfolioMaster = (DataTrackingPortfolioMaster) tc.getPortfolioMaster(); _configMaster = (DataTrackingConfigMaster) tc.getConfigMaster(); _timeSeriesMaster = (DataTrackingHistoricalTimeSeriesMaster) tc.getHistoricalTimeSeriesMaster(); _holidayMaster = (DataTrackingHolidayMaster) tc.getHolidayMaster(); _exchangeMaster = (DataTrackingExchangeMaster) tc.getExchangeMaster(); _snapshotMaster = (DataTrackingMarketDataSnapshotMaster) tc.getMarketDataSnapshotMaster(); _legalEntityMaster = (DataTrackingLegalEntityMaster) tc.getLegalEntityMaster(); _conventionMaster = (DataTrackingConventionMaster) tc.getConventionMaster(); _referenceDataProvider = (InMemoryCachingReferenceDataProvider) tc.getBloombergReferenceDataProvider(); } /** * Run the db dump, building appropriate filters from the passed DataTracking masters. * @throws IOException */ public void execute() throws IOException { MasterQueryManager filterManager = buildFilterManager(); _regressionIO.beginWrite(); try { //dump ref data accesses first ImmutableMap<String, ReferenceData> dataAccessed; if (_referenceDataProvider != null) { dataAccessed = _referenceDataProvider.getDataAccessed(); } else { dataAccessed = ImmutableMap.of(); } _regressionIO.write(null, RegressionReferenceData.create(dataAccessed), RegressionUtils.REF_DATA_ACCESSES_IDENTIFIER); DatabaseDump databaseDump = new DatabaseDump(_regressionIO, _securityMaster, _positionMaster, _portfolioMaster, _configMaster, _timeSeriesMaster, _holidayMaster, _exchangeMaster, _snapshotMaster, _legalEntityMaster, _conventionMaster, filterManager); databaseDump.dumpDatabase(); } finally { _regressionIO.endWrite(); } } private MasterQueryManager buildFilterManager() { return new MasterQueryManager( new UniqueIdentifiableQuery<SecurityDocument, SecurityMaster>(_securityMaster.getIdsAccessed()), new UniqueIdentifiableQuery<PositionDocument, PositionMaster>(_positionMaster.getIdsAccessed()), new UniqueIdentifiableQuery<PortfolioDocument, PortfolioMaster>(_portfolioMaster.getIdsAccessed()), new UniqueIdentifiableQuery<ConfigDocument, ConfigMaster>(_configMaster.getIdsAccessed()), new UniqueIdentifiableQuery<HistoricalTimeSeriesInfoDocument, HistoricalTimeSeriesMaster>(_timeSeriesMaster.getIdsAccessed()), new UniqueIdentifiableQuery<HolidayDocument, HolidayMaster>(_holidayMaster.getIdsAccessed()), new UniqueIdentifiableQuery<ExchangeDocument, ExchangeMaster>(_exchangeMaster.getIdsAccessed()), new UniqueIdentifiableQuery<MarketDataSnapshotDocument, MarketDataSnapshotMaster>(_snapshotMaster.getIdsAccessed()), new UniqueIdentifiableQuery<LegalEntityDocument, LegalEntityMaster>(_legalEntityMaster.getIdsAccessed()), new UniqueIdentifiableQuery<ConventionDocument, ConventionMaster>(_conventionMaster.getIdsAccessed())); } /** * Filter which checks a {@link UniqueIdentifiable} object is identified by one of * a set of ids. */ private static class UniqueIdentifiableQuery<D extends AbstractDocument, M extends AbstractMaster<D>> implements Function<M, Collection<D>> { private Set<UniqueId> _idsToInclude; public UniqueIdentifiableQuery(Set<UniqueId> uniqueId) { _idsToInclude = uniqueId; } @Override public Collection<D> apply(M input) { return input.get(_idsToInclude).values(); } } }
package com.bfwg.config; import com.bfwg.security.TokenHelper; import com.bfwg.security.auth.RestAuthenticationEntryPoint; import com.bfwg.security.auth.TokenAuthenticationFilter; import com.bfwg.service.impl.CustomUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Autowired private CustomUserDetailsService jwtUserDetailsService; @Autowired private RestAuthenticationEntryPoint restAuthenticationEntryPoint; @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Autowired public void configureGlobal( AuthenticationManagerBuilder auth ) throws Exception { auth.userDetailsService( jwtUserDetailsService ) .passwordEncoder( passwordEncoder() ); } @Autowired TokenHelper tokenHelper; @Override protected void configure(HttpSecurity http) throws Exception { http .sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS ).and() .exceptionHandling().authenticationEntryPoint( restAuthenticationEntryPoint ).and() .authorizeRequests() "*.html", "*.css", "*.js"
package org.apache.velocity.runtime.directive; import java.io.Writer; import java.io.IOException; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; import org.apache.velocity.Context; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.util.ClassUtils; import org.apache.velocity.util.ArrayIterator; import org.apache.velocity.runtime.parser.Node; import org.apache.velocity.runtime.parser.Token; /** * Foreach directive used for moving through arrays, * or objects that provide an Iterator. */ public class Foreach extends Directive { private final static int ARRAY = 1; private final static int ITERATOR = 2; private final static String COUNTER_IDENTIFIER = Runtime.getString(Runtime.COUNTER_NAME); private final static int COUNTER_INITIAL_VALUE = new Integer(Runtime.getString(Runtime.COUNTER_INITIAL_VALUE)).intValue(); private String elementKey; private Object listObject; private Object tmp; private int iterator; public String getName() { return "foreach"; } public int getType() { return BLOCK; } public void init(Context context, Node node) throws Exception { Object sampleElement = null; elementKey = node.jjtGetChild(0).getFirstToken().image.substring(1); // This is a refence node and it needs to // be inititialized. node.jjtGetChild(2).init(context, null); listObject = node.jjtGetChild(2).value(context); // Figure out what type of object the list // element is so that we don't have to do it // everytime the node is traversed. if (listObject instanceof Object[]) { node.setInfo(ARRAY); sampleElement = ((Object[]) listObject)[0]; } else if (ClassUtils.implementsMethod(listObject, "iterator")) { node.setInfo(ITERATOR); sampleElement = ((Collection) listObject).iterator().next(); } // This is a little trick so that we can initialize // all the blocks in the foreach properly given // that there are references that refer to the // elementKey name. if (sampleElement != null) { context.put(elementKey, sampleElement); super.init(context, node); context.remove(elementKey); } } public void render(Context context, Writer writer, Node node) throws IOException { Iterator i; listObject = node.jjtGetChild(2).value(context); if (node.getInfo() == ARRAY) i = new ArrayIterator((Object[]) listObject); else i = ((Collection) listObject).iterator(); iterator = COUNTER_INITIAL_VALUE; while (i.hasNext()) { context.put(COUNTER_IDENTIFIER, new Integer(iterator)); context.put(elementKey,i.next()); node.jjtGetChild(3).render(context, writer); iterator++; } context.remove(COUNTER_IDENTIFIER); context.remove(elementKey); } }
package org.batfish.common.bdd; import static org.batfish.datamodel.PacketHeaderConstraintsUtil.DEFAULT_PACKET_LENGTH; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.util.GlobalTracer; import java.util.List; import net.sf.javabdd.BDD; import org.batfish.common.BatfishException; import org.batfish.datamodel.IcmpType; import org.batfish.datamodel.Ip; import org.batfish.datamodel.IpProtocol; import org.batfish.datamodel.NamedPort; import org.batfish.datamodel.Prefix; /** This class generates common useful flow constraints as BDDs. */ public final class BDDFlowConstraintGenerator { /** Allows a caller to express preferences on how packets should be retrieved. */ public enum FlowPreference { /** Prefers ICMP over UDP over TCP. */ DEBUGGING, /** Prefers TCP over UDP over ICMP. */ APPLICATION, /** * Prefers TCP over UDP over ICMP. Not currently different from {@link #APPLICATION}, but may * change. */ TESTFILTER, /** Prefers UDP traceroute. */ TRACEROUTE } @VisibleForTesting static final Prefix PRIVATE_SUBNET_10 = Prefix.parse("10.0.0.0/8"); @VisibleForTesting static final Prefix PRIVATE_SUBNET_172 = Prefix.parse("172.16.0.0/12"); @VisibleForTesting static final Prefix PRIVATE_SUBNET_192 = Prefix.parse("192.168.0.0/16"); @VisibleForTesting static final Prefix RESERVED_DOCUMENTATION_192 = Prefix.parse("192.0.2.0/24"); @VisibleForTesting static final Prefix RESERVED_DOCUMENTATION_198 = Prefix.parse("198.51.100.0/24"); @VisibleForTesting static final Prefix RESERVED_DOCUMENTATION_203 = Prefix.parse("203.0.113.0/24"); static final int UDP_TRACEROUTE_FIRST_PORT = 33434; static final int UDP_TRACEROUTE_LAST_PORT = 33534; private final BDDPacket _bddPacket; private final BDDOps _bddOps; private final List<BDD> _icmpConstraints; private final List<BDD> _udpConstraints; private final List<BDD> _tcpConstraints; private final BDD _defaultPacketLength; private final List<BDD> _ipConstraints; private final BDD _udpTraceroute; BDDFlowConstraintGenerator(BDDPacket pkt) { Span span = GlobalTracer.get().buildSpan("construct BDDFlowConstraintGenerator").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning _bddPacket = pkt; _bddOps = new BDDOps(pkt.getFactory()); _defaultPacketLength = _bddPacket.getPacketLength().value(DEFAULT_PACKET_LENGTH); _udpTraceroute = computeUdpTraceroute(); _icmpConstraints = computeICMPConstraint(); _udpConstraints = computeUDPConstraints(); _tcpConstraints = computeTCPConstraints(); _ipConstraints = computeIpConstraints(); } } private List<BDD> computeICMPConstraint() { BDD icmp = _bddPacket.getIpProtocol().value(IpProtocol.ICMP); BDDIcmpType type = _bddPacket.getIcmpType(); BDD codeZero = _bddPacket.getIcmpCode().value(0); // Prefer ICMP Echo_Request, then anything with code 0, then anything ICMP/ return ImmutableList.of( _bddOps.and(icmp, type.value(IcmpType.ECHO_REQUEST), codeZero), _bddOps.and(icmp, codeZero), icmp); } private BDD emphemeralPort(BDDInteger portInteger) { return portInteger.geq(NamedPort.EPHEMERAL_LOWEST.number()); } private List<BDD> tcpPortPreferences(BDD tcp, BDDInteger tcpPort) { return ImmutableList.of( _bddOps.and(tcp, tcpPort.value(NamedPort.HTTP.number())), _bddOps.and(tcp, tcpPort.value(NamedPort.HTTPS.number())), _bddOps.and(tcp, tcpPort.value(NamedPort.SSH.number())), // at least not zero if possible _bddOps.and(tcp, tcpPort.value(0).not())); } private List<BDD> tcpFlagPreferences(BDD tcp) { return ImmutableList.of( // Force all the rarely used flags off _bddOps.and(tcp, _bddPacket.getTcpCwr().not()), _bddOps.and(tcp, _bddPacket.getTcpEce().not()), _bddOps.and(tcp, _bddPacket.getTcpPsh().not()), _bddOps.and(tcp, _bddPacket.getTcpUrg().not()), // Less rarely used flags _bddOps.and(tcp, _bddPacket.getTcpFin().not()), // Sometimes used flags _bddOps.and(tcp, _bddPacket.getTcpRst().not()), // Prefer SYN, SYN_ACK, ACK _bddOps.and(tcp, _bddPacket.getTcpSyn(), _bddPacket.getTcpAck().not()), _bddOps.and(tcp, _bddPacket.getTcpAck(), _bddPacket.getTcpSyn()), _bddOps.and(tcp, _bddPacket.getTcpAck())); } // Get TCP packets with special named ports, trying to find cases where only one side is // ephemeral. private List<BDD> computeTCPConstraints() { BDDInteger dstPort = _bddPacket.getDstPort(); BDDInteger srcPort = _bddPacket.getSrcPort(); BDD tcp = _bddPacket.getIpProtocol().value(IpProtocol.TCP); BDD srcPortEphemeral = emphemeralPort(srcPort); BDD dstPortEphemeral = emphemeralPort(dstPort); return ImmutableList.<BDD>builder() // First, try to nudge src and dst port apart. E.g., if one is ephemeral the other is not. .add(_bddOps.and(tcp, srcPortEphemeral, dstPortEphemeral.not())) .add(_bddOps.and(tcp, srcPortEphemeral.not(), dstPortEphemeral)) // Next, execute port preferences. .addAll(tcpPortPreferences(tcp, srcPort)) .addAll(tcpPortPreferences(tcp, dstPort)) // Next execute flag preferences. .addAll(tcpFlagPreferences(tcp)) // Anything TCP. .add(tcp) .build(); } private List<BDD> udpPortPreferences(BDD udp, BDDInteger tcpPort) { return ImmutableList.of( _bddOps.and(udp, tcpPort.value(NamedPort.DOMAIN.number())), _bddOps.and(udp, tcpPort.value(NamedPort.SNMP.number())), _bddOps.and(udp, tcpPort.value(NamedPort.SNMPTRAP.number())), // at least not zero if possible _bddOps.and(udp, tcpPort.value(0).not())); } private BDD computeUdpTraceroute() { BDDInteger dstPort = _bddPacket.getDstPort(); BDDInteger srcPort = _bddPacket.getSrcPort(); BDD udp = _bddPacket.getIpProtocol().value(IpProtocol.UDP); return _bddOps.and( udp, dstPort.range(UDP_TRACEROUTE_FIRST_PORT, UDP_TRACEROUTE_LAST_PORT), srcPort.geq(NamedPort.EPHEMERAL_LOWEST.number())); } // Get UDP packets with special named ports, trying to find cases where only one side is // ephemeral. private List<BDD> computeUDPConstraints() { BDDInteger dstPort = _bddPacket.getDstPort(); BDDInteger srcPort = _bddPacket.getSrcPort(); BDD udp = _bddPacket.getIpProtocol().value(IpProtocol.UDP); BDD srcPortEphemeral = emphemeralPort(srcPort); BDD dstPortEphemeral = emphemeralPort(dstPort); return ImmutableList.<BDD>builder() // Try for UDP traceroute. .add(_udpTraceroute) // Next, try to nudge src and dst port apart. E.g., if one is ephemeral the other is not. .add(_bddOps.and(udp, srcPortEphemeral, dstPortEphemeral.not())) .add(_bddOps.and(udp, srcPortEphemeral.not(), dstPortEphemeral)) // Next, execute port preferences .addAll(udpPortPreferences(udp, srcPort)) .addAll(udpPortPreferences(udp, dstPort)) // Anything UDP. .add(udp) .build(); } @VisibleForTesting static BDD isPrivateIp(IpSpaceToBDD ip) { return BDDOps.orNull( ip.toBDD(PRIVATE_SUBNET_10), ip.toBDD(PRIVATE_SUBNET_172), ip.toBDD(PRIVATE_SUBNET_192)); } @VisibleForTesting static BDD isDocumentationIp(IpSpaceToBDD ip) { return BDDOps.orNull( ip.toBDD(RESERVED_DOCUMENTATION_192), ip.toBDD(RESERVED_DOCUMENTATION_198), ip.toBDD(RESERVED_DOCUMENTATION_203)); } private static List<BDD> ipPreferences(BDDInteger ipInteger) { return ImmutableList.of( // First, one of the special IPs. ipInteger.value(Ip.parse("8.8.8.8").asLong()), ipInteger.value(Ip.parse("1.1.1.1").asLong()), // Next, at least don't start with 0. ipInteger.geq(Ip.parse("1.0.0.0").asLong()), // Next, try to be in class A. ipInteger.leq(Ip.parse("126.255.255.254").asLong())); } private List<BDD> computeIpConstraints() { BDD srcIpPrivate = isPrivateIp(_bddPacket.getSrcIpSpaceToBDD()); BDD dstIpPrivate = isPrivateIp(_bddPacket.getDstIpSpaceToBDD()); return ImmutableList.<BDD>builder() // 0. Try to not use documentation IPs if that is possible. .add(isDocumentationIp(_bddPacket.getSrcIpSpaceToBDD()).not()) .add(isDocumentationIp(_bddPacket.getDstIpSpaceToBDD()).not()) // First, try to nudge src and dst IP apart. E.g., if one is private the other should be // public. .add(_bddOps.and(srcIpPrivate, dstIpPrivate.not())) .add(_bddOps.and(srcIpPrivate.not(), dstIpPrivate)) // Next, execute IP preferences .addAll(ipPreferences(_bddPacket.getSrcIp())) .addAll(ipPreferences(_bddPacket.getDstIp())) .build(); } public List<BDD> generateFlowPreference(FlowPreference preference) { switch (preference) { case DEBUGGING: return ImmutableList.<BDD>builder() .addAll(_icmpConstraints) .addAll(_udpConstraints) .addAll(_tcpConstraints) .add(_defaultPacketLength) .addAll(_ipConstraints) .build(); case APPLICATION: case TESTFILTER: return ImmutableList.<BDD>builder() .addAll(_tcpConstraints) .addAll(_udpConstraints) .addAll(_icmpConstraints) .add(_defaultPacketLength) .addAll(_ipConstraints) .build(); case TRACEROUTE: return ImmutableList.<BDD>builder() .addAll(_udpConstraints) .addAll(_tcpConstraints) .addAll(_icmpConstraints) .add(_defaultPacketLength) .addAll(_ipConstraints) .build(); default: throw new BatfishException("Not supported flow preference"); } } }
package com.clinichelper.Entity; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.UUID; @Entity @Table(name="equipments") public class Equipment implements Serializable{ @Id private String equipmentId; @NotNull private String equipmentName; @NotNull private String equipmentUse; private String equipmentDescription; private Integer equipmentInStock; @ManyToMany private Clinic clinic; // Constructores public Equipment(){ } public Equipment(Clinic clinic, String equipmentName, String equipmentUse, String equipmentDescription, Integer equipmentInStock) { this.setEquipmentId(clinic.getClinicPrefix() + "-E-" + UUID.randomUUID().toString().split("-")[0].toUpperCase()); this.setEquipmentName(equipmentName.toUpperCase()); this.setEquipmentUse(equipmentUse); this.setEquipmentDescription(equipmentDescription); this.clinic = clinic; this.setEquipmentInStock(equipmentInStock); } //Getters and Setters public String getEquipmentId() { return equipmentId; } public void setEquipmentId(String equipmentId) { this.equipmentId = equipmentId; } public String getEquipmentName() { return equipmentName; } public void setEquipmentName(String equipmentName) { this.equipmentName = equipmentName; } public String getEquipmentUse() { return equipmentUse; } public void setEquipmentUse(String equipmentUse) { this.equipmentUse = equipmentUse; } public String getEquipmentDescription() { return equipmentDescription; } public void setEquipmentDescription(String equipmentDescription) { this.equipmentDescription = equipmentDescription; } public Integer getEquipmentInStock() { return equipmentInStock; } public void setEquipmentInStock(Integer equipmentInStock) { this.equipmentInStock = equipmentInStock; } }
package org.apache.velocity.runtime.directive; import java.io.*; import org.apache.velocity.context.InternalContextAdapter; import org.apache.velocity.runtime.parser.node.Node; import org.apache.velocity.runtime.RuntimeServices; /** * A very simple directive that leverages the Node.literal() * to grab the literal rendition of a node. We basically * grab the literal value on init(), then repeatedly use * that during render(). * * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> * @version $Id: Literal.java,v 1.7 2002/10/10 16:54:32 dlr Exp $ */ public class Literal extends Directive { String literalText; /** * Return name of this directive. */ public String getName() { return "literal"; } /** * Return type of this directive. */ public int getType() { return BLOCK; } /** * Store the literal rendition of a node using * the Node.literal(). */ public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws Exception { super.init( rs, context, node ); literalText = node.jjtGetChild(0).literal(); } /** * Throw the literal rendition of the block between * #literal()/#end into the writer. */ public boolean render( InternalContextAdapter context, Writer writer, Node node) throws IOException { writer.write(literalText); return true; } }
package com.cloudius.urchin.api; import java.io.StringReader; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonReaderFactory; import javax.json.JsonString; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import com.cloudius.urchin.utils.SnapshotDetailsTabularData; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.WebResource.Builder; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import javax.ws.rs.core.MediaType; public class APIClient { JsonReaderFactory factory = Json.createReaderFactory(null); public static String getBaseUrl() { return "http://" + System.getProperty("apiaddress", "localhost") + ":" + System.getProperty("apiport", "10000"); } public Builder get(String path) { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(UriBuilder.fromUri(getBaseUrl()) .build()); return service.path(path).accept(MediaType.APPLICATION_JSON); } public Builder get(String path, MultivaluedMap<String, String> queryParams) { if (queryParams == null) { return get(path); } ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(UriBuilder.fromUri(getBaseUrl()) .build()); return service.queryParams(queryParams).path(path) .accept(MediaType.APPLICATION_JSON); } public void post(String path, MultivaluedMap<String, String> queryParams) { if (queryParams != null) { get(path, queryParams).post(); return; } get(path).post(); } public void post(String path) { post(path, null); } public void delete(String path, MultivaluedMap<String, String> queryParams) { if (queryParams != null) { get(path, queryParams).delete(); return; } get(path).delete(); } public void delete(String path) { delete(path, null); } public String getStringValue(String string, MultivaluedMap<String, String> queryParams) { if (!string.equals("")) { return get(string, queryParams).get(String.class); } return ""; } public String getStringValue(String string) { return getStringValue(string, null); } public JsonReader getReader(String string, MultivaluedMap<String, String> queryParams) { return factory.createReader(new StringReader(getStringValue(string, queryParams))); } public JsonReader getReader(String string) { return getReader(string, null); } public String[] getStringArrValue(String string) { List<String> val = getListStrValue(string); return val.toArray(new String[val.size()]); } public int getIntValue(String string, MultivaluedMap<String, String> queryParams) { return Integer.parseInt(getStringValue(string, queryParams)); } public int getIntValue(String string) { return getIntValue(string, null); } public boolean getBooleanValue(String string) { return Boolean.parseBoolean(getStringValue(string)); } public double getDoubleValue(String string) { return Double.parseDouble(getStringValue(string)); } public List<String> getListStrValue(String string, MultivaluedMap<String, String> queryParams) { JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); List<String> res = new ArrayList<String>(arr.size()); for (int i = 0; i < arr.size(); i++) { res.add(arr.getString(i)); } reader.close(); return res; } public List<String> getListStrValue(String string) { return getListStrValue(string, null); } public static List<String> listStrFromJArr(JsonArray arr) { List<String> res = new ArrayList<String>(); for (int i = 0; i < arr.size(); i++) { res.add(arr.getString(i)); } return res; } public static Map<String, String> mapStrFromJArr(JsonArray arr) { Map<String, String> res = new HashMap<String, String>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { res.put(obj.getString("key"), obj.getString("value")); } } return res; } public static String join(String[] arr, String joiner) { String res = ""; if (arr != null) { for (String name : arr) { if (name != null && !name.equals("")) { if (!res.equals("")) { res = res + ","; } res = res + name; } } } return res; } public static String join(String[] arr) { return join(arr, ","); } public static boolean set_query_param( MultivaluedMap<String, String> queryParams, String key, String value) { if (queryParams != null && key != null && value != null && !value.equals("")) { queryParams.add(key, value); return true; } return false; } public static boolean set_bool_query_param( MultivaluedMap<String, String> queryParams, String key, boolean value) { if (queryParams != null && key != null && value) { queryParams.add(key, "true"); return true; } return false; } public Map<String, List<String>> getMapStringListStrValue(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<String, List<String>> map = new HashMap<String, List<String>>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { map.put(obj.getString("key"), listStrFromJArr(obj.getJsonArray("value"))); } } reader.close(); return map; } public Map<String, List<String>> getMapStringListStrValue(String string) { return getMapStringListStrValue(string, null); } public Map<List<String>, List<String>> getMapListStrValue(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<List<String>, List<String>> map = new HashMap<List<String>, List<String>>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { map.put(listStrFromJArr(obj.getJsonArray("key")), listStrFromJArr(obj.getJsonArray("value"))); } } reader.close(); return map; } public Map<List<String>, List<String>> getMapListStrValue(String string) { return getMapListStrValue(string, null); } public Set<String> getSetStringValue(String string, MultivaluedMap<String, String> queryParams) { JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Set<String> res = new HashSet<String>(); for (int i = 0; i < arr.size(); i++) { res.add(arr.getString(i)); } reader.close(); return res; } public Set<String> getSetStringValue(String string) { return getSetStringValue(string, null); } public Map<String, String> getMapStrValue(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { map.put(obj.getString("key"), obj.getString("value")); } } reader.close(); return map; } public Map<String, String> getMapStrValue(String string) { return getMapStrValue(string, null); } public List<InetAddress> getListInetAddressValue(String string, MultivaluedMap<String, String> queryParams) { List<String> vals = getListStrValue(string, queryParams); List<InetAddress> res = new ArrayList<InetAddress>(); for (String val : vals) { try { res.add(InetAddress.getByName(val)); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return res; } public List<InetAddress> getListInetAddressValue(String string) { return getListInetAddressValue(string, null); } public Map<String, TabularData> getMapStringTabularDataValue(String string) { // TODO Auto-generated method stub return null; } private TabularDataSupport getSnapshotData(String ks, JsonArray arr) { TabularDataSupport data = new TabularDataSupport( SnapshotDetailsTabularData.TABULAR_TYPE); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("cf")) { SnapshotDetailsTabularData.from(obj.getString("key"), ks, obj.getString("cf"), obj.getInt("total"), obj.getInt("live"), data); } } return data; } public Map<String, TabularData> getMapStringSnapshotTabularDataValue( String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<String, TabularData> map = new HashMap<>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); if (obj.containsKey("key") && obj.containsKey("value")) { String key = obj.getString("key"); map.put(key, getSnapshotData(key, obj.getJsonArray("value"))); } } reader.close(); return map; } public long getLongValue(String string) { return Long.parseLong(getStringValue(string)); } public Map<InetAddress, Float> getMapInetAddressFloatValue(String string) { // TODO Auto-generated method stub return null; } public Map<String, Long> getMapStringLongValue(String string) { // TODO Auto-generated method stub return null; } public long[] getLongArrValue(String string, MultivaluedMap<String, String> queryParams) { JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); long[] res = new long[arr.size()]; for (int i = 0; i < arr.size(); i++) { res[i] = arr.getJsonNumber(i).longValue(); } reader.close(); return res; } public long[] getLongArrValue(String string) { return getLongArrValue(string, null); } public Map<String, Integer> getMapStringIntegerValue(String string) { // TODO Auto-generated method stub return null; } public int[] getIntArrValue(String string) { // TODO Auto-generated method stub return null; } public Map<String, Long> getListMapStringLongValue(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray arr = reader.readArray(); Map<String, Long> map = new HashMap<String, Long>(); for (int i = 0; i < arr.size(); i++) { JsonObject obj = arr.getJsonObject(i); Iterator<String> it = obj.keySet().iterator(); String key = ""; long val = -1; while (it.hasNext()) { String k = it.next(); if (obj.get(k) instanceof JsonString) { key = obj.getString(k); } else { val = obj.getInt(k); } } if (val > 0 && !key.equals("")) { map.put(key, val); } } reader.close(); return map; } public Map<String, Long> getListMapStringLongValue(String string) { return getListMapStringLongValue(string, null); } public JsonArray getJsonArray(String string, MultivaluedMap<String, String> queryParams) { if (string.equals("")) { return null; } JsonReader reader = getReader(string, queryParams); JsonArray res = reader.readArray(); reader.close(); return res; } public JsonArray getJsonArray(String string) { return getJsonArray(string, null); } public List<Map<String, String>> getListMapStrValue(String string, MultivaluedMap<String, String> queryParams) { JsonArray arr = getJsonArray(string, queryParams); List<Map<String, String>> res = new ArrayList<Map<String, String>>(); for (int i = 0; i < arr.size(); i++) { res.add(mapStrFromJArr(arr.getJsonArray(i))); } return res; } public List<Map<String, String>> getListMapStrValue(String string) { return getListMapStrValue(string, null); } public TabularData getCQLResult(String string) { // TODO Auto-generated method stub return null; } }
package com.continuuity.http; import org.jboss.netty.buffer.ChannelBuffer; /** * HttpHandler would extend this abstract class and implement methods to stream the body directly. * chunk method would receive the http-chunks of the body and finished would be called * on receipt of the last chunk. */ public abstract class BodyConsumer { /** * Http request content will be streamed directly to this method. * @param request * @param responder */ abstract void chunk(ChannelBuffer request, HttpResponder responder); /** * This is called on the receipt of the last HttpChunk. * @param responder */ abstract void finished(HttpResponder responder); /** * When there is exception on netty while streaming, it will be propagated to handler * so the handler can do the cleanup. * @param cause */ abstract void handleError(Throwable cause); }
package com.credit.web.common.tag; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import com.gvtv.manage.base.util.PageData; @SuppressWarnings("serial") public class PageTag extends BodyTagSupport { private String href; public int doEndTag() throws JspException { JspWriter out = pageContext.getOut(); HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); PageData pageData = (PageData) request.getAttribute("pd"); if (pageData != null) { PageInfo pageInfo = (PageInfo) pageData.get("pageInfo"); StringBuilder html=new StringBuilder(); int first = pageInfo.getRangeOfFirst(); int end = pageInfo.getRangeOfEnd(); html.append("<form action='"+this.href+"' method='post' id='pageForm' target='_self'>"); html.append("<input type='hidden' name='pageNo' id='pageNo' value='"+pageInfo.getPageNo()+"'>"); html.append("<input type='hidden' name='pageSize' value='"+pageInfo.getPageSize()+"'>"); html.append("<div class='text-center'>"); html.append("<div class='btn-group'>"); html.append("<button class='btn btn-white' onclick='pageSubmit("+(pageInfo.getPageNo()-1)+")'><i class='fa fa-chevron-left'></i></button>"); for (int i=first;i<=end;i++) { if(pageInfo.getPageNo()==i){ html.append("<button class='btn btn-white active' onclick='pageSubmit("+i+")'>"+i+"</button>"); }else{ html.append("<button class='btn btn-white' onclick='pageSubmit("+i+")'>"+i+"</button>"); } } html.append("<button class='btn btn-white' onclick='pageSubmit("+(pageInfo.getPageNo()+1)+")'><i class='fa fa-chevron-right'></i></button>"); html.append(" </div>"); html.append(" </div>"); html.append(" </form>"); try { out.write(html.toString()); } catch (IOException e) { e.printStackTrace(); } } return super.doEndTag(); } public String getHref() { return href; } public void setHref(String href) { this.href = href; } }
package org.jaxen.function; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import junit.framework.TestCase; import org.jaxen.FunctionCallException; import org.jaxen.JaxenException; import org.jaxen.XPath; import org.jaxen.dom.DOMXPath; import org.w3c.dom.Document; /** * @author Elliotte Rusty Harold * */ public class TranslateFunctionTest extends TestCase { private Document doc; public void setUp() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.newDocument(); doc.appendChild(doc.createElement("root")); } public void testTranslate() throws JaxenException { XPath xpath = new DOMXPath( "translate('abc', 'b', 'd')" ); String result = (String) xpath.evaluate( doc ); assertEquals("adc", result); } public void testTranslateIgnoresExtraArguments() throws JaxenException { XPath xpath = new DOMXPath( "translate('abc', 'b', 'dghf')" ); String result = (String) xpath.evaluate( doc ); assertEquals("adc", result); } public void testTranslateFunctionRequiresAtLeastThreeArguments() throws JaxenException { XPath xpath = new DOMXPath("translate('a', 'b')"); try { xpath.selectNodes(doc); fail("Allowed translate function with two arguments"); } catch (FunctionCallException ex) { assertNotNull(ex.getMessage()); } } public void testTranslateRequiresAtMostThreeArguments() throws JaxenException { XPath xpath = new DOMXPath("substring-after('a', 'a', 'a', 'a')"); try { xpath.selectNodes(doc); fail("Allowed translate function with four arguments"); } catch (FunctionCallException ex) { assertNotNull(ex.getMessage()); } } public void testTranslateStringThatContainsNonBMPChars() throws JaxenException { XPath xpath = new DOMXPath( "translate('ab\uD834\uDD00b', 'b', 'd')" ); String result = (String) xpath.evaluate( doc ); assertEquals("ad\uD834\uDD00d", result); } public void testTranslateNonBMPChars() throws JaxenException { XPath xpath = new DOMXPath( "translate('ab\uD834\uDD00b', '\uD834\uDD00', 'd')" ); String result = (String) xpath.evaluate( doc ); assertEquals("abdb", result); } public void testTranslateNonBMPChars2() throws JaxenException { XPath xpath = new DOMXPath( "translate('ab\uD834\uDD00b', '\uD834\uDD00', 'da')" ); String result = (String) xpath.evaluate( doc ); assertEquals("abdb", result); } public void testTranslateWithNonBMPChars() throws JaxenException { XPath xpath = new DOMXPath( "translate('abc', 'c', '\uD834\uDD00b')" ); String result = (String) xpath.evaluate( doc ); assertEquals("ab\uD834\uDD00b", result); } }
package com.deveo.plugin.jenkins; import javax.net.ssl.*; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; public class DeveoAPI { private String hostname; private DeveoAPIKeys deveoAPIKeys; public DeveoAPI(String hostname, DeveoAPIKeys deveoAPIKeys) { this.hostname = hostname; this.deveoAPIKeys = deveoAPIKeys; } private static HttpURLConnection getConnection(URL url) throws IOException { return getConnection(url, false); } private static HttpURLConnection getConnection(URL url, boolean acceptInvalidSSLCertificate) throws IOException { if (acceptInvalidSSLCertificate) { // This is here for testing in environments with invalid certs try { final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } public X509Certificate[] getAcceptedIssuers() { return null; } }}; final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory); ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() { public boolean verify(String string, SSLSession ssls) { return true; } }); return connection; } return connection; } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } catch (KeyManagementException ex) { ex.printStackTrace(); } return null; } else { return (HttpURLConnection) url.openConnection(); } } public void create(String endpoint, String content) throws DeveoException { URL url; HttpURLConnection connection; try { url = new URL(String.format("%s/api/%s", hostname, endpoint)); connection = getConnection(url); connection.setRequestProperty("Accept", "application/vnd.deveo.v1"); connection.setRequestProperty("Authorization", deveoAPIKeys.toString()); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length)); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(content); wr.flush(); wr.close(); BufferedReader in; if (connection.getResponseCode() != HttpURLConnection.HTTP_CREATED) { in = new BufferedReader(new InputStreamReader(connection.getErrorStream())); StringBuffer responseContent = new StringBuffer(); try { String responseLine; while ((responseLine = in.readLine()) != null) { responseContent.append(responseLine); } } catch (Exception ex) { // Ignore } finally { in.close(); throw new DeveoException(String.format("%s %s - %s", connection.getResponseCode(), connection.getResponseMessage(), responseContent.toString())); } } } catch (MalformedURLException e) { throw new DeveoException(String.format("Deveo API hostname could not be parsed: %s", hostname)); } catch (ProtocolException e) { throw new DeveoException(String.format("Deveo connection could not be established due to ProtocolException: %s", e.getMessage())); } catch (IOException e) { throw new DeveoException(String.format("Deveo connection could not be established due to IOException: %s", e.getMessage())); } } }
package com.devmpv.service; import static com.devmpv.config.Const.BOARD; import static com.devmpv.config.Const.TEXT; import static com.devmpv.config.Const.THREAD; import static com.devmpv.config.Const.TITLE; import static com.devmpv.config.WebSocketConfig.MESSAGE_PREFIX; import java.io.IOException; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.annotation.PostConstruct; import javax.transaction.Transactional; import org.jsoup.Jsoup; import org.jsoup.nodes.Document.OutputSettings; import org.jsoup.safety.Whitelist; import org.nibor.autolink.Autolink; import org.nibor.autolink.LinkExtractor; import org.nibor.autolink.LinkSpan; import org.nibor.autolink.LinkType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.hateoas.EntityLinks; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.devmpv.exceptions.CRException; import com.devmpv.model.Attachment; import com.devmpv.model.Board; import com.devmpv.model.Message; import com.devmpv.model.Thread; import com.devmpv.repositories.BoardRepository; import com.devmpv.repositories.MessageRepository; import com.devmpv.repositories.ThreadRepository; import ac.simons.oembed.OembedResponse; import ac.simons.oembed.OembedService; /** * Service to manage basic message operations. * * @author devmpv * */ @Service public class MessageService { private static final String REPLY_STRING = "&gt;&gt;([0-9]{1,8})"; private static final String REPLY_REPLACE = "<a id='reply-link' key='$1'>$1</a>"; @Value("${chan.message.maxCount}") private int messageMaxCount; @Value("${chan.message.bumpLimit}") private int messageBumpLimit; @Value("${chan.thread.maxCount}") private int threadMaxCount; @Autowired private ThreadRepository threadRepo; @Autowired private MessageRepository messageRepo; @Autowired private BoardRepository boardRepo; @Autowired private AttachmentService attachmentService; @Autowired private SimpMessagingTemplate template; @Autowired private EntityLinks entityLinks; @Autowired private OembedService oembedService; private LinkExtractor linkExtractor = LinkExtractor.builder().linkTypes(EnumSet.of(LinkType.URL)).build(); private OutputSettings textSettings = new OutputSettings(); private String getPath(Message message) { return entityLinks.linkForSingleResource(message.getClass(), message.getId()).toUri().getPath(); } private void notify(Message message) { Map<String, Object> headers = new HashMap<>(); headers.put("thread", message.getThread().getId()); template.convertAndSend(MESSAGE_PREFIX + "/newMessage", getPath(message), headers); } @PostConstruct private void postConstruct() { textSettings.prettyPrint(false); } private String prepareText(String input) { String result = Jsoup.clean(input, "", Whitelist.basic(), textSettings).replaceAll(REPLY_STRING, REPLY_REPLACE); Iterable<LinkSpan> links = linkExtractor.extractLinks(result); result = Autolink.renderLinks(result, links, (link, text, sb) -> { String url = text.subSequence(link.getBeginIndex(), link.getEndIndex()).toString(); Optional<OembedResponse> response = oembedService.getOembedResponseFor(url); sb.append("<a href=\"").append(url).append("\">").append(url).append("</a>"); if (response.isPresent()) { sb.append("<div>").append(response.get().getHtml()).append("</div>"); } }); return result; } private Message saveAttachments(Message message, Map<String, MultipartFile> files) { Set<Attachment> result = new HashSet<>(); Set<String> errors = new HashSet<>(); files.forEach((name, file) -> { try { result.add(attachmentService.add(file)); } catch (IllegalStateException | IOException e) { errors.add(name); throw new CRException(e.getMessage(), e); } }); if (!errors.isEmpty()) { throw new CRException("Error saving files: " + errors.toString()); } message.setAttachments(result); return message; } private Message saveMessage(Map<String, String[]> params, Map<String, MultipartFile> files, String text) { Thread thread = threadRepo.findOne(Long.valueOf(params.get(THREAD)[0])); Message message = new Message(params.get(TITLE)[0], text); message.setThread(thread); saveAttachments(message, files); long count = messageRepo.countByThreadId(thread.getId()); if (count < messageBumpLimit) { thread.setUpdated(message.getTimestamp()); threadRepo.save(thread); } if (count >= messageMaxCount) { throw new CRException("Thread limit exceeded!"); } return messageRepo.save(message); } @Transactional public Message saveNew(Map<String, String[]> params, Map<String, MultipartFile> files) { String text = prepareText(params.get(TEXT)[0]); Message result; if (params.containsKey(THREAD)) { result = saveMessage(params, files, text); notify(result); } else { result = saveThread(params, files, text); } return result; } private Thread saveThread(Map<String, String[]> params, Map<String, MultipartFile> files, String text) { Board board = boardRepo.findOne(params.get(BOARD)[0]); long count = threadRepo.countByBoard(board); if (count >= threadMaxCount) { List<Thread> threads = threadRepo.findByBoardOrderByUpdatedAsc(board); for (int i = 0; i < count - (threadMaxCount - 1); i++) { threadRepo.delete(threads.get(i)); } } Thread thread = (Thread) saveAttachments(new Thread(board, params.get(TITLE)[0], text), files); return threadRepo.save(thread); } }
package com.ezardlabs.dethsquare; import java.util.Iterator; public final class Animator extends Script implements Iterable<Animation> { private Animation[] animations; private int index = -1; private int frame = 0; private long nextFrameTime = 0; public Animator(Animation... animations) { this.animations = animations; } public void setAnimations(Animation... animations) { this.animations = animations; } public void addAnimations(Animation... animations) { Animation[] newAnimations = new Animation[this.animations.length + animations.length]; System.arraycopy(this.animations, 0, newAnimations, 0, this.animations.length); System.arraycopy(animations, 0, newAnimations, this.animations.length, animations.length); this.animations = newAnimations; } public void update() { int startFrame = frame; if (index == -1 || frame == -1) return; if (System.currentTimeMillis() >= nextFrameTime) { nextFrameTime += animations[index].frameDuration; frame = animations[index].type.update(frame, animations[index].frames.length); if (frame == -1) { if (animations[index].listener != null) { animations[index].listener.onAnimationFinished(this); } return; } try { gameObject.renderer.sprite = animations[index].frames[frame]; } catch (ArrayIndexOutOfBoundsException ignored) { } } if (frame != startFrame && animations[index].listener != null) { animations[index].listener.onFrame(this, frame); } } public void play(String animationName) { if (index != -1 && animations[index].name.equals(animationName)) return; for (int i = 0; i < animations.length; i++) { if (i != index && animations[i].name.equals(animationName)) { index = i; frame = 0; nextFrameTime = System.currentTimeMillis() + animations[index].frameDuration; gameObject.renderer.sprite = animations[index].frames[frame]; if (animations[index].listener != null) animations[index].listener.onAnimatedStarted(this); break; } } } public Animation getCurrentAnimation() { if (index == -1) return null; else return animations[index]; } public int getCurrentAnimationId() { return index; } public int getCurrentAnimationFrame() { return frame; } @Override public Iterator<Animation> iterator() { return new ObjectIterator<>(animations); } }
package com.fastdtw.dtw.matrix; public interface CostMatrix { void put(int col, int row, double value); double get(int col, int row); int size(); }
package com.github.andriell.general; import java.io.*; public class Files { public static final String DATA_DIR; public static final String PROJECTS_DIR; public static final String DB_DIR; public static final String JS_DIR; static { DATA_DIR = System.getProperty("user.dir") + File.separator + "data"; PROJECTS_DIR = DATA_DIR + File.separator + "projects"; DB_DIR = DATA_DIR + File.separator + "db"; JS_DIR = DATA_DIR + File.separator + "js"; } public static String readFile(File fileName) { try { BufferedReader br = new BufferedReader(new FileReader(fileName)); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append("\n"); line = br.readLine(); } return sb.toString(); } catch (IOException ignored) { } return null; } public static void writeToFile(File fileName, String s) { try { PrintWriter out = new PrintWriter(fileName); out.print(s); out.flush(); out.close(); } catch (FileNotFoundException ignored) { } } }
package net.recommenders.rival.recommend.frameworks; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Properties; public class MultipleRecommendationRunner { public static final String input = "input"; public static final String mahoutItemBasedRecs = "mahout.rec.ib"; public static final String mahoutUserBasedRecs = "mahout.rec.ub"; public static final String mahoutSimilarities = "mahout.sim"; public static final String mahoutSVDRecs = "mahout.rec.svd"; public static final String mahoutSVDFactorizer = "mahout.svd.factorizer"; public static final String lenskitItemBasedRecs = "lenskit.rec.ib"; public static final String lenskitUserBasedRecs = "lenskit.rec.ub"; public static final String lenskitSimilarities = "lenskit.sim"; public static final String lenskitSVDRecs = "lenskit.rec.svd"; public static final String n = "neighborhood"; //also factors public static final String svdIter = "svd.iterations"; public static final String output = "output"; public static String[] neighborhoods; public static String[] svdIterations; public static String[] ibRecs; public static String[] ubRecs; public static String[] svdRecs; public static String[] similarities; public static Properties properties; public static ArrayList<String> paths; public static void main(String[] args) { paths = new ArrayList<String>(); String propertyFile = System.getProperty("file"); properties = new Properties(); try { properties.load(new FileInputStream(propertyFile)); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } for (Object pr : properties.stringPropertyNames()) System.out.println((String)pr + " : " + properties.getProperty((String)pr)); listAllFiles(properties.getProperty(input)); neighborhoods = properties.getProperty(n).split(","); svdIterations = properties.getProperty(svdIter).split(","); runLenskitRecommeders(); runMahoutRecommeders(); } public static void runLenskitRecommeders(){ try{ ibRecs = properties.getProperty(lenskitItemBasedRecs).split(","); ubRecs = properties.getProperty(lenskitUserBasedRecs).split(","); svdRecs = properties.getProperty(lenskitSVDRecs).split(","); similarities = properties.getProperty(lenskitSimilarities).split(","); } catch (NullPointerException e){ System.out.println("Properties not set"); return; } for(String path : paths){ Properties prop = new Properties(); prop.setProperty(RecommendationRunner.trainingSet, path + ".train"); prop.setProperty(RecommendationRunner.testSet, path + ".test"); prop.setProperty(RecommendationRunner.output, properties.getProperty(output)); prop.setProperty(RecommendationRunner.framework, "lenskit"); for (String ubRec : ubRecs){ prop.setProperty(RecommendationRunner.recommender, ubRec); for (String sim : similarities){ prop.setProperty(RecommendationRunner.similarity, sim); for (String n : neighborhoods){ prop.setProperty(RecommendationRunner.neighborhood, n); RecommendationRunner.recommend(prop); } prop.remove(RecommendationRunner.similarity); // prop.remove(RecommendationRunner.neighborhood); } } for (String ibRec : ibRecs){ prop.setProperty(RecommendationRunner.recommender, ibRec); for (String sim : similarities){ prop.setProperty(RecommendationRunner.similarity, sim); RecommendationRunner.recommend(prop); prop.remove(RecommendationRunner.similarity); } } for (String svdRec : svdRecs){ prop.setProperty(RecommendationRunner.recommender, svdRec); for (String f : neighborhoods){ prop.setProperty(RecommendationRunner.factors, f); RecommendationRunner.recommend(prop); } prop.remove(RecommendationRunner.factorizer); } } } public static void runMahoutRecommeders(){ try{ ibRecs = properties.getProperty(mahoutItemBasedRecs).split(","); ubRecs = properties.getProperty(mahoutUserBasedRecs).split(","); svdRecs = properties.getProperty(mahoutSVDRecs).split(","); similarities = properties.getProperty(mahoutSimilarities).split(","); } catch (NullPointerException e){ System.out.println("Properties not set"); return; } String[] factorizers = properties.getProperty(mahoutSVDFactorizer).split(","); for(String path : paths){ Properties prop = new Properties(); prop.setProperty(RecommendationRunner.trainingSet, path + ".train"); prop.setProperty(RecommendationRunner.testSet, path + ".test"); prop.setProperty(RecommendationRunner.output, properties.getProperty(output)); prop.setProperty(RecommendationRunner.framework, "mahout"); for (String ubRec : ubRecs){ prop.setProperty(RecommendationRunner.recommender, ubRec); for (String sim : similarities){ prop.setProperty(RecommendationRunner.similarity, sim); for (String n : neighborhoods){ prop.setProperty(RecommendationRunner.neighborhood, n); RecommendationRunner.recommend(prop); } prop.remove(RecommendationRunner.similarity); // prop.remove(RecommendationRunner.neighborhood); } } for (String ibRec : ibRecs){ prop.setProperty(RecommendationRunner.recommender, ibRec); for (String sim : similarities){ prop.setProperty(RecommendationRunner.similarity, sim); RecommendationRunner.recommend(prop); prop.remove(RecommendationRunner.similarity); } } for (String svdRec : svdRecs){ prop.setProperty(RecommendationRunner.recommender, svdRec); for (String fact : factorizers){ prop.setProperty(RecommendationRunner.factorizer, fact); for (String f : neighborhoods){ prop.setProperty(RecommendationRunner.factors, f); RecommendationRunner.recommend(prop); } prop.remove(RecommendationRunner.factorizer); } } } } public static void listAllFiles(String path){ File folder = new File(path); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles){ if (file.isDirectory()) listAllFiles(file.getAbsolutePath()); else if (file.getName().contains("train")) paths.add(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("."))); } } }
package com.github.lpandzic.junit.bdd; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import java.util.Optional; public final class Bdd implements TestRule { /** * Used for specifying behavior that should throw an exception. * * @param throwableSupplier supplier or throwable * @param <T> the type of * * @return new {@link Then.Throws} */ public static <T extends Exception> Then.Throws<T> when(ThrowableSupplier<T> throwableSupplier) { Bdd bdd = Bdd.bdd.get(); if (bdd == null) { throw new IllegalStateException("Bdd rule not initialized"); } bdd.requireThatNoUnexpectedExceptionWasThrown(); return new When(bdd).when(throwableSupplier); } /** * Used for specifying behavior that should return a value. * * @param value returned by the specified behavior * @param <T> type of {@code value} * * @return new {@link Then.Returns} */ public static <T> Then.Returns<T> when(T value) { Bdd bdd = Bdd.bdd.get(); if (bdd == null) { throw new IllegalStateException("Bdd rule not initialized"); } bdd.requireThatNoUnexpectedExceptionWasThrown(); return new When(bdd).when(value); } /** * Static factory method for {@link Bdd}. * * @return new bdd */ public static Bdd initialized() { Bdd bdd = new Bdd(); Bdd.bdd.set(bdd); return bdd; } private static final ThreadLocal<Bdd> bdd = new ThreadLocal<>(); /** * Exception thrown in a {@link When} or {@link Optional#empty()}. */ private Optional<Throwable> thrownException; @Override public Statement apply(Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { base.evaluate(); requireThatNoUnexpectedExceptionWasThrown(); } }; } /** * Inserts the {@code throwable} into {@link #thrownException}. * * @param throwable to add */ void putThrownException(Throwable throwable) { requireThatNoUnexpectedExceptionWasThrown(); thrownException = Optional.of(throwable); } /** * Retrieves and removes {@link #thrownException}. * * Used by {@link Then} for consuming {@link #thrownException} * * @return {@link #thrownException} */ Optional<Throwable> takeThrownException() { Optional<Throwable> thrownException = this.thrownException; this.thrownException = Optional.empty(); return thrownException; } void throwUnexpectedException(Throwable throwable) { throw new IllegalStateException("Unexpected exception was thrown", throwable); } private void requireThatNoUnexpectedExceptionWasThrown() { if (thrownException.isPresent()) { throwUnexpectedException(thrownException.get()); } } private Bdd() { thrownException = Optional.empty(); } }
package com.github.onsdigital.api; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.DirectoryStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.GET; import javax.ws.rs.core.Context; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.github.davidcarboni.restolino.framework.Endpoint; import com.github.davidcarboni.restolino.json.Serialiser; import com.github.onsdigital.configuration.Configuration; import com.github.onsdigital.json.ContentType; import com.github.onsdigital.json.Data; import com.github.onsdigital.json.TaxonomyFolder; /** * Sitemap endpoint that reflects the taxonomy structure: * * @author David Carboni * */ @Endpoint public class Sitemap { static String encoding = "UTF8"; static Document document; @GET public void get(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException { if (document == null) { // Get the request URI: URL requestUrl = new URL(request.getRequestURL().toString()); // Create a sitemap structure: Document document = createDocument(); Element rootElement = createRootElement(document); // Iterate the taxonomy structure: Path taxonomyPath = getHomePath(); // System.out.println("Searching " + taxonomyPath); int total = 0; total += addPath(taxonomyPath, 1, document, rootElement, requestUrl); total += iterate(taxonomyPath, 0.8, document, rootElement, requestUrl); // Output the result: System.out.println("Found " + total + " URLs for the sitemap."); Sitemap.document = document; } writeResponse(document, response); } private Path getHomePath() throws IOException { return FileSystems.getDefault().getPath(Configuration.getTaxonomyPath()); } private Document createDocument() throws IOException { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); document.setXmlStandalone(true); return document; } catch (ParserConfigurationException e) { throw new IOException("Error setting up XML DocumentBuilder", e); } } /** * Creates the correct root element in the Document. * * @param document * @return */ private Element createRootElement(Document document) { Element rootElement = document.createElementNS("http: document.appendChild(rootElement); return rootElement; } private int iterate(Path taxonomyPath, double priority, Document document, Element rootElement, URL requestUrl) throws IOException { int result = 0; List<Path> subdirectories = new ArrayList<Path>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(taxonomyPath)) { for (Path path : stream) { // Iterate over the paths: if (Files.isDirectory(path)) { result += addPath(path, priority, document, rootElement, requestUrl); subdirectories.add(path); } } } catch (DOMException | MalformedURLException e) { throw new IOException("Error iterating taxonomy", e); } // Step into subfolders: for (Path subdirectory : subdirectories) { result += iterate(subdirectory, priority * .8, document, rootElement, requestUrl); } return result; } private int addPath(Path path, double priority, Document document, Element rootElement, URL requestUrl) throws IOException { int result = 0; Data data = getDataJson(path); if (data != null && data.type == ContentType.home) { try { URI uri = toUri(data, requestUrl); addUrl(uri, document, rootElement, priority); result++; } catch (URISyntaxException | DOMException | MalformedURLException e) { throw new IOException("Error iterating taxonomy", e); } } return result; } private Data getDataJson(Path path) throws IOException { Data result = null; Path dataJson = path.resolve("data.json"); if (Files.exists(dataJson)) { try (InputStream input = Files.newInputStream(dataJson)) { result = Serialiser.deserialise(input, Data.class); } } return result; } private URI toUri(Data data, URL requestUrl) throws URISyntaxException { StringBuilder fragment = new StringBuilder("!"); if (data != null && data.breadcrumb != null) { for (TaxonomyFolder segment : data.breadcrumb) { fragment.append("/" + segment.fileName); } } fragment.append("/"); if (!StringUtils.equals("/", data.fileName)) { fragment.append(data.fileName); } new URI(requestUrl.getProtocol(), requestUrl.getHost(), "/", fragment.toString()); int port = -1; if (requestUrl.getPort() == 8080) { port = 8080; } String userInfo = null; String query = null; URI uri = new URI(requestUrl.getProtocol(), userInfo, requestUrl.getHost(), port, "/", query, fragment.toString()); return uri; } private void addUrl(URI uri, Document document, Element rootElement, double priorityValue) throws DOMException, MalformedURLException { // Container Element url = document.createElement("url"); rootElement.appendChild(url); // Location Element loc = document.createElement("loc"); url.appendChild(loc); loc.setTextContent(uri.toURL().toExternalForm()); // Priority Element priority = document.createElement("priority"); url.appendChild(priority); priority.setTextContent(String.format("%.2f", priorityValue)); System.out.println(uri.toURL().toExternalForm()); } private void writeResponse(Document document, HttpServletResponse response) throws IOException { // Setting the character encoding here ensures the PrintWriter // uses the correct encoding: response.setCharacterEncoding(encoding); PrintWriter writer = response.getWriter(); try { DOMSource domSource = new DOMSource(document); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); // Just to be sure, set the value in <?xml ... encoding="..."?> // to match the response character encoding: transformer.setOutputProperty(OutputKeys.ENCODING, encoding); transformer.transform(domSource, result); writer.flush(); } catch (TransformerException e) { throw new IOException("Error transforming XML", e); } } }
package edu.wustl.query.util.global; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.json.JSONException; import org.json.JSONObject; import edu.common.dynamicextensions.domaininterface.AbstractMetadataInterface; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.domaininterface.EntityInterface; import edu.common.dynamicextensions.domaininterface.TaggedValueInterface; import edu.common.dynamicextensions.entitymanager.EntityManagerConstantsInterface; import edu.wustl.common.beans.QueryResultObjectData; import edu.wustl.common.beans.QueryResultObjectDataBean; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.QueryBizLogic; import edu.wustl.common.dao.AbstractDAO; import edu.wustl.common.dao.DAOFactory; import edu.wustl.common.dao.QuerySessionData; import edu.wustl.common.dao.queryExecutor.PagenatedResultData; import edu.wustl.common.querysuite.queryobject.IAbstractQuery; import edu.wustl.common.querysuite.queryobject.IExpression; import edu.wustl.common.querysuite.queryobject.IOutputAttribute; import edu.wustl.common.querysuite.queryobject.IParameterizedQuery; import edu.wustl.common.querysuite.queryobject.IQuery; import edu.wustl.common.querysuite.queryobject.LogicalOperator; import edu.wustl.common.querysuite.queryobject.RelationalOperator; import edu.wustl.common.querysuite.queryobject.impl.AbstractQuery; import edu.wustl.common.querysuite.queryobject.impl.ParameterizedQuery; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.logger.Logger; import edu.wustl.query.bizlogic.QueryOutputSpreadsheetBizLogic; import edu.wustl.query.bizlogic.WorkflowBizLogic; import edu.wustl.query.querymanager.Count; import edu.wustl.query.util.querysuite.AbstractQueryUIManager; import edu.wustl.query.util.querysuite.IQueryUpdationUtil; import edu.wustl.query.util.querysuite.QueryModuleException; public class Utility extends edu.wustl.common.util.Utility { private static String pattern = "MM-dd-yyyy"; public static Object toNewGridFormat(Object obj) { obj = toGridFormat(obj); if (obj instanceof String) { String objString = (String) obj; StringBuffer tokenedString = new StringBuffer(); StringTokenizer tokenString = new StringTokenizer(objString, ","); while (tokenString.hasMoreTokens()) { tokenedString.append(tokenString.nextToken() + " "); } String gridFormattedStr = new String(tokenedString); obj = gridFormattedStr; } return obj; } /** * Adds the attribute values in the list in sorted order and returns the * list containing the attribute values in proper order * * @param dataType - * data type of the attribute value * @param value1 - * first attribute value * @param value2 - * second attribute value * @return List containing value1 and valu2 in sorted order */ public static ArrayList<String> getAttributeValuesInProperOrder(String dataType, String value1, String value2) { String v1 = value1; String v2 = value2; ArrayList<String> attributeValues = new ArrayList<String>(); if (dataType.equalsIgnoreCase(EntityManagerConstantsInterface.DATE_ATTRIBUTE_TYPE)) { SimpleDateFormat df = new SimpleDateFormat(pattern); try { Date date1 = df.parse(value1); Date date2 = df.parse(value2); if (date1.after(date2)) { v1 = value2; v2 = value1; } } catch (ParseException e) { Logger.out .error("Can not parse the given date in getAttributeValuesInProperOrder() method :" + e.getMessage()); e.printStackTrace(); } } else { if (dataType.equalsIgnoreCase(EntityManagerConstantsInterface.INTEGER_ATTRIBUTE_TYPE) || dataType .equalsIgnoreCase(EntityManagerConstantsInterface.LONG_ATTRIBUTE_TYPE)) { if (Long.parseLong(value1) > Long.parseLong(value2)) { v1 = value2; v2 = value1; } } else { if (dataType .equalsIgnoreCase(EntityManagerConstantsInterface.DOUBLE_ATTRIBUTE_TYPE)) { if (Double.parseDouble(value1) > Double.parseDouble(value2)) { v1 = value2; v2 = value1; } } } } attributeValues.add(v1); attributeValues.add(v2); return attributeValues; } public static String getmyData(List dataList) { String myData = "["; int i = 0; if (dataList != null && dataList.size() != 0) { for (i = 0; i < (dataList.size() - 1); i++) { List row = (List) dataList.get(i); int j; myData = myData + "\""; for (j = 0; j < (row.size() - 1); j++) { myData = myData + Utility.toNewGridFormat(row.get(j)).toString(); myData = myData + ","; } myData = myData + Utility.toNewGridFormat(row.get(j)).toString(); myData = myData + "\""; myData = myData + ","; } List row = (List) dataList.get(i); int j; myData = myData + "\""; for (j = 0; j < (row.size() - 1); j++) { myData = myData + Utility.toNewGridFormat(row.get(j)).toString(); myData = myData + ","; } myData = myData + Utility.toNewGridFormat(row.get(j)).toString(); myData = myData + "\""; } myData = myData + "]"; return myData; } public static String getcolumns(List columnList) { String columns = "\""; int col; if (columnList != null) { for (col = 0; col < (columnList.size() - 1); col++) { columns = columns + columnList.get(col); columns = columns + ","; } columns = columns + columnList.get(col); } columns = columns + "\""; return columns; } public static String getcolWidth(List columnList, boolean isWidthInPercent) { String colWidth = "\""; int col; if (columnList != null) { String fixedColWidth = null; if (isWidthInPercent) { fixedColWidth = String.valueOf(100 / columnList.size()); } else { fixedColWidth = "100"; } for (col = 0; col < (columnList.size() - 1); col++) { colWidth = colWidth + fixedColWidth; colWidth = colWidth + ","; } colWidth = colWidth + fixedColWidth; } colWidth = colWidth + "\""; return colWidth; } public static String getcolTypes(List dataList) { StringBuffer colTypes = new StringBuffer(); colTypes.append("\""); colTypes.append(Variables.prepareColTypes(dataList)); colTypes.append("\""); return colTypes.toString(); } public static void setGridData(List dataList, List columnList, HttpServletRequest request) { request.setAttribute("myData", getmyData(dataList)); request.setAttribute("columns", getcolumns(columnList)); boolean isWidthInPercent = false; if (columnList.size() < 10) { isWidthInPercent = true; } request.setAttribute("colWidth", getcolWidth(columnList, isWidthInPercent)); request.setAttribute("isWidthInPercent", isWidthInPercent); request.setAttribute("colTypes", getcolTypes(dataList)); int heightOfGrid = 100; if (dataList != null) { int noOfRows = dataList.size(); heightOfGrid = (noOfRows + 2) * 20; if (heightOfGrid > 240) { heightOfGrid = 230; } } request.setAttribute("heightOfGrid", heightOfGrid); int col = 0; int i = 0; String hiddenColumnNumbers = ""; if (columnList != null) { for (col = 0; col < columnList.size(); col++) { if (columnList.get(col).toString().trim().equals("ID") || columnList.get(col).toString().trim().equals("Status") || columnList.get(col).toString().trim().equals("Site Name") || columnList.get(col).toString().trim().equals("Report Collection Date")) { hiddenColumnNumbers = hiddenColumnNumbers + "hiddenColumnNumbers[" + i + "] = " + col + ";"; i++; } } } request.setAttribute("hiddenColumnNumbers", hiddenColumnNumbers); } public static Object toNewGridFormatWithHref(List<String> row, Map<Integer, QueryResultObjectData> hyperlinkColumnMap, int index) { Object obj = row.get(index); if (obj instanceof String) { obj = toNewGridFormat(obj); QueryResultObjectData queryResultObjectData = hyperlinkColumnMap.get(index); if (queryResultObjectData != null)// This column is to be shown as // hyperlink. { if (obj == null || obj.equals("")) { obj = "NA"; } /** * Name : Prafull Bug ID: 4223 Patch ID: 4223_1 Description: * Edit User: password fields empty & error on submitting new * password Added PageOf Attribute as request parameter in the * link. */ String aliasName = queryResultObjectData.getAliasName(); String link = "SimpleSearchEdit.do?" + Constants.TABLE_ALIAS_NAME + "=" + aliasName + "&" + Constants.SYSTEM_IDENTIFIER + "=" + row.get(queryResultObjectData.getIdentifierColumnId()) + "&" + Constants.PAGE_OF + "=" + Variables.aliasAndPageOfMap.get(aliasName); /** * bug ID: 4225 Patch id: 4225_1 Description : Passing a * different name to the popup window */ String onclickStr = " onclick=javascript:NewWindow('" + link + "','simpleSearch','800','600','yes') "; String hrefTag = "<a class='normalLink' href='#'" + onclickStr + ">" + obj + "</a>"; // String hrefTag = "<a href='"+ link+ "'>"+obj+"</a>"; obj = hrefTag; } } return obj; } /** * This method creates a comma separated string of numbers representing * column width. * */ public static String getColumnWidth(List columnNames) { String colWidth = getColumnWidth((String) columnNames.get(0)); int size = columnNames.size()-1; for (int col = 0; col < size; col++) { String columnName = (String) columnNames.get(col); colWidth = colWidth + "," + getColumnWidth(columnName); } return colWidth; } private static String getColumnWidth(String columnName) { /* * Patch ID: Bug#3090_31 Description: The first column which is just a * checkbox, used to select the rows, was always given a width of 100. * Now width of 20 is set for the first column. Also, width of 100 was * being applied to each column of the grid, which increasing the total * width of the grid. Now the width of each column is set to 80. */ String columnWidth = null; if ("ID".equals(columnName.trim())) { columnWidth = "0"; } else if ("".equals(columnName.trim())) { columnWidth = "20"; } else { columnWidth = "150"; } return columnWidth; } public static String getColumnWidthP(List columnNames) { StringBuffer colWidth = new StringBuffer(""); int size = columnNames.size(); double temp = 97.5f; for (int col = 0; col < size; col++) { colWidth = colWidth.append(String.valueOf(temp / (size))); colWidth = colWidth.append(","); } if(colWidth.lastIndexOf(",")== colWidth.length()-1) { colWidth.deleteCharAt(colWidth.length()-1); } return colWidth.toString(); } /** * limits the title of the saved query to 125 characters to avoid horizontal * scrollbar * * @param title - * title of the saved query (may be greater than 125 characters) * @return - query title upto 125 characters */ public static String getQueryTitle(String title) { String multilineTitle = ""; if (title.length() <= Constants.CHARACTERS_IN_ONE_LINE) { multilineTitle = title; } else { multilineTitle = title.substring(0, Constants.CHARACTERS_IN_ONE_LINE) + "....."; } return multilineTitle; } /** * returns the entire title to display it in tooltip . * * @param title - * title of the saved query * @return tooltip string */ public static String getTooltip(String title) { String tooltip = title.replaceAll("'", Constants.SINGLE_QUOTE_ESCAPE_SEQUENCE); // escape sequence // for ' return tooltip; } public static List getPaginationDataList(HttpServletRequest request, SessionDataBean sessionData, int recordsPerPage, int pageNum, QuerySessionData querySessionData) throws DAOException { List paginationDataList; querySessionData.setRecordsPerPage(recordsPerPage); int startIndex = recordsPerPage * (pageNum - 1); QueryBizLogic qBizLogic = new QueryBizLogic(); PagenatedResultData pagenatedResultData = qBizLogic.execute(sessionData, querySessionData, startIndex); paginationDataList = pagenatedResultData.getResult(); String isSimpleSearch = (String) request.getSession().getAttribute( Constants.IS_SIMPLE_SEARCH); if (isSimpleSearch == null || (!isSimpleSearch.equalsIgnoreCase(Constants.TRUE))) { Map<Long, QueryResultObjectDataBean> queryResultObjectDataBeanMap = querySessionData .getQueryResultObjectDataMap(); if (queryResultObjectDataBeanMap != null) { for (Long id : queryResultObjectDataBeanMap.keySet()) { QueryResultObjectDataBean bean = queryResultObjectDataBeanMap.get(id); if (bean.isClobeType()) { List<String> columnsList = (List<String>) request.getSession() .getAttribute(Constants.SPREADSHEET_COLUMN_LIST); QueryOutputSpreadsheetBizLogic queryBizLogic = new QueryOutputSpreadsheetBizLogic(); Map<Integer, Integer> fileTypeIndexMainEntityIndexMap = queryBizLogic .updateSpreadSheetColumnList(columnsList, queryResultObjectDataBeanMap); // QueryOutputSpreadsheetBizLogic.updateDataList(paginationDataList, fileTypeIndexMainEntityIndexMap); Map exportMetataDataMap = QueryOutputSpreadsheetBizLogic.updateDataList( paginationDataList, fileTypeIndexMainEntityIndexMap); request.getSession().setAttribute(Constants.ENTITY_IDS_MAP, exportMetataDataMap.get(Constants.ENTITY_IDS_MAP)); request.getSession().setAttribute(Constants.EXPORT_DATA_LIST, exportMetataDataMap.get(Constants.EXPORT_DATA_LIST)); break; } } } } return paginationDataList; } /** * @param entity entity for which Primary Key list is required * @return List<String> primary key list */ public static List<String> getPrimaryKey(EntityInterface entity) { Collection<TaggedValueInterface> taggedValueCollection = entity.getTaggedValueCollection(); List<String> primaryKeyList = new ArrayList<String>(); for (TaggedValueInterface tag : taggedValueCollection) { if (Constants.PRIMARY_KEY_TAG_NAME.equals(tag.getKey())) { StringTokenizer stringTokenizer = new StringTokenizer(tag.getValue(), ","); for (int i = 0; stringTokenizer.hasMoreTokens(); i++) { primaryKeyList.add(stringTokenizer.nextToken()); } } } return primaryKeyList; } /** * Method to generate SQL for Node * @param parentNodeId parent node id which contains data * @param tableName temporary table name * @param parentIdColumnName parent node ID column names (, separated) * @param selectSql SQL * @param idColumnOfCurrentNode id column name (, separated) of current node * @return SQL for current node */ public static String getSQLForNode(String parentNodeId, String tableName, String parentIdColumnName, String selectSql, String idColumnOfCurrentNode) { selectSql = selectSql + Constants.FROM + tableName; if (parentNodeId != null) { selectSql = selectSql + Constants.WHERE + " ("; StringTokenizer stringTokenizerParentID = new StringTokenizer(parentIdColumnName, ","); StringTokenizer stringTokenizerParentNodeID = new StringTokenizer(parentNodeId, Constants.PRIMARY_KEY_ATTRIBUTE_SEPARATOR); while (stringTokenizerParentID.hasMoreElements()) { selectSql = selectSql + stringTokenizerParentID.nextElement() + " = '" + stringTokenizerParentNodeID.nextElement() + "' " + LogicalOperator.And + " "; } StringTokenizer stringTokenizerIDofCurrentNode = new StringTokenizer( idColumnOfCurrentNode, ","); while (stringTokenizerIDofCurrentNode.hasMoreElements()) { selectSql = selectSql + " " + stringTokenizerIDofCurrentNode.nextElement() + " " + RelationalOperator.getSQL(RelationalOperator.IsNotNull) + " " + LogicalOperator.And; } if (selectSql.substring(selectSql.length() - 3).equals(LogicalOperator.And.toString())) { selectSql = selectSql.substring(0, selectSql.length() - 3); } selectSql = selectSql + ")"; } return selectSql; } public static ActionErrors setActionError(String errorMessage, String key) { ActionErrors errors = new ActionErrors(); ActionError error = new ActionError("errors.item", errorMessage); errors.add(ActionErrors.GLOBAL_ERROR, error); return errors; } /** * This method returns the session data bean * @param request * @return */ public static SessionDataBean getSessionData(HttpServletRequest request) { Object obj = request.getSession().getAttribute(Constants.SESSION_DATA); SessionDataBean sessionData = null; if (obj != null) { sessionData = (SessionDataBean) obj; return sessionData; } return sessionData; } /** * Method checks if attribute is not viewable in results view of Query. * @param attribute * @return isNotViewable */ public static boolean isNotViewable(AttributeInterface attribute) { boolean isNotViewable = false; Collection<TaggedValueInterface> taggedValueCollection = attribute .getTaggedValueCollection(); for (TaggedValueInterface tagValue : taggedValueCollection) { if (tagValue.getKey().equals(Constants.TAGGED_VALUE_NOT_VIEWABLE)) { isNotViewable = true; break; } } return isNotViewable; } public static boolean isMainEntity(EntityInterface entity) { boolean isMainEntity = false; Collection<TaggedValueInterface> taggedValueCollection = entity.getTaggedValueCollection(); for (TaggedValueInterface tagValue : taggedValueCollection) { if (tagValue.getKey().equals(Constants.TAGGED_VALUE_MAIN_ENTIY)) { isMainEntity = true; break; } } return isMainEntity; } public static String removeLastAnd(String select) { String selectString = select; if (select.endsWith(Constants.QUERY_AND)) { selectString = selectString.substring(0, selectString.length() - 5); } return selectString; } public static void removeLastComma(StringBuilder string) { if (Constants.QUERY_COMMA.equals(string.substring(string.length() - 2))) { string.delete(string.length() - 2, string.length()); } } public static boolean istagPresent(AbstractMetadataInterface entity, String tag) { boolean isTagPresent = false; Collection<TaggedValueInterface> taggedValueCollection = entity.getTaggedValueCollection(); for (TaggedValueInterface tagValue : taggedValueCollection) { if (tagValue.getKey().equals(tag)) { isTagPresent = true; break; } } return isTagPresent; } /** * Method to update Query Objects with containments. * @param session object * @param query to be updated. */ public static void updateIQueryForContainments(HttpSession session, IQuery query, boolean isDefaultConditionPresent) { if (query != null) { Map<Integer, HashMap<EntityInterface, List<EntityInterface>>> eachExpressionParentChildMap = IQueryUpdationUtil .getAllConatainmentObjects(query, session, isDefaultConditionPresent); //Update the IQuery with containment objects......add only those containment objects which are not present in IQuery IQueryUpdationUtil.addConatinmentObjectsToIquery(query, session); //IQueryUpdationUtil.addDefaultConditionToIquery(query,session); //Add the link/association among parent and containment entities IQueryUpdationUtil.addLinks(eachExpressionParentChildMap, session, query); } } /** * get the alias for given attribute to identify it uniquely * @param attribute * @return */ public static String getAliasFor(AttributeInterface attribute, IExpression expression) { return getAliasFor(attribute.getName(), expression); } public static String getAliasFor(String attributeName, IExpression expression) { return attributeName + "_" + expression.getExpressionId(); } /** * To get IQuery object from Query Id * @param queryId * @return * @throws DAOException */ public static IAbstractQuery getQuery(Long queryId) throws DAOException { IAbstractQuery query = null; if (queryId != null) { AbstractDAO dao = DAOFactory.getInstance().getDAO(Constants.HIBERNATE_DAO); dao.openSession(null); query = (IAbstractQuery) dao.retrieve(AbstractQuery.class.getName(), queryId); dao.closeSession(); } return query; } /** * * @param entity * @param tag * @return */ public static String getTagValue(AbstractMetadataInterface entity, String tag) { String value = ""; Collection<TaggedValueInterface> taggedValueCollection = entity.getTaggedValueCollection(); for (TaggedValueInterface tagValue : taggedValueCollection) { if (tagValue.getKey().equals(tag)) { value = tagValue.getValue(); break; } } return value; } public static void setQueryOutputAttributeList(IParameterizedQuery query, List<IOutputAttribute> newoutputAttributeList) { query.getOutputAttributeList().clear(); query.getOutputAttributeList().addAll(newoutputAttributeList); } /** This method is used to get a display name * @param outputAttribute * @return */ public static String getDisplayNameForColumn(IOutputAttribute outputAttribute) { String columnDisplayName = ""; AttributeInterface attribute = outputAttribute.getAttribute(); String className = Utility.parseClassName(outputAttribute.getExpression().getQueryEntity().getDynamicExtensionsEntity().getName()); className = Utility.getDisplayLabel(className); String attributeLabel = Utility.getDisplayLabel(attribute.getName()); columnDisplayName = className +" : " + attributeLabel ; return columnDisplayName; } /** * Private method used to generate the List of JSON objects. * * @param executionIdMap * Execution Id Map * @param workflowBizLogic * Instance of BizLogic to be used. * @param qUIManager * Instance of the Query UI Manager. * @param projectId * Project Id * @return The List of JSON Objects * @throws QueryModuleException * if error while executing the query. */ public static List<JSONObject> generateExecutionQueryResults(Map<Long, Integer> executionIdMap, WorkflowBizLogic workflowBizLogic, AbstractQueryUIManager qUIManager, boolean hasSecurePrivilege) throws QueryModuleException { Count resultCount = null; JSONObject jsonObject = null; List<JSONObject> executionQueryResults = new ArrayList<JSONObject>(); Set<Long> titleset = executionIdMap.keySet(); Iterator<Long> iterator = titleset.iterator(); while (iterator.hasNext()) { Long query = iterator.next(); resultCount = workflowBizLogic .getCount(executionIdMap.get(query)); boolean hasFewRecords = qUIManager.checkTooFewRecords( resultCount,hasSecurePrivilege); if (hasFewRecords) { resultCount.setCount(0); } jsonObject = createResultJSON(query, resultCount.getCount(), resultCount .getStatus(), resultCount .getQueryExectionId()); executionQueryResults.add(jsonObject); } return executionQueryResults; } /** * @param queryId =Query identifier for which execute request sent * @param errormessage * @param workflowId * @param queryIndex=row number where results to be displayed * @param resultCount=value of result count for query * @returns jsonObject * * creates the jsonObject for input parameters */ public static JSONObject createResultJSON(Long queryId, int resultCount, String status, int executionLogId) { JSONObject resultObject = null; resultObject = new JSONObject(); try { resultObject.append("queryId", queryId); resultObject.append("queryResult", resultCount); resultObject.append("status", status); resultObject.append("executionLogId", executionLogId); } catch (JSONException e) { Logger.out.info("error in initializing json object " + e); } return resultObject; } }
package com.imcode.imcms.config; import com.imcode.imcms.mapping.CategoryMapper; import com.imcode.imcms.mapping.DocumentMapper; import imcode.server.Imcms; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan({ "com.imcode.imcms.servlet.apis", "com.imcode.imcms.controller" }) public class WebConfig { public final Environment environment; @Autowired public WebConfig(Environment environment) { this.environment = environment; } @Bean public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(Long.parseLong(environment.getProperty("ImageArchiveMaxImageUploadSize"))); return multipartResolver; } @Bean public ViewResolver templateViewResolver() { return instantiateJspViewResolver("/WEB-INF/templates/text/"); } @Bean public ViewResolver internalViewResolver() { return instantiateJspViewResolver("/WEB-INF/jsp/imcms/views/"); } private ViewResolver instantiateJspViewResolver(String prefix) { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix(prefix); viewResolver.setSuffix(".jsp"); return viewResolver; } @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { return new MappingJackson2HttpMessageConverter(); } @Bean public DocumentMapper documentMapper() { return Imcms.getServices().getDocumentMapper(); } @Bean public CategoryMapper categoryMapper() { return Imcms.getServices().getCategoryMapper(); } }
package com.kurento.kmf.media; import java.io.IOException; import java.security.Policy.Parameters; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import com.kurento.kmf.media.internal.MediaServerServiceManager; import com.kurento.kms.api.MediaObjectNotFoundException; import com.kurento.kms.api.MediaServerException; import com.kurento.kms.api.MediaServerService; import com.kurento.kms.api.MediaServerService.AsyncClient.generateOffer_call; import com.kurento.kms.api.MediaServerService.AsyncClient.getLocalSessionDescription_call; import com.kurento.kms.api.MediaServerService.AsyncClient.getRemoteSessionDescription_call; import com.kurento.kms.api.MediaServerService.AsyncClient.processAnswer_call; import com.kurento.kms.api.MediaServerService.AsyncClient.processOffer_call; import com.kurento.kms.api.NegotiationException; // TODO: update doc public abstract class SdpEndPoint extends EndPoint { private static final long serialVersionUID = 1L; SdpEndPoint(com.kurento.kms.api.MediaObject sdpEndPoint) { super(sdpEndPoint); } /* SYNC */ public String generateOffer() throws IOException { MediaServerService.Client service = MediaServerServiceManager .getMediaServerService(); try { return service.generateOffer(mediaObject); } catch (MediaObjectNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (MediaServerException e) { throw new RuntimeException(e.getMessage(), e); } catch (TException e) { throw new IOException(e.getMessage(), e); } finally { MediaServerServiceManager.releaseMediaServerService(service); } } public String processOffer(String offer) throws IOException { MediaServerService.Client service = MediaServerServiceManager .getMediaServerService(); try { return service.processOffer(mediaObject, offer); } catch (MediaObjectNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (MediaServerException e) { throw new RuntimeException(e.getMessage(), e); } catch (TException e) { throw new IOException(e.getMessage(), e); } finally { MediaServerServiceManager.releaseMediaServerService(service); } } public String processAnswer(String answer) throws IOException { MediaServerService.Client service = MediaServerServiceManager .getMediaServerService(); try { return service.processAnswer(mediaObject, answer); } catch (MediaObjectNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (MediaServerException e) { throw new RuntimeException(e.getMessage(), e); } catch (TException e) { throw new IOException(e.getMessage(), e); } finally { MediaServerServiceManager.releaseMediaServerService(service); } } /** * This method gives access to the SessionSpec offered by this * NetworkConnection * * <p> * <b>Note:</b> This method returns the local MediaSpec, negotiated or not. * If no offer has been generated yet, it returns null. It an offer has been * generated it returns the offer and if an asnwer has been processed it * returns the negotiated local SessionSpec. * </p> * * @return The last agreed SessionSpec * @throws IOException */ public String getLocalSessionDescriptor() throws IOException { MediaServerService.Client service = MediaServerServiceManager .getMediaServerService(); try { return service.getLocalSessionDescription(mediaObject); } catch (MediaObjectNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (MediaServerException e) { throw new RuntimeException(e.getMessage(), e); } catch (TException e) { throw new IOException(e.getMessage(), e); } finally { MediaServerServiceManager.releaseMediaServerService(service); } } /** * This method gives access to the remote session description. * * <p> * <b>Note:</b> This method returns the media previously agreed after a * complete offer-answer exchange. If no media has been agreed yet, it * returns null. * </p> * * @return The last agreed User Agent session description */ public String getRemoteSessionDescriptor() throws IOException { MediaServerService.Client service = MediaServerServiceManager .getMediaServerService(); try { return service.getRemoteSessionDescription(mediaObject); } catch (MediaObjectNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (MediaServerException e) { throw new RuntimeException(e.getMessage(), e); } catch (TException e) { throw new IOException(e.getMessage(), e); } finally { MediaServerServiceManager.releaseMediaServerService(service); } } /* ASYNC */ /** * Request a SessionSpec offer. * * <p> * The resulting offer is available with * {@link SdpEndPoint#getSessionSpec()} * </p> * * <p> * This can be used to initiate a connection. * </p> * * @param cont * Continuation object to notify when operation completes * @throws MediaException */ public void generateOffer(final Continuation<String> cont) throws IOException { MediaServerService.AsyncClient service = MediaServerServiceManager .getMediaServerServiceAsync(); try { service.generateOffer( mediaObject, new AsyncMethodCallback<MediaServerService.AsyncClient.generateOffer_call>() { @Override public void onComplete(generateOffer_call response) { try { String sessionDescriptor = response.getResult(); cont.onSuccess(sessionDescriptor); } catch (MediaObjectNotFoundException e) { cont.onError(new RuntimeException(e .getMessage(), e)); } catch (MediaServerException e) { cont.onError(new RuntimeException(e .getMessage(), e)); } catch (TException e) { cont.onError(new IOException(e.getMessage(), e)); } } @Override public void onError(Exception exception) { cont.onError(exception); } }); } catch (TException e) { throw new IOException(e.getMessage(), e); } finally { MediaServerServiceManager.releaseMediaServerServiceAsync(service); } } /** * Request the NetworkConnection to process the given SessionSpec offer * (from the remote User Agent).<br> * The resulting answer is available with * {@link SdpEndPoint#getSessionSpec()} and the remote offer will be * returned by {@link SdpEndPoint#getRemoteSessionSpec()} * * @param offer * SessionSpec offer from the remote User Agent * @param cont * Continuation object to notify when operation completes and to * provide the answer SessionSpec. */ public void processOffer(String offer, final Continuation<String> cont) throws IOException { MediaServerService.AsyncClient service = MediaServerServiceManager .getMediaServerServiceAsync(); try { service.processOffer( mediaObject, offer, new AsyncMethodCallback<MediaServerService.AsyncClient.processOffer_call>() { @Override public void onComplete(processOffer_call response) { try { String sessionDescriptor = response.getResult(); cont.onSuccess(sessionDescriptor); } catch (MediaObjectNotFoundException e) { cont.onError(new RuntimeException(e .getMessage(), e)); } catch (NegotiationException e) { cont.onError(new MediaException(e.getMessage(), e)); } catch (MediaServerException e) { cont.onError(new RuntimeException(e .getMessage(), e)); } catch (TException e) { cont.onError(new IOException(e.getMessage(), e)); } } @Override public void onError(Exception exception) { cont.onError(exception); } }); } catch (TException e) { throw new IOException(e.getMessage(), e); } finally { MediaServerServiceManager.releaseMediaServerServiceAsync(service); } } /** * Request the NetworkConnection to process the given SessionSpec answer * (from the remote User Agent).<br> * The answer become available on method * {@link SdpEndPoint#getRemoteSessionSpec()} * * @param answer * SessionSpec answer from the remote User Agent * @param cont * Continuation object to notify when operation completes, * returned SessionSpec is the local SessionSpec. */ public void processAnswer(String answer, final Continuation<String> cont) throws IOException { MediaServerService.AsyncClient service = MediaServerServiceManager .getMediaServerServiceAsync(); try { service.processAnswer( mediaObject, answer, new AsyncMethodCallback<MediaServerService.AsyncClient.processAnswer_call>() { @Override public void onComplete(processAnswer_call response) { try { String sessionDescriptor = response.getResult(); cont.onSuccess(sessionDescriptor); } catch (MediaObjectNotFoundException e) { cont.onError(new RuntimeException(e .getMessage(), e)); } catch (NegotiationException e) { cont.onError(new MediaException(e.getMessage(), e)); } catch (MediaServerException e) { cont.onError(new RuntimeException(e .getMessage(), e)); } catch (TException e) { cont.onError(new IOException(e.getMessage(), e)); } } @Override public void onError(Exception exception) { cont.onError(exception); } }); } catch (TException e) { throw new IOException(e.getMessage(), e); } finally { MediaServerServiceManager.releaseMediaServerServiceAsync(service); } } /** * This method gives access to the SessionSpec offered by this * NetworkConnection * * <p> * <b>Note:</b> This method returns the local MediaSpec, negotiated or not. * If no offer has been generated yet, it returns null. It an offer has been * generated it returns the offer and if an asnwer has been processed it * returns the negotiated local SessionSpec. * </p> * * @return The last agreed SessionSpec * @throws IOException */ public void getLocalSessionDescriptor(final Continuation<String> cont) throws IOException { MediaServerService.AsyncClient service = MediaServerServiceManager .getMediaServerServiceAsync(); try { service.getLocalSessionDescription( mediaObject, new AsyncMethodCallback<MediaServerService.AsyncClient.getLocalSessionDescription_call>() { @Override public void onComplete( getLocalSessionDescription_call response) { try { String sessionDescriptor = response.getResult(); cont.onSuccess(sessionDescriptor); } catch (MediaObjectNotFoundException e) { cont.onError(new RuntimeException(e .getMessage(), e)); } catch (MediaServerException e) { cont.onError(new RuntimeException(e .getMessage(), e)); } catch (TException e) { cont.onError(new IOException(e.getMessage(), e)); } } @Override public void onError(Exception exception) { cont.onError(exception); } }); } catch (TException e) { throw new IOException(e.getMessage(), e); } finally { MediaServerServiceManager.releaseMediaServerServiceAsync(service); } } /** * This method gives access to the remote session description. * * <p> * <b>Note:</b> This method returns the media previously agreed after a * complete offer-answer exchange. If no media has been agreed yet, it * returns null. * </p> * * @return The last agreed User Agent session description */ public void getRemoteSessionDescriptor(final Continuation<String> cont) throws IOException { MediaServerService.AsyncClient service = MediaServerServiceManager .getMediaServerServiceAsync(); try { service.getRemoteSessionDescription( mediaObject, new AsyncMethodCallback<MediaServerService.AsyncClient.getRemoteSessionDescription_call>() { @Override public void onComplete( getRemoteSessionDescription_call response) { try { String sessionDescriptor = response.getResult(); cont.onSuccess(sessionDescriptor); } catch (MediaObjectNotFoundException e) { cont.onError(new RuntimeException(e .getMessage(), e)); } catch (MediaServerException e) { cont.onError(new RuntimeException(e .getMessage(), e)); } catch (TException e) { cont.onError(new IOException(e.getMessage(), e)); } } @Override public void onError(Exception exception) { cont.onError(exception); } }); } catch (TException e) { throw new IOException(e.getMessage(), e); } finally { MediaServerServiceManager.releaseMediaServerServiceAsync(service); } } }
package com.loopperfect.buckaroo; public final class Buckaroo { private Buckaroo() { } public static final SemanticVersion version = SemanticVersion.of(1, 2, 0); }
package com.matt.forgehax.mods; import static com.matt.forgehax.Helper.*; import com.google.common.collect.Lists; import com.matt.forgehax.asm.ForgeHaxHooks; import com.matt.forgehax.events.LocalPlayerUpdateEvent; import com.matt.forgehax.mods.services.HotbarSelectionService.ResetFunction; import com.matt.forgehax.util.SimpleTimer; import com.matt.forgehax.util.Utils; import com.matt.forgehax.util.command.Setting; import com.matt.forgehax.util.entity.EntityUtils; import com.matt.forgehax.util.entity.LocalPlayerInventory; import com.matt.forgehax.util.key.Bindings; import com.matt.forgehax.util.math.Angle; import com.matt.forgehax.util.mod.Category; import com.matt.forgehax.util.mod.ToggleMod; import com.matt.forgehax.util.mod.loader.RegisterMod; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Objects; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import net.minecraft.init.Blocks; import net.minecraft.item.ItemRedstone; import net.minecraft.network.play.client.CPacketAnimation; import net.minecraft.network.play.client.CPacketPlayerDigging; import net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent; @RegisterMod public class AntiAfkMod extends ToggleMod { private final Setting<Long> delay = getCommandStub() .builders() .<Long>newSettingBuilder() .name("delay") .description("Delay time (in MS) between tasks") .defaultTo(10_000L) .min(0L) .build(); private final Setting<Long> runtime = getCommandStub() .builders() .<Long>newSettingBuilder() .name("runtime") .description("Time to run each task") .defaultTo(5_000L) .min(0L) .build(); private final Setting<Boolean> silent = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("silent") .description("Make most afk tasks execute without disrupting the players view") .defaultTo(false) .changed(cb -> TaskEnum.setSilent(cb.getTo())) .build(); private final Setting<Boolean> swing = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("swing") .description("Swing the players arm") .defaultTo(true) .build(); private final Setting<Boolean> walk = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("walk") .description("Walk in different directions") .defaultTo(false) .build(); private final Setting<Boolean> spin = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("spin") .description("Spin the players view") .defaultTo(false) .build(); private final Setting<Boolean> mine = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("mine") .description( "Place and break a block that is in the players inventory. Only runs if the player has a block that can break in 1 hit and be placed under the player.") .defaultTo(false) .build(); private final SimpleTimer timer = new SimpleTimer(); private final AtomicBoolean ranStop = new AtomicBoolean(false); private TaskEnum task = TaskEnum.NONE; public AntiAfkMod() { super(Category.PLAYER, "AntiAFK", false, "Swing arm to prevent being afk kicked"); TaskEnum.SWING.setParentSetting(swing); TaskEnum.WALK.setParentSetting(walk); TaskEnum.SPIN.setParentSetting(spin); TaskEnum.MINE.setParentSetting(mine); } private TaskEnum getTask() { return task; } private void setTask(TaskEnum task) { this.task = task; } private boolean isTaskRunning() { return !getTask().equals(TaskEnum.NONE); } private List<TaskEnum> getNextTask() { return TaskEnum.ALL .stream() .filter(IAFKTask::isRunnable) .filter(TaskEnum::isEnabled) .collect(Collectors.toList()); } private void reset() { timer.reset(); ranStop.set(false); getTask().onStop(); setTask(TaskEnum.NONE); } @Override protected void onLoad() { TaskEnum.setSilent(silent.get()); } @Override public String getDebugDisplayText() { return super.getDebugDisplayText() + " " + String.format( "[%s | %s | next = %s]", getTask().name(), isTaskRunning() ? "Running" : "Waiting", isTaskRunning() ? (SimpleTimer.toFormattedTime(Math.max(runtime.get() - timer.getTimeElapsed(), 0))) : (SimpleTimer.toFormattedTime(Math.max(delay.get() - timer.getTimeElapsed(), 0)))); } @SubscribeEvent public void onKeyboardInput(InputEvent.KeyInputEvent event) { reset(); } @SubscribeEvent public void onMouseEvent(InputEvent.MouseInputEvent event) { reset(); } @SubscribeEvent public void onDisconnect(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) { reset(); } @SubscribeEvent public void onUpdate(LocalPlayerUpdateEvent event) { if (!timer.isStarted()) timer.start(); // start timer if it hasn't already if (!isTaskRunning()) { if (timer.hasTimeElapsed(delay.get())) { List<TaskEnum> next = getNextTask(); if (!next.isEmpty()) { // wait again to check if the task is valid setTask( next.get(ThreadLocalRandom.current().nextInt(next.size()))); // select a random task getTask().onStart(); } timer.start(); } } else { if (timer.hasTimeElapsed(runtime.get())) { boolean prev = ranStop.get(); if (ranStop.compareAndSet(false, true)) // only run once getTask().onStop(); if (getTask().isRunning()) { if (prev == ranStop.get()) getTask().onTick(); // only run if this task did not execute onStop() on the same tick } else { setTask(TaskEnum.NONE); ranStop.set(false); timer.start(); } } else { getTask().onTick(); // run task tick } } } enum TaskEnum implements IAFKTask { NONE { @Override public void onTick() {} @Override public void onStart() {} @Override public void onStop() {} @Override public boolean isRunnable() { return false; } }, SWING { @Override public void onTick() {} @Override public void onStart() {} @Override public void onStop() { swingHand(); } }, WALK { static final int DEGREES = 45; double angle = 0; @Override public void onTick() { Bindings.forward.setPressed(true); // TODO: reimplement view angle setting } @Override public void onStart() { ForgeHaxHooks.isSafeWalkActivated = true; Bindings.forward.bind(); Vec3d eye = EntityUtils.getEyePos(getLocalPlayer()); List<Double> yaws = Lists.newArrayList(); for (int i = 0; i < (360 / DEGREES); ++i) yaws.add((i * DEGREES) - 180.D); Collections.shuffle(yaws); double lastDistance = -1.D; for (double y : yaws) { double[] cc = Angle.degrees(0.f, (float) y).getForwardVector(); Vec3d target = eye.add(new Vec3d(cc[0], cc[1], cc[2]).normalize().scale(64)); RayTraceResult result = getWorld().rayTraceBlocks(eye, target, false, true, false); double distance = result == null ? 64.D : eye.distanceTo(result.hitVec); if ((distance >= 1.D || lastDistance == -1.D) && (distance > lastDistance || Math.random() < 0.20D)) { angle = y; lastDistance = distance; } } } @Override public void onStop() { Bindings.forward.setPressed(false); Bindings.forward.unbind(); getLocalPlayer().motionX = 0.D; getLocalPlayer().motionY = 0.D; getLocalPlayer().motionZ = 0.D; getModManager() .get(SafeWalkMod.class) .ifPresent(mod -> ForgeHaxHooks.isSafeWalkActivated = mod.isEnabled()); } }, SPIN { float ang = 0.f; double p, y; @Override public void onTick() { setViewAngles( MathHelper.clamp( getLocalPlayer().rotationPitch + MathHelper.cos(ang += 0.1f), -90.f, 90.f), getLocalPlayer().rotationYaw + 1.8f); } @Override public void onStart() { ang = 0.f; p = getLocalPlayer().rotationPitch; y = getLocalPlayer().rotationYaw; } @Override public void onStop() { setViewAngles(p, y); } }, MINE { static final int MULTIPLIER = 2; final SimpleTimer halting = new SimpleTimer(); int counter = 0; double p; RayTraceResult getTraceBelow() { // TODO: fix the trace so i dont have to do witchcraft in // getBlockBelow() Vec3d eyes = EntityUtils.getEyePos(getLocalPlayer()); return getWorld() .rayTraceBlocks( eyes, eyes.addVector(0, -MC.playerController.getBlockReachDistance(), 0), false, false, false); } BlockPos getBlockBelow() { RayTraceResult tr = getTraceBelow(); return tr == null ? BlockPos.ORIGIN : (getWorld() .getBlockState(tr.getBlockPos().add(0, 1, 0)) .getBlock() .equals(Blocks.REDSTONE_WIRE) ? tr.getBlockPos().add(0, 1, 0) : tr.getBlockPos()); } boolean isPlaced() { return getWorld().getBlockState(getBlockBelow()).getBlock().equals(Blocks.REDSTONE_WIRE); } @Override public void onTick() { if (counter++ % (TPS * MULTIPLIER) == 0) { if (isPlaced()) { getNetworkManager() .sendPacket( new CPacketPlayerDigging( CPacketPlayerDigging.Action.START_DESTROY_BLOCK, getBlockBelow(), EnumFacing.UP)); swingHand(); return; } LocalPlayerInventory.InvItem item = LocalPlayerInventory.getHotbarInventory() .stream() .filter(itm -> itm.getItemStack().getItem() instanceof ItemRedstone) .findAny() .orElse(LocalPlayerInventory.InvItem.EMPTY); if (item.isNull()) return; RayTraceResult result = getTraceBelow(); if (result == null) return; if (!Blocks.REDSTONE_WIRE.canPlaceBlockAt(getWorld(), result.getBlockPos())) return; // can't place block ResetFunction func = LocalPlayerInventory.setSelected(item); LocalPlayerInventory.syncSelected(); getNetworkManager() .sendPacket( new CPacketPlayerTryUseItemOnBlock( result.getBlockPos(), EnumFacing.UP, EnumHand.MAIN_HAND, (float) (result.hitVec.x - result.getBlockPos().getX()), (float) (result.hitVec.y - result.getBlockPos().getY()), (float) (result.hitVec.z - result.getBlockPos().getZ()))); swingHand(); func.revert(); } } @Override public void onStart() { halting.reset(); counter = TPS * MULTIPLIER - 1; // start by placing the block p = getLocalPlayer().rotationPitch; BlockPos pos = getBlockBelow(); Vec3d look = new Vec3d(pos.getX() + 0.5D, pos.getY(), pos.getZ() + 0.5D); Angle va = Utils.getLookAtAngles(look); setViewAngles(va.getPitch(), va.getYaw()); } @Override public void onStop() { halting.start(); } @Override public boolean isRunnable() { return LocalPlayerInventory.getHotbarInventory() .stream() .anyMatch(item -> item.getItemStack().getItem() instanceof ItemRedstone) && (Blocks.REDSTONE_WIRE.canPlaceBlockAt(getWorld(), getBlockBelow()) || isPlaced()); // return false; // disabled until functional } @Override public boolean isRunning() { return (!halting.isStarted() || !halting.hasTimeElapsed(5_000)) && isPlaced(); } }, ; Setting<Boolean> parentSetting; TaskEnum() {} public void setParentSetting(Setting<Boolean> parentSetting) { this.parentSetting = parentSetting; } public boolean isEnabled() { Objects.requireNonNull(parentSetting, "Setting must be set for all tasks in enum"); return parentSetting.get(); } static final int TPS = 20; static boolean silent = false; static void swingHand() { if (silent) getNetworkManager().sendPacket(new CPacketAnimation(EnumHand.MAIN_HAND)); else getLocalPlayer().swingArm(EnumHand.MAIN_HAND); } static void setViewAngles(double p, double y) { /* if(silent) getNetworkManager().sendPacket(new CPacketPlayer.Rotation((float)p, (float)y, getLocalPlayer().onGround)); else LocalPlayerUtils.setViewAngles(p, y);*/ // TODO: view angle stuff } public static void setSilent(boolean silent) { TaskEnum.silent = silent; } public static final EnumSet<TaskEnum> ALL = EnumSet.allOf(TaskEnum.class); } interface IAFKTask { void onTick(); void onStart(); void onStop(); default boolean isRunnable() { return true; } default boolean isRunning() { return false; } } }
package com.maxmind.geoip2; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.util.Arrays; import java.util.List; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.maxmind.geoip2.exception.AddressNotFoundException; import com.maxmind.geoip2.model.Country; import com.maxmind.geoip2.model.Omni; import com.maxmind.maxminddb.MaxMindDbReader; /** * Instances of this class provide a reader for the GeoIP2 database format. IP * addresses can be looked up using the <code>get</code> method. */ public class DatabaseReader implements Closeable { // This is sort of annoying. Rename one of the two? private final MaxMindDbReader reader; private final ObjectMapper om; /** * Constructs a Reader for the GeoIP2 database format. The file passed to it * must be a valid GeoIP2 database file. * * @param database * the GeoIP2 database file to use. * @throws IOException * if there is an error opening or reading from the file. */ public DatabaseReader(File database) throws IOException { this(database, Arrays.asList("en")); } /** * Constructs a Reader for the GeoIP2 database format. The file passed to it * must be a valid GeoIP2 database file. * * @param database * the GeoIP2 database file to use. * @param languages * List of language codes to use in name property from most * preferred to least preferred. * @throws IOException * if there is an error opening or reading from the file. */ public DatabaseReader(File database, List<String> languages) throws IOException { this.reader = new MaxMindDbReader(database); this.om = new ObjectMapper(); this.om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); InjectableValues inject = new InjectableValues.Std().addValue( "languages", languages); this.om.setInjectableValues(inject); } /** * @param ipAddress * IPv4 or IPv6 address to lookup. * @return A <T> object with the data for the IP address * @throws IOException * if there is an error opening or reading from the file. * @throws AddressNotFoundException * if the IP address is not in our database */ public <T extends Country> T get(InetAddress ipAddress) throws IOException, AddressNotFoundException { ObjectNode node = (ObjectNode) this.reader.get(ipAddress); // XXX - I am not sure Java programmers would expect an exception here, // but the web service code does throw an exception in this case. If we // keep this exception, we should adjust the web service to throw the // same exception when it gets and IP_ADDRESS_NOT_FOUND error. if (node == null) { throw new AddressNotFoundException("The address " + ipAddress.getHostAddress() + " is not in the database."); } if (!node.has("traits")) { node.put("traits", this.om.createObjectNode()); } ObjectNode traits = (ObjectNode) node.get("traits"); traits.put("ip_address", ipAddress.getHostAddress()); // The cast and the Omni.class are sort of ugly. There might be a // better way return (T) this.om.treeToValue(node, Omni.class); } /** * Closes the GeoIP2 database and returns resources to the system. * * @throws IOException * if an I/O error occurs. */ @Override public void close() throws IOException { this.reader.close(); } }
package com.noodlesandwich.streams; import java.util.Iterator; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.noodlesandwich.streams.functions.Concat; import com.noodlesandwich.streams.functions.Drop; import com.noodlesandwich.streams.functions.Filter; import com.noodlesandwich.streams.functions.Fold; import com.noodlesandwich.streams.functions.FoldFunction; import com.noodlesandwich.streams.functions.Map; import com.noodlesandwich.streams.functions.Take; import com.noodlesandwich.streams.functions.Zip; import com.noodlesandwich.streams.functions.ZipWithFunction; import com.noodlesandwich.streams.implementations.Cons; import com.noodlesandwich.streams.implementations.Nil; import com.noodlesandwich.streams.implementations.Wrapper; import com.noodlesandwich.streams.iterators.StreamIterator; public abstract class Stream<T> implements Iterable<T> { public static <T> Stream<T> cons(T head, Stream<T> tail) { return new Cons<T>(head, tail); } public static <T> Stream<T> nil() { return new Nil<T>(); } public static <T> Stream<T> clone(Iterable<T> iterable) { return clone(iterable.iterator()); } private static <T> Stream<T> clone(Iterator<T> iterator) { if (!iterator.hasNext()) { return nil(); } return cons(iterator.next(), clone(iterator)); } public static <T> Stream<T> wrap(Iterable<T> iterable) { return wrap(iterable.iterator()); } public static <T> Stream<T> wrap(Iterator<T> iterator) { return new Wrapper<T>(iterator); } public <U> Stream<U> map(Function<T, U> function) { return new Map<T, U>(function, this); } public Stream<T> filter(Predicate<T> predicate) { return new Filter<T>(predicate, this); } public <U> U fold(FoldFunction<T, U> foldFunction, U initializer) { return new Fold<T, U>(foldFunction, initializer).apply(this); } public Stream<T> take(int n) { return new Take<T>(n, this); } public Stream<T> drop(int n) { return new Drop<T>(n, this); } public Stream<T> concat(Stream<T> nextStream) { return Concat.concat(this, nextStream); } public <U> Stream<Pair<T, U>> zip(Stream<U> pairedStream) { return zipWith(pairedStream, new ZipWithFunction<T, U, Pair<T, U>>() { @Override public Pair<T, U> apply(T a, U b) { return new Pair<T, U>(a, b); } }); } public <U, V> Stream<V> zipWith(Stream<U> pairedStream, ZipWithFunction<? super T, ? super U, V> zipWithFunction) { return new Zip<T, U, V>(zipWithFunction, this, pairedStream); } public abstract boolean isNil(); public abstract T head(); public abstract Stream<T> tail(); @Override public Iterator<T> iterator() { return new StreamIterator<T>(this); } }
package com.sdl.selenium.extjs6.grid; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.table.Table; import com.sdl.selenium.web.utils.RetryUtils; import com.sdl.selenium.web.utils.Utils; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Collections; import java.util.List; @Slf4j public class Grid extends Table implements Scrollable { public Grid() { setClassName("Grid"); setBaseCls("x-grid"); setTag("*"); WebLocator header = new WebLocator().setClasses("x-title").setRoot(" setTemplateTitle(new WebLocator(header)); } public Grid(WebLocator container) { this(); setContainer(container); } /** * <pre>{@code * Grid grid = new Grid().setHeaders("Company", "Price", "Change"); * }</pre> * * @param headers grid's headers in order * @param <T> element which extended the Grid * @return this Grid */ public <T extends Table> T setHeaders(final String... headers) { List<WebLocator> list = new ArrayList<>(); for (int i = 0; i < headers.length; i++) { WebLocator headerEL = new WebLocator(this).setTag("*[" + (i + 1) + "]").setClasses("x-column-header"). setText(headers[i], SearchType.DEEP_CHILD_NODE_OR_SELF, SearchType.EQUALS); list.add(headerEL); } setChildNodes(list.stream().toArray(WebLocator[]::new)); return (T) this; } @Override public Row getRow(int rowIndex) { return new Row(this, rowIndex).setInfoMessage("-Row"); } public Group getGroup(String groupName) { return new Group(this, groupName).setInfoMessage("-Group"); } public Group getGroup(int rowIndex) { return new Group(this, rowIndex).setInfoMessage("-Group"); } @Override public Row getRow(String searchElement) { return new Row(this, searchElement, SearchType.EQUALS).setInfoMessage("-Row"); } @Override public Row getRow(String searchElement, SearchType... searchTypes) { return new Row(this, searchElement, searchTypes).setInfoMessage("-Row"); } public Row getRow(Cell... byCells) { return new Row(this, byCells).setInfoMessage("-Row"); } public Row getRow(int indexRow, Cell... byCells) { return new Row(this, indexRow, byCells).setInfoMessage("-Row"); } @Override public Cell getCell(int rowIndex, int columnIndex) { Row row = getRow(rowIndex); return new Cell(row, columnIndex).setInfoMessage("cell - Table"); } @Override public Cell getCell(String searchElement, SearchType... searchTypes) { Row row = new Row(this); return new Cell(row).setText(searchElement, searchTypes); } public Cell getCell(int rowIndex, int columnIndex, String text) { Row row = getRow(rowIndex); return new Cell(row, columnIndex, text, SearchType.EQUALS); } public Cell getCell(String searchElement, String columnText, SearchType... searchTypes) { Row row = getRow(searchElement, SearchType.CONTAINS); return new Cell(row).setText(columnText, searchTypes); } @Override public Cell getCell(String searchElement, int columnIndex, SearchType... searchTypes) { return new Cell(new Row(this, searchElement, searchTypes), columnIndex); } public Cell getCell(int columnIndex, Cell... byCells) { return new Cell(getRow(byCells), columnIndex); } public Cell getCell(int columnIndex, String text, Cell... byCells) { return new Cell(getRow(byCells), columnIndex, text, SearchType.EQUALS); } public boolean waitToActivate(int seconds) { String info = toString(); int count = 0; boolean hasMask; while ((hasMask = hasMask()) && (count < seconds)) { count++; log.info("waitToActivate:" + (seconds - count) + " seconds; " + info); Utils.sleep(900); } return !hasMask; } private boolean hasMask() { WebLocator mask = new WebLocator(this).setClasses("x-mask").setElPathSuffix("style", "not(contains(@style, 'display: none'))").setAttribute("aria-hidden", "false").setInfoMessage("Mask"); return mask.waitToRender(500, false); } @Override public boolean waitToPopulate(int seconds) { Row row = getRow(1).setVisibility(true).setRoot("//..//").setInfoMessage("first Row"); WebLocator body = new WebLocator(this).setClasses("x-grid-header-ct"); // TODO see if must add for all rows row.setContainer(body); return row.waitToRender(seconds * 1000L); } public List<String> getHeaders() { List<String> headers = new ArrayList<>(); WebLocator header = new WebLocator(this).setClasses("x-grid-header-ct"); String headerText = RetryUtils.retrySafe(4, header::getText); Collections.addAll(headers, headerText.trim().split("\n")); return headers; } @Override public List<List<String>> getCellsText(int... excludedColumns) { Row rowsEl = new Row(this); Row rowEl = new Row(this, 1); Cell columnsEl = new Cell(rowEl); int rows = rowsEl.size(); int columns = columnsEl.size(); List<Integer> columnsList = getColumns(columns, excludedColumns); if (rows <= 0) { return null; } else { List<List<String>> listOfList = new ArrayList<>(); boolean canRead = true; String id = ""; int timeout = 0; do { for (int i = 1; i <= rows; ++i) { if (canRead) { List<String> list = new ArrayList<>(); for (int j : columnsList) { list.add(this.getCell(i, j).getText(true).trim()); } listOfList.add(list); } else { String currentId = new Row(this, i).getAttributeId(); if (!"".equals(id) && id.equals(currentId)) { canRead = true; } } } if (isScrollBottom()) { break; } id = new Row(this, rows).getAttributeId(); scrollPageDownInTree(); canRead = false; timeout++; } while (timeout < 30); return listOfList; } } public List<List<String>> getCellsText(String group, int... excludedColumns) { Group groupEl = getGroup(group); groupEl.expand(); List<Row> groupElRows = groupEl.getRows(); Cell columnsEl = new Cell(groupElRows.get(1)); int rows = groupElRows.size(); int columns = columnsEl.size(); List<Integer> columnsList = getColumns(columns, excludedColumns); if (rows <= 0) { return null; } else { List<List<String>> listOfList = new ArrayList<>(); boolean canRead = true; String id = ""; int timeout = 0; do { for (int i = 0; i < rows; ++i) { if (canRead) { List<String> list = new ArrayList<>(); for (int j : columnsList) { list.add(groupElRows.get(i).getCell(j).getText(true).trim()); } listOfList.add(list); } else { String currentId = new Row(this, i + 1).getAttributeId(); if (!"".equals(id) && id.equals(currentId)) { canRead = true; } } } if (isScrollBottom() || listOfList.size() >= rows) { break; } id = new Row(this, rows).getAttributeId(); scrollPageDownInTree(); canRead = false; timeout++; } while (listOfList.size() < rows && timeout < 30); return listOfList; } } @Override public int getCount() { if (ready(true)) { return new Row(this).size(); } else { return -1; } } public List<String> getGroupsName() { Group group = new Group(this); int size = group.size(); List<String> list = new ArrayList<>(); for (int i = 1; i <= size; i++) { group.setResultIdx(i); list.add(group.getNameGroup()); } return list; } public String getNextGroupName(String groupName) { Group group = new Group(this); int size = group.size(); List<String> list = new ArrayList<>(); for (int i = 1; i <= size; i++) { group.setResultIdx(i); list.add(group.getNameGroup()); } for (int i = 0; i < list.size(); i++) { String g = list.get(i).substring(0, 1).toUpperCase() + list.get(i).substring(1).toLowerCase(); if (g.contains(groupName)) { try { return list.get(i + 1).substring(0, 1).toUpperCase() + list.get(i + 1).substring(1).toLowerCase(); } catch (IndexOutOfBoundsException e) { return null; } } } return null; } }
package com.sorcix.sirc; /** * Thrown when the nickname is already in use. */ public final class PasswordException extends Exception { /** Serial Version ID */ private static final long serialVersionUID = -7856391898471344111L; /** * Creates a new PasswordException. * * @param string Error string. */ public PasswordException(final String string) { super(string); } }
package com.topsy.jmxproxy.core; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializable; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import java.io.IOException; import java.lang.reflect.Array; import java.util.List; import java.util.ArrayList; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Attribute implements JsonSerializable { private static final Logger LOG = LoggerFactory.getLogger(Attribute.class); private Object attributeValue; public void setAttributeValue(Object attributeValue) { this.attributeValue = attributeValue; } public void serialize(JsonGenerator jgen, SerializerProvider sp) throws IOException, JsonProcessingException { buildJson(jgen, attributeValue); } public void serializeWithType(JsonGenerator jgen, SerializerProvider sp, TypeSerializer ts) throws IOException, JsonProcessingException { buildJson(jgen, attributeValue); } private void buildJson(JsonGenerator jgen, Object objectValue) throws IOException, JsonProcessingException { if (objectValue == null) { jgen.writeNull(); } else if (objectValue instanceof Boolean) { jgen.writeBoolean((Boolean)objectValue); } else if (objectValue instanceof JsonNode) { jgen.writeTree((JsonNode)objectValue); } else if (objectValue.getClass().isArray()) { jgen.writeStartArray(); int length = Array.getLength(objectValue); for (int i = 0; i < length; i++) { buildJson(jgen, Array.get(objectValue, i)); } jgen.writeEndArray(); } else if (objectValue instanceof Iterable) { Iterable data = (Iterable) objectValue; jgen.writeStartArray(); for (Object objectEntry : data) { buildJson(jgen, objectEntry); } jgen.writeEndArray(); } else if (objectValue instanceof TabularData) { TabularData data = (TabularData) objectValue; jgen.writeStartArray(); for (Object objectEntry : data.values()) { buildJson(jgen, objectEntry); } jgen.writeEndArray(); } else if (objectValue instanceof CompositeData) { CompositeData data = (CompositeData) objectValue; jgen.writeStartObject(); for (String objectEntry : data.getCompositeType().keySet()) { jgen.writeFieldName(objectEntry); buildJson(jgen, data.get(objectEntry)); } jgen.writeEndObject(); } else if (objectValue instanceof Number) { Double data = ((Number) objectValue).doubleValue(); if (data.isNaN()) { jgen.writeString("NaN"); } else if (data.isInfinite()) { jgen.writeString("Infinity"); } else { jgen.writeNumber(((Number)objectValue).toString()); } } else { try { String input = objectValue.toString(); List<JsonNode> parts = new ArrayList<JsonNode>(); ObjectMapper mapper = new ObjectMapper(); JsonParser parser = new JsonFactory().createJsonParser(input); for (parser.nextToken(); parser.hasCurrentToken(); parser.nextToken()) { JsonToken tok = parser.getCurrentToken(); int pos = (int)parser.getTokenLocation().getCharOffset(); if (tok == JsonToken.START_OBJECT || tok == JsonToken.START_ARRAY) { parser.skipChildren(); } parts.add(mapper.readTree(input.substring(pos, (int)parser.getTokenLocation().getCharOffset() + parser.getTextLength() + (tok == JsonToken.VALUE_STRING ? 2 : 0)))); } if (parts.isEmpty()) { jgen.writeString(""); } else if (parts.size() == 1) { buildJson(jgen, parts.get(0)); } else { buildJson(jgen, parts); } } catch (JsonParseException e) { jgen.writeString(objectValue.toString()); } } } }
package fr.wseduc.cas.endpoint; import java.net.URI; import java.net.URISyntaxException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.UUID; import java.util.logging.Logger; import fr.wseduc.cas.async.Handler; import fr.wseduc.cas.data.DataHandler; import fr.wseduc.cas.data.DataHandlerFactory; import fr.wseduc.cas.entities.AuthCas; import fr.wseduc.cas.entities.LoginTicket; import fr.wseduc.cas.entities.ServiceTicket; import fr.wseduc.cas.exceptions.AuthenticationException; import fr.wseduc.cas.exceptions.Try; import fr.wseduc.cas.http.HttpClient; import fr.wseduc.cas.http.HttpClientFactory; import fr.wseduc.cas.http.Request; public class Credential { private DataHandlerFactory dataHandlerFactory; private CredentialResponse credentialResponse; private HttpClientFactory httpClientFactory; private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); private static final Logger log = Logger.getLogger("Credential"); public void loginRequestor(final Request request) { final DataHandler dataHandler = dataHandlerFactory.create(request); final String service = request.getParameter("service") != null ? request.getParameter("service") : request.getParameter("TARGET"); final boolean renew = Boolean.getBoolean(request.getParameter("renew")); final boolean gateway = Boolean.getBoolean(request.getParameter("gateway")); final String method = request.getParameter("method") != null ? request.getParameter("method") : "GET"; dataHandler.getOrCreateAuth(request, new Handler<AuthCas>() { @Override public void handle(AuthCas authCas) { // TODO check if null if (!authCas.isLoggedIn()) { credentialResponse.loginRequestorResponse(request, new LoginTicket(), service, renew, gateway, method); } else { if (service != null && !service.trim().isEmpty()) { loginAcceptor(request, authCas); } else { credentialResponse.loggedIn(request); } } } }); } public void loginAcceptor(final Request request) { loginAcceptor(request, null); } private void loginAcceptor(final Request request, final AuthCas authCas) { final DataHandler dataHandler = dataHandlerFactory.create(request); if (authCas != null && authCas.isLoggedIn()) { generateServiceTicket(request, authCas, dataHandler); } else { dataHandler.getOrCreateAuth(request, new Handler<AuthCas>() { @Override public void handle(AuthCas auth) { if (auth != null && auth.isLoggedIn()) { generateServiceTicket(request, authCas, dataHandler); } else { request.getFormAttributesMap(new Handler<Map<String, String>>() { @Override public void handle(Map<String, String> attributes) { dataHandler.authenticateUser( attributes.get("login"), attributes.get("password"), authCas, new Handler<Try<AuthenticationException, AuthCas>>() { @Override public void handle(Try<AuthenticationException, AuthCas> ac) { try { generateServiceTicket(request, ac.get(), dataHandler); } catch (AuthenticationException e) { credentialResponse.denyResponse(request, e); } } }); } }); } } }); } } private void generateServiceTicket(final Request request, final AuthCas authCas, final DataHandler dataHandler) { final String service = request.getParameter("service") != null ? request.getParameter("service") : request.getParameter("TARGET"); dataHandler.validateService(service, new Handler<Boolean>(){ @Override public void handle(Boolean success) { if (success) { final ServiceTicket serviceTicket = new ServiceTicket(service); final String ticketParameterName = request.getParameter("ticketAttributeName"); if (ticketParameterName != null && !ticketParameterName.trim().isEmpty()) { serviceTicket.setTicketParameter(ticketParameterName); } if (request.getParameter("TARGET") != null) { serviceTicket.setTicketParameter("SAMLart"); } authCas.addServiceTicket(serviceTicket); dataHandler.persistAuth(authCas, new Handler<Boolean>() { @Override public void handle(Boolean success) { if (success) { credentialResponse.loginAcceptorResponse(request, serviceTicket); } else { credentialResponse.denyResponse(request, new AuthenticationException("SESSION_ERROR")); } } }); } else { credentialResponse.denyResponse(request, new AuthenticationException("INVALID_SERVICE")); } } }); } public void logout(final Request request) { final String service = request.getParameter("service"); final DataHandler dataHandler = dataHandlerFactory.create(request); dataHandler.getAndDestroyAuth(request, new Handler<AuthCas>(){ @Override public void handle(AuthCas authCas) { if (authCas != null) { singleLogout(authCas); } if (service != null && !service.trim().isEmpty()) { credentialResponse.logoutRedirectService(request, service); } else { credentialResponse.logoutResponse(request); } } }); } public void logout(final String user) { final DataHandler dataHandler = dataHandlerFactory.create(null); dataHandler.getAndDestroyAuth(user, new Handler<AuthCas>(){ @Override public void handle(AuthCas authCas) { if (authCas != null) { singleLogout(authCas); } } }); } private void singleLogout(AuthCas authCas) { for (ServiceTicket st : authCas.getServiceTickets()) { try { URI uri = new URI(st.redirectUri()); int port = uri.getPort() > 0 ? uri.getPort() : ("https".equals(uri.getScheme()) ? 443 : 80); HttpClient client = httpClientFactory.create(uri.getHost(), port, "https".equals(uri.getScheme())); String serviceUri = st.redirectUri().replaceFirst( "^(?:([^:/? client.post(serviceUri, sloBody(st.getTicket()), null); } catch (URISyntaxException e) { log.severe(e.getMessage()); } } } private String sloBody(String ticket) { return "<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\"\n" + " ID=\"" + UUID.randomUUID().toString() + "\" Version=\"2.0\" IssueInstant=\"" + df.format(new Date()) + "\">\n" + " <saml:NameID xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\">\n" + " @NOT_USED@\n" + " </saml:NameID>\n" + " <samlp:SessionIndex>" + ticket + "</samlp:SessionIndex>\n" + " </samlp:LogoutRequest>"; } public void setDataHandlerFactory(DataHandlerFactory dataHandlerFactory) { this.dataHandlerFactory = dataHandlerFactory; } public void setCredentialResponse(CredentialResponse credentialResponse) { this.credentialResponse = credentialResponse; } public void setHttpClientFactory(HttpClientFactory httpClientFactory) { this.httpClientFactory = httpClientFactory; } }
package io.lcs.framework.base; import com.google.gson.Gson; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specifications; import javax.persistence.EntityManager; import javax.persistence.Id; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BaseService extends Base { @Autowired protected EntityManager entityManager; @Autowired protected Gson gson; private final static String[] PERSIST_ANNOTATION = new String[]{"ID", "COLUMN", "MANYTOONE"}; protected <T extends BasePojo> Specifications<T> initSearch(final T t) { return this.initSearch(t, new String[0]); } protected <T extends BasePojo> Specifications<T> initSearch(final T t, String... ignoreFileds) { Specifications<T> specifications = Specifications.where(null); List<String> ignoreFiledList = ignoreFileds == null ? new ArrayList<String>() : Arrays.asList(ignoreFileds); final Class<T> clazz = (Class<T>) t.getClass(); for (final Field field : clazz.getDeclaredFields()) { if (!hasPersistAnnotation(field.getAnnotations())) continue; String filedName = field.getName(); Object val = null; try { String prefix = field.getType().equals(boolean.class) || field.getType().equals(Boolean.class) ? "is" : "get"; String methodName = filedName.startsWith("is") ? filedName : prefix + filedName.substring(0, 1).toUpperCase() + filedName.substring(1); val = clazz.getDeclaredMethod(methodName).invoke(t); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (ignoreFiledList.contains(filedName)) continue; if (val == null) continue; if (field.isAnnotationPresent(Id.class) && (Long) val == 0) continue; final Object val2 = val; specifications = specifications.and(new Specification<T>() { @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) { if (field.getType() == String.class ) { if (StringUtils.isNotBlank(val2.toString())) { return cb.like(root.<String>get(field.getName()), val2.toString()); } return null; } else { if (BasePojo.class.isAssignableFrom(field.getType())) { long id = ((BasePojo) val2).getId(); if (id <= 0) return null; } return cb.equal(root.<String>get(field.getName()), val2); } } }); } return specifications; } private boolean hasPersistAnnotation(Annotation[] annotations) { for (Annotation annotation : annotations) { String name = annotation.annotationType().getSimpleName().toUpperCase(); for (String n : PERSIST_ANNOTATION) { if( n.equals(name) ) return true; } } return false; } /** * @see io.lcs.framework.utils.AssertExt#hasId(BasePojo, String) * @param basePojo * @return */ protected static boolean hasId(BasePojo basePojo) { return basePojo != null && basePojo.getId() > 0; } }
package io.sqooba.traildb; import java.nio.ByteBuffer; import java.util.Iterator; /** * Class representing a cursor over a particular trail of the database. The cursor is initially constructed from the * TrailDB.trail() method. The cursor points to the current event and this event is updated each time a .next() is * called. * * @author B. Sottas * */ public class TrailDBIterator implements Iterable<TrailDBEvent>, AutoCloseable { private ByteBuffer cursor; private TrailDBEvent event; protected TrailDBIterator(ByteBuffer cursor, TrailDBEvent event) { this.event = event; this.cursor = cursor; } @Override public void close() { if (this.cursor != null) { TrailDBNative.INSTANCE.cursorFree(this.cursor); this.cursor = null; } } @Override public Iterator<TrailDBEvent> iterator() { return new Iterator<TrailDBEvent>() { @Override public TrailDBEvent next() { if (!TrailDBIterator.this.event.isBuilt()) { TrailDBNative.INSTANCE.cursorNext(TrailDBIterator.this.cursor, TrailDBIterator.this.event); } return TrailDBIterator.this.event; } @Override public boolean hasNext() { return TrailDBNative.INSTANCE.cursorNext(TrailDBIterator.this.cursor, TrailDBIterator.this.event) == 0; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } public TrailDBEvent getCurrentEvent() { return new TrailDBEvent(TrailDBIterator.this.event); } }
package io.vertx.codegen; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.vertx.codegen.annotations.DataObject; import io.vertx.codegen.annotations.GenModule; import io.vertx.codegen.annotations.ProxyGen; import io.vertx.codegen.annotations.VertxGen; import org.mvel2.MVEL; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.io.Writer; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ @javax.annotation.processing.SupportedOptions({"outputDirectory","codeGenerators"}) @javax.annotation.processing.SupportedSourceVersion(javax.lang.model.SourceVersion.RELEASE_8) public class CodeGenProcessor extends AbstractProcessor { private final static ObjectMapper mapper = new ObjectMapper(); private static final Logger log = Logger.getLogger(CodeGenProcessor.class.getName()); private File outputDirectory; private Map<String, List<CodeGenerator>> codeGenerators; @Override public Set<String> getSupportedAnnotationTypes() { return Arrays.asList( VertxGen.class, ProxyGen.class, DataObject.class, DataObject.class, GenModule.class ).stream().map(Class::getName).collect(Collectors.toSet()); } private Collection<CodeGenerator> getCodeGenerators() { if (codeGenerators == null) { Map<String, List<CodeGenerator>> codeGenerators = new LinkedHashMap<>(); Enumeration<URL> descriptors = Collections.emptyEnumeration(); try { descriptors = CodeGenProcessor.class.getClassLoader().getResources("codegen.json"); } catch (IOException ignore) { processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Could not load code generator descriptors"); } while (descriptors.hasMoreElements()) { URL descriptor = descriptors.nextElement(); try (Scanner scanner = new Scanner(descriptor.openStream(), "UTF-8").useDelimiter("\\A")) { String s = scanner.next(); ObjectNode obj = (ObjectNode) mapper.readTree(s); String name = obj.get("name").asText(); ArrayNode generatorsCfg = (ArrayNode) obj.get("generators"); for (JsonNode generator : generatorsCfg) { String kind = generator.get("kind").asText(); String templateFileName = generator.get("templateFileName").asText(); String fileName = generator.get("fileName").asText(); Serializable fileNameExpression = MVEL.compileExpression(fileName); Template compiledTemplate = new Template(templateFileName); compiledTemplate.setOptions(processingEnv.getOptions()); List<CodeGenerator> generators = codeGenerators.computeIfAbsent(name, abc -> new ArrayList<>()); generators.add(new CodeGenerator(kind, fileNameExpression, compiledTemplate)); } log.info("Loaded " + name + " code generator"); } catch (Exception e) { String msg = "Could not load code generator " + descriptor; log.log(Level.SEVERE, msg, e); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg); } } String outputDirectoryOption = processingEnv.getOptions().get("outputDirectory"); if (outputDirectoryOption != null) { outputDirectory = new File(outputDirectoryOption); if (!outputDirectory.exists()) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Output directory " + outputDirectoryOption + " does not exist"); } if (!outputDirectory.isDirectory()) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Output directory " + outputDirectoryOption + " is not a directory"); } } String codeGeneratorsOption = processingEnv.getOptions().get("codeGenerators"); if (codeGeneratorsOption != null) { Set<String> wanted = Stream.of(codeGeneratorsOption.split(",")).map(String::trim).collect(Collectors.toSet()); if (codeGenerators.keySet().containsAll(wanted)) { codeGenerators.keySet().retainAll(wanted); } else { codeGenerators.clear(); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Code generators " + wanted.removeAll(codeGenerators.keySet()) + " not found"); } } this.codeGenerators = codeGenerators; } ArrayList<CodeGenerator> ret = new ArrayList<>(); codeGenerators.values().stream().forEach(ret::addAll); return ret; } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (!roundEnv.processingOver()) { Collection<CodeGenerator> codeGenerators = getCodeGenerators(); if (!roundEnv.errorRaised()) { CodeGen codegen = new CodeGen(processingEnv, roundEnv); // Generate source code codegen.getModels().forEach(entry -> { try { Model model = entry.getValue(); if (outputDirectory != null) { Map<String, Object> vars = new HashMap<>(); vars.put("helper", new Helper()); vars.put("options", processingEnv.getOptions()); vars.put("fileSeparator", File.separator); vars.put("fqn", model.getFqn()); vars.put("module", model.getModule()); vars.putAll(model.getVars()); for (CodeGenerator codeGenerator : codeGenerators) { if (codeGenerator.kind.equals(model.getKind())) { String relativeName = (String) MVEL.executeExpression(codeGenerator.filenameExpr, vars); if (relativeName != null) { if (relativeName.endsWith(".java")) { // Special handling for .java JavaFileObject target = processingEnv.getFiler().createSourceFile(relativeName.substring(0, relativeName.length() - ".java".length())); String output = codeGenerator.transformTemplate.render(model); try (Writer writer = target.openWriter()) { writer.append(output); } } else { File target = new File(outputDirectory, relativeName); codeGenerator.transformTemplate.apply(model, target); } log.info("Generated model " + model.getFqn() + ": " + relativeName); } } } } else { log.info("Validated model " + model.getFqn()); } } catch (GenException e) { String msg = "Could not generate model for " + e.element + ": " + e.msg; log.log(Level.SEVERE, msg, e); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, e.element); } catch (Exception e) { String msg = "Could not generate element for " + entry.getKey() + ": " + e.getMessage(); log.log(Level.SEVERE, msg, e); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, entry.getKey()); } }); } } return true; } static class CodeGenerator { final String kind; final Serializable filenameExpr; final Template transformTemplate; CodeGenerator(String kind, Serializable filenameExpr, Template transformTemplate) { this.kind = kind; this.filenameExpr = filenameExpr; this.transformTemplate = transformTemplate; } } }
/** * Purely functional collections based on {@linkplain javaslang.collection.TraversableOnce}. * * <h2>Performance Characteristics of Javaslang Collections</h2> * <table cellpadding="5" cellspacing="0" border="1" style="border-collapse: collapse"> * <caption>Time Complexity of Sequential Operations</caption> * <thead> * <tr> * <th>&nbsp;</th> * <th>head()</th> * <th>tail()</th> * <th>get(int)</th> * <th>update(int, T)</th> * <th>prepend(T)</th> * <th>append(T)</th> * </tr> * </thead> * <tbody> * <tr><td>{@linkplain javaslang.collection.Array}</td><td><small>const</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td></tr> * <tr><td>{@linkplain javaslang.collection.CharSeq}</td><td><small>const</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>linear</small></td></tr> * <tr><td><em>{@linkplain javaslang.collection.Iterator}</em></td><td><small>const</small></td><td><small>const</small></td><td>&mdash;</td><td>&mdash;</td><td>&mdash;</td><td>&mdash;</td></tr> * <tr><td>{@linkplain javaslang.collection.List}</td><td><small>const</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>linear</small></td></tr> * <tr><td>{@linkplain javaslang.collection.Queue}</td><td><small>const</small></td><td><small>const<sup>a</sup></small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>const</small></td><td><small>const</small></td></tr> * <tr><td>{@linkplain javaslang.collection.Stream}</td><td><small>const</small></td><td><small>const</small></td><td><small>linear</small></td><td><small>linear</small></td><td><small>const<sup>lazy</sup></small></td><td><small>const<sup>lazy</sup></small></td></tr> * <tr><td>{@linkplain javaslang.collection.Vector}</td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td></tr> * </tbody> * </table> * <br> * <table cellpadding="5" cellspacing="0" border="1" style="border-collapse: collapse"> * <caption>Time Complexity of Map/Set Operations</caption> * <thead> * <tr> * <th>&nbsp;</th> * <th>contains/Key</th> * <th>add/put</th> * <th>remove</th> * <th>min</th> * </tr> * </thead> * <tbody> * <tr><td>{@linkplain javaslang.collection.HashMap}</td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td></tr> * <tr><td>{@linkplain javaslang.collection.HashSet}</td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td><td><small>const<sup>eff</sup></small></td></tr> * <tr><td><em>{@linkplain javaslang.collection.Tree}</em></td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td></tr> * <tr><td>{@linkplain javaslang.collection.TreeMap}</td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td></tr> * <tr><td>{@linkplain javaslang.collection.TreeSet}</td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td><td><small>log</small></td></tr> * </tbody> * </table> * <br> * <ul> * <li><small>const</small>&nbsp;&middot;&nbsp;constant time</li> * <li><small>const<sup>a</sup></small>&nbsp;&middot;&nbsp;amotized constant time, few operations may take longer</li> * <li><small>const<sup>eff</sup></small>&nbsp;&middot;&nbsp;effectively constant time, depending on assumptions like distribution of hash keys</li> * <li><small>const<sup>lazy</sup></small>&nbsp;&middot;&nbsp;lazy constant time, the operation is deferred</li> * <li><small>log</small>&nbsp;&middot;&nbsp;logarithmic time</li> * <li><small>linear</small>&nbsp;&middot;&nbsp;linear time</li> * </ul> * * @since 1.1.0 */ package javaslang.collection;
package jfdi.logic.commands; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.stream.Collectors; import jfdi.logic.events.SearchDoneEvent; import jfdi.logic.interfaces.Command; import jfdi.storage.apis.TaskAttributes; import jfdi.storage.apis.TaskDb; /** * @author Liu Xinan */ public class SearchCommand extends Command { private HashSet<String> keywords; private SearchCommand(Builder builder) { this.keywords = builder.keywords; } public static class Builder { HashSet<String> keywords = new HashSet<>(); public Builder addKeyword(String keyword) { this.keywords.add(keyword); return this; } public Builder addKeywords(Collection<String> keywords) { this.keywords.addAll(keywords); return this; } public SearchCommand build() { return new SearchCommand(this); } } @Override public void execute() { Collection<TaskAttributes> allTasks = TaskDb.getInstance().getAll(); ArrayList<TaskAttributes> results = allTasks.stream() .filter(task -> { for (String keyword : keywords) { if (!task.getDescription().matches(String.format("(?i:.*\\b%s\\b.*)", keyword))) { return false; } } return true; }) .collect(Collectors.toCollection(ArrayList::new)); eventBus.post(new SearchDoneEvent(results, keywords)); System.out.println(results); } }
package mil.dds.anet.database; import java.util.Arrays; import java.util.List; import mil.dds.anet.AnetObjectEngine; import mil.dds.anet.beans.Location; import mil.dds.anet.beans.lists.AnetBeanList; import mil.dds.anet.beans.search.LocationSearchQuery; import mil.dds.anet.database.mappers.LocationMapper; import mil.dds.anet.utils.DaoUtils; import ru.vyarus.guicey.jdbi3.tx.InTransaction; public class LocationDao extends AnetBaseDao<Location, LocationSearchQuery> { public static final String TABLE_NAME = "locations"; @Override public Location getByUuid(String uuid) { return getByIds(Arrays.asList(uuid)).get(0); } static class SelfIdBatcher extends IdBatcher<Location> { private static final String sql = "/* batch.getLocationsByUuids */ SELECT * from locations where uuid IN ( <uuids> )"; public SelfIdBatcher() { super(sql, "uuids", new LocationMapper()); } } @Override public List<Location> getByIds(List<String> uuids) { final IdBatcher<Location> idBatcher = AnetObjectEngine.getInstance().getInjector().getInstance(SelfIdBatcher.class); return idBatcher.getByIds(uuids); } @Override public Location insertInternal(Location l) { getDbHandle().createUpdate( "/* locationInsert */ INSERT INTO locations (uuid, name, status, lat, lng, \"createdAt\", " + "\"updatedAt\", \"customFields\") VALUES (:uuid, :name, :status, :lat, :lng, :createdAt, " + ":updatedAt, :customFields)") .bindBean(l).bind("createdAt", DaoUtils.asLocalDateTime(l.getCreatedAt())) .bind("updatedAt", DaoUtils.asLocalDateTime(l.getUpdatedAt())) .bind("status", DaoUtils.getEnumId(l.getStatus())).execute(); return l; } @Override public int updateInternal(Location l) { return getDbHandle().createUpdate("/* updateLocation */ UPDATE locations " + "SET name = :name, status = :status, lat = :lat, lng = :lng, \"updatedAt\" = :updatedAt, " + "\"customFields\" = :customFields WHERE uuid = :uuid").bindBean(l) .bind("updatedAt", DaoUtils.asLocalDateTime(l.getUpdatedAt())) .bind("status", DaoUtils.getEnumId(l.getStatus())).execute(); } @Override public AnetBeanList<Location> search(LocationSearchQuery query) { return AnetObjectEngine.getInstance().getSearcher().getLocationSearcher().runSearch(query); } @InTransaction public int mergeLocations(Location loserLocation, Location winnerLocation) { final String loserLocationUuid = loserLocation.getUuid(); final String winnerLocationUuid = winnerLocation.getUuid(); // Update Locations update(winnerLocation); // Update approvalSteps updateForMerge("approvalSteps", "relatedObjectUuid", winnerLocationUuid, loserLocationUuid); // Update reports location updateForMerge("reports", "locationUuid", winnerLocationUuid, loserLocationUuid); // update positions location updateForMerge("positions", "locationUuid", winnerLocationUuid, loserLocationUuid); // update noteRelatedObjects location updateM2mForMerge("noteRelatedObjects", "noteUuid", "relatedObjectUuid", winnerLocationUuid, loserLocationUuid); // finally delete the location! return deleteForMerge("locations", "uuid", loserLocationUuid); } // TODO: Don't delete any location if any references exist. }
package moba.server.messagehandler; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import moba.server.com.SenderI; import moba.server.database.Database; import moba.server.datatypes.enumerations.ErrorId; import moba.server.datatypes.objects.TrackLayoutInfoData; import moba.server.datatypes.objects.TracklayoutSymbolData; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import moba.server.json.JSONException; import moba.server.messages.Message; import moba.server.messages.MessageHandlerA; import moba.server.messages.messageType.LayoutMessage; import moba.server.tracklayout.utilities.TracklayoutLock; import moba.server.utilities.config.Config; import moba.server.utilities.config.ConfigException; import moba.server.utilities.exceptions.ErrorException; public class Layout extends MessageHandlerA { protected static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); protected Database database = null; protected SenderI dispatcher = null; protected TracklayoutLock lock = null; protected Config config = null; protected long activeLayout = 0; public Layout(SenderI dispatcher, Database database, TracklayoutLock lock, Config config) { this.database = database; this.dispatcher = dispatcher; this.lock = lock; this.config = config; } @Override public int getGroupId() { return LayoutMessage.GROUP_ID; } @Override public void init() { Object o; o = config.getSection("trackLayout.activeTracklayoutId"); if(o != null) { activeLayout = (long)o; } } @Override public void shutdown() { freeResources(-1); try { storeData(); } catch(ConfigException | IOException | JSONException e) { Layout.LOGGER.log(Level.WARNING, "<{0}>", new Object[]{e.toString()}); } } @Override public void freeResources(long appId) { lock.freeLocks(appId); } @Override public void handleMsg(Message msg) throws ErrorException { try { switch(LayoutMessage.fromId(msg.getMessageId())) { case GET_LAYOUTS_REQ: getLayouts(msg); break; case GET_LAYOUT_REQ: getLayout(msg, true); break; case GET_LAYOUT_READ_ONLY_REQ: getLayout(msg, false); break; case DELETE_LAYOUT: deleteLayout(msg); break; case CREATE_LAYOUT: createLayout(msg); break; case UPDATE_LAYOUT: updateLayout(msg); break; case UNLOCK_LAYOUT: unlockLayout(msg); break; case LOCK_LAYOUT: lockLayout(msg); break; case SAVE_LAYOUT: saveLayout(msg); break; default: throw new ErrorException(ErrorId.UNKNOWN_MESSAGE_ID, "unknow msg <" + Long.toString(msg.getMessageId()) + ">."); } } catch(SQLException e) { throw new ErrorException(ErrorId.DATABASE_ERROR, e.getMessage()); } catch(ConfigException | IOException | JSONException e) { throw new ErrorException(ErrorId.UNKNOWN_ERROR, e.getMessage()); } } protected void getLayouts(Message msg) throws SQLException { String q = "SELECT * FROM `TrackLayouts`;"; ArrayList<TrackLayoutInfoData> arraylist; Layout.LOGGER.log(Level.INFO, q); try(ResultSet rs = database.query(q)) { arraylist = new ArrayList(); while(rs.next()) { long id = rs.getLong("Id"); arraylist.add(new TrackLayoutInfoData( id, rs.getString("Name"), rs.getString("Description"), rs.getInt("Locked"), (id == activeLayout), rs.getDate("ModificationDate"), rs.getDate("CreationDate") )); } } dispatcher.dispatch(new Message(LayoutMessage.GET_LAYOUTS_RES, arraylist), msg.getEndpoint()); } protected void deleteLayout(Message msg) throws SQLException, IOException, ConfigException, JSONException, ErrorException { long id = (Long)msg.getData(); lock.isLockedByApp(id, msg.getEndpoint()); Connection con = database.getConnection(); String q = "DELETE FROM `TrackLayouts` WHERE (`locked` IS NULL OR `locked` = ?) AND `id` = ? "; try (PreparedStatement pstmt = con.prepareStatement(q)) { pstmt.setLong(1, msg.getEndpoint().getAppId()); pstmt.setLong(2, id); Layout.LOGGER.log(Level.INFO, "<{0}>", new Object[]{pstmt.toString()}); if(pstmt.executeUpdate() == 0) { throw new ErrorException(ErrorId.DATASET_MISSING, "could not delete <" + String.valueOf(id) + ">"); } } if(id == activeLayout) { storeData(-1); } dispatcher.dispatch(new Message(LayoutMessage.LAYOUT_DELETED, id)); } protected void createLayout(Message msg) throws SQLException, ConfigException, IOException, JSONException { Map<String, Object> map = (Map)msg.getData(); boolean isActive = (boolean)map.get("active"); long currAppId = msg.getEndpoint().getAppId(); TrackLayoutInfoData tl = new TrackLayoutInfoData((String)map.get("name"), (String)map.get("description"), currAppId, isActive); Connection con = database.getConnection(); String q = "INSERT INTO `TrackLayouts` (`Name`, `Description`, `CreationDate`, `ModificationDate`, `Locked`) VALUES (?, ?, NOW(), NOW(), ?)"; try(PreparedStatement pstmt = con.prepareStatement(q, PreparedStatement.RETURN_GENERATED_KEYS)) { pstmt.setString(1, tl.getName()); pstmt.setString(2, tl.getDescription()); pstmt.setLong(3, currAppId); pstmt.executeUpdate(); Layout.LOGGER.log(Level.INFO, pstmt.toString()); try(ResultSet rs = pstmt.getGeneratedKeys()) { rs.next(); int id = rs.getInt(1); if(isActive) { storeData(id); } tl.setId(id); } } dispatcher.dispatch(new Message(LayoutMessage.LAYOUT_CREATED, tl)); } protected void updateLayout(Message msg) throws SQLException, ConfigException, IOException, JSONException, ErrorException { Map<String, Object> map = (Map)msg.getData(); long id = (Long)map.get("id"); lock.isLockedByApp(id, msg.getEndpoint()); TrackLayoutInfoData tl; boolean active = (boolean)map.get("active"); long appId = msg.getEndpoint().getAppId(); tl = new TrackLayoutInfoData(id, (String)map.get("name"), (String)map.get("description"), appId, active, new Date(), getCreationDate(id)); Connection con = database.getConnection(); String q = "UPDATE `TrackLayouts` SET `Name` = ?, `Description` = ?, `ModificationDate` = ? WHERE (`locked` IS NULL OR `locked` = ?) AND `id` = ? "; try (PreparedStatement pstmt = con.prepareStatement(q)) { pstmt.setString(1, tl.getName()); pstmt.setString(2, tl.getDescription()); pstmt.setDate(3, new java.sql.Date(tl.getModificationDate().getTime())); pstmt.setLong(4, appId); pstmt.setLong(5, id); Layout.LOGGER.log(Level.INFO, pstmt.toString()); if(pstmt.executeUpdate() == 0) { throw new ErrorException(ErrorId.DATASET_MISSING, "could not update <" + String.valueOf(id) + ">"); } if(active) { storeData(id); } dispatcher.dispatch(new Message(LayoutMessage.LAYOUT_UPDATED, tl)); } } protected void unlockLayout(Message msg) throws SQLException, ErrorException { long id = getId(msg.getData()); lock.unlockLayout(id, msg.getEndpoint()); dispatcher.dispatch(new Message(LayoutMessage.LAYOUT_UNLOCKED, id)); } protected void lockLayout(Message msg) throws SQLException, ErrorException { long id = getId(msg.getData()); lock.lockLayout(id, msg.getEndpoint()); dispatcher.dispatch(new Message(LayoutMessage.LAYOUT_LOCKED, id)); } protected void getLayout(Message msg, boolean tryLock) throws SQLException, ErrorException { long id = getId(msg.getData()); if(tryLock) { lock.lockLayout(id, msg.getEndpoint()); } Connection con = database.getConnection(); HashMap<String, Object> map = new HashMap<>(); map.put("id", id); String q = "SELECT `Id`, `XPos`, `YPos`, `Symbol` FROM `TrackLayoutSymbols` WHERE `TrackLayoutId` = ?"; try (PreparedStatement pstmt = con.prepareStatement(q)) { pstmt.setLong(1, id); Layout.LOGGER.log(Level.INFO, pstmt.toString()); ArrayList<TracklayoutSymbolData> arraylist; ResultSet rs = pstmt.executeQuery(); arraylist = new ArrayList(); while(rs.next()) { arraylist.add(new TracklayoutSymbolData( rs.getLong("Id"), rs.getLong("XPos"), rs.getLong("YPos"), rs.getLong("Symbol") )); } map.put("symbols", arraylist); dispatcher.dispatch(new Message(LayoutMessage.GET_LAYOUT_RES, map), msg.getEndpoint()); } } protected void saveLayout(Message msg) throws SQLException, ErrorException { Map<String, Object> map = (Map<String, Object>)msg.getData(); long id = getId(map.get("id")); if(!lock.isLockedByApp(id, msg.getEndpoint())) { throw new ErrorException(ErrorId.DATASET_NOT_LOCKED, "layout <" + String.valueOf(id) + "> not locked"); } Connection con = database.getConnection(); String stmt = "UPDATE `TrackLayouts` SET `ModificationDate` = NOW() WHERE `Id` = ? "; try (PreparedStatement pstmt = con.prepareStatement(stmt)) { pstmt.setLong(1, id); Layout.LOGGER.log(Level.INFO, pstmt.toString()); if(pstmt.executeUpdate() == 0) { throw new ErrorException(ErrorId.DATASET_MISSING, "could not save <" + String.valueOf(id) + ">"); } } ArrayList<Object> arrayList = (ArrayList<Object>)map.get("symbols"); stmt = "DELETE FROM `TrackLayoutSymbols` WHERE `TrackLayoutId` = ?"; try(PreparedStatement pstmt = con.prepareStatement(stmt)) { pstmt.setLong(1, id); Layout.LOGGER.log(Level.INFO, pstmt.toString()); pstmt.executeUpdate(); } for(Object item : arrayList) { Map<String, Object> symbol = (Map<String, Object>)item; stmt = "INSERT INTO `TrackLayoutSymbols` (`Id`, `TrackLayoutId`, `XPos`, `YPos`, `Symbol`) " + "VALUES (?, ?, ?, ?, ?)"; try(PreparedStatement pstmt = con.prepareStatement(stmt)) { if(symbol.get("id") == null) { pstmt.setNull(1, java.sql.Types.INTEGER); } else { pstmt.setInt(1, (int)symbol.get("id")); } pstmt.setLong(2, id); pstmt.setLong(3, (long)symbol.get("xPos")); pstmt.setLong(4, (long)symbol.get("yPos")); pstmt.setLong(5, (long)symbol.get("symbol")); Layout.LOGGER.log(Level.INFO, pstmt.toString()); pstmt.executeUpdate(); } } dispatcher.dispatch(new Message(LayoutMessage.LAYOUT_CHANGED, map)); } protected Date getCreationDate(long id) throws SQLException { String q = "SELECT `CreationDate` FROM `TrackLayouts` WHERE `Id` = ?;"; Connection con = database.getConnection(); try (PreparedStatement pstmt = con.prepareStatement(q)) { pstmt.setLong(1, id); Layout.LOGGER.log(Level.INFO, pstmt.toString()); ResultSet rs = pstmt.executeQuery(); if(!rs.next()) { throw new NoSuchElementException(String.format("no elements found for layout <%4d>", id)); } return rs.getDate("CreationDate"); } } protected void storeData(long id) throws ConfigException, IOException, JSONException { activeLayout = id; storeData(); } protected void storeData() throws ConfigException, IOException, JSONException { HashMap<String, Object> map = new HashMap<>(); map.put("activeTracklayoutId", activeLayout); config.setSection("trackLayout", map); config.writeFile(); } protected long getId(Object o) throws ErrorException { if(o != null) { return (long)o; } if(activeLayout >= 0) { return activeLayout; } throw new ErrorException(ErrorId.NO_DEFAULT_GIVEN, "no default-tracklayout given"); } }
package mod.jd.botapi.Bot.Body; import mod.jd.botapi.Bot.Body.Senses.PlayerSensor; import mod.jd.botapi.Bot.Body.Senses.Sensor; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.settings.KeyBinding; import net.minecraft.util.MovementInput; import net.minecraft.util.MovementInputFromOptions; import java.util.HashSet; import java.util.Set; /** * This class hooks to the given {@link net.minecraft.client.entity.EntityPlayerSP}. * It provides functions to control the player and a sensor to sense its surroundings. * * NOTE : This class is only to be used on the Client Side. * * @see EntityPlayerSP * @see PlayerSensor for documentation on the {@link PlayerSensor} * @see EmptyBody for functions common to most Bodies. * @see Body for all the documentation not found here. */ public class PlayerBody extends EmptyBody { // The PlayerSensor to sense the player's surroundings. private PlayerSensor sensor; // The Player Object this object is hooked to. private EntityPlayerSP player; // A MovementInput object reserved for user input. private MovementInputFromOptions playerMovementInput; // The PlayerBody's custom MovementInput object. private MovementInput customMovementInput; // True if the user took over controls. private boolean userTookOver; // Used to hold the jump key in the JumpSafeMovementInput. private boolean holdJump = false; // Synchronised jump flag. private boolean toJump = false; // Used to count the ticks for which jump is pressed. private short jumpTicks = 0; // Used for synchronous hit func. and to prevent mouse blocking after GUI screens. private boolean toHit,keephit; // Used for synchronous interact func. and to prevent mouse blocking after GUI screens. private boolean toInteract,toKeepInteract; // The pitch and yaw this body must turn to. private double toTurnPitch,toTurnYaw; private double turnSpeed; // Speed in degrees per second the player can turn at max. private static final int MAX_TURN_PER_SEC = 180; // Controllable key bindings private static ControllableKeyBinding hitKey; private static ControllableKeyBinding useItemKey; // True if global keyBindings replaced with the static {@Link ControllableKeyBinding} above. private static boolean controlsTaken = false; /** * Constructor which sets the default values, creates the sensor and binds the given {@link EntityPlayerSP}. * It raises an {@link UnsupportedOperationException} if called at {@link net.minecraftforge.fml.relauncher.Side#SERVER}, i.e. Server Side. * It also replaces keyBindings at first run. */ public PlayerBody(EntityPlayerSP pl) { if(!Minecraft.getMinecraft().world.isRemote)throw (new UnsupportedOperationException("Cannot Instantiate PlayerBody at Server Side.")); sensor = new PlayerSensor(); customMovementInput = getCustomMovementInput(); setDefaults(); bindEntity(pl); if(controlsTaken)return; hitKey = new ControllableKeyBinding(Minecraft.getMinecraft().gameSettings.keyBindAttack); useItemKey = new ControllableKeyBinding(Minecraft.getMinecraft().gameSettings.keyBindUseItem); Minecraft.getMinecraft().gameSettings.keyBindAttack = hitKey; Minecraft.getMinecraft().gameSettings.keyBindUseItem = useItemKey; controlsTaken = true; } public void setDefaults() { toTurnPitch=0; toTurnYaw=0; turnSpeed = 0.15364d; toJump = false; holdJump = false; jumpTicks = 0; toKeepInteract = false; toInteract = false; toHit = false; keephit = false; userTookOver = false; } @Override public void unbindEntity() { player.movementInput = new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings); Minecraft.getMinecraft().gameSettings.keyBindAttack = hitKey.originalKeyBinding; Minecraft.getMinecraft().gameSettings.keyBindUseItem = useItemKey.originalKeyBinding; controlsTaken = false; setDefaults(); super.unbindEntity();; } @Override public Set<Class<?>> getCompatibleClassList() { HashSet<Class<?>> l = new HashSet<Class<?>>(); l.add(EntityPlayerSP.class); return l; } @Override public Sensor getSensor() { return sensor; } @Override public <T> void bindEntity(T object) { if(object instanceof EntityPlayerSP) { player = (EntityPlayerSP) object; sensor.bindEntity(player); playerMovementInput = new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings) { @Override public void updatePlayerMoveState() { maintainMovementControl(); } }; player.movementInput = playerMovementInput; isBinded = true; } } /** * Returns the hooked Player Object. * One can use instanceof to check for its class. * Or one can even use getClass() to get its Class. * @return player : The player hooked to this body */ @Override public Object getBindedObject() { return player; } /** * Returns a MovementInput which responds to the PlayerBody's variables. * @return MovementInput */ private MovementInput getCustomMovementInput() { return new MovementInput(){ @Override public void updatePlayerMoveState() { // Maintain proper User and PlayerBody simultaneous control. maintainMovementControl(); // If user took over do not proceed. Let the user work. Resume after user input ends. if(userTookOver)return; // Hit update if(toHit) { hitKey.pressed = true; hitKey.pressTime = 1; toHit = false; } else if(keephit){hitKey.pressed = true;++hitKey.pressTime;} else hitKey.pressed = false; // Interact update if(toInteract) { useItemKey.pressed = true; useItemKey.pressTime = 1; toInteract = false; } else if(toKeepInteract){useItemKey.pressed = true;++useItemKey.pressTime;} else useItemKey.pressed = false; // Jump Update if(toJump || holdJump) { this.jump = true; toJump = false; } else { if(jumpTicks==0) { this.jump = false; } else --jumpTicks; } // Key update this.forwardKeyDown = this.moveForward > 0; this.backKeyDown = this.moveForward < 0; this.leftKeyDown = this.moveStrafe > 0; this.rightKeyDown = this.moveStrafe < 0; // Facing direction update. if(toTurnYaw!=0) { double diff; diff = Math.min((toTurnYaw * turnSpeed), MAX_TURN_PER_SEC / 20); if ((int) toTurnYaw * 10 == 0) diff = toTurnYaw; //player.rotationYawHead += diff; player.rotationYaw += diff; toTurnYaw -= diff; } if(toTurnPitch!=0){ double diff; diff = Math.min((toTurnPitch * turnSpeed), MAX_TURN_PER_SEC / 20); if ((int) toTurnPitch * 10 == 0) diff = toTurnPitch; player.rotationPitch += diff; toTurnPitch -= diff; } } }; } /** * Maintains simultaneous control of the player entity so the both the PlayerBody and the player can control it. * @see MovementInputFromOptions#updatePlayerMoveState() for normal keyboard movement update code. * @see MovementInput for basic movement data storage code. */ public void maintainMovementControl() { if(isBinded) { userTookOver = false; playerMovementInput.moveStrafe = 0.0F; playerMovementInput.moveForward = 0.0F; if (Minecraft.getMinecraft().gameSettings.keyBindForward.isKeyDown()) { ++playerMovementInput.moveForward; playerMovementInput.forwardKeyDown = true; player.movementInput = playerMovementInput; userTookOver = true; } else { playerMovementInput.forwardKeyDown = false; } if (Minecraft.getMinecraft().gameSettings.keyBindBack.isKeyDown()) { --playerMovementInput.moveForward; playerMovementInput.backKeyDown = true; player.movementInput = playerMovementInput; userTookOver = true; } else { playerMovementInput.backKeyDown = false; } if (Minecraft.getMinecraft().gameSettings.keyBindLeft.isKeyDown()) { ++playerMovementInput.moveStrafe; playerMovementInput.leftKeyDown = true; player.movementInput = playerMovementInput; userTookOver = true; } else { playerMovementInput.leftKeyDown = false; } if (Minecraft.getMinecraft().gameSettings.keyBindRight.isKeyDown()) { --playerMovementInput.moveStrafe; playerMovementInput.rightKeyDown = true; player.movementInput = playerMovementInput; userTookOver = true; } else { playerMovementInput.rightKeyDown = false; } playerMovementInput.jump = Minecraft.getMinecraft().gameSettings.keyBindJump.isKeyDown(); playerMovementInput.sneak = Minecraft.getMinecraft().gameSettings.keyBindSneak.isKeyDown(); if(playerMovementInput.jump || playerMovementInput.sneak) { player.movementInput = playerMovementInput; userTookOver = true; } if (playerMovementInput.sneak) { playerMovementInput.moveStrafe = (float)((double) playerMovementInput.moveStrafe * 0.3D); playerMovementInput.moveForward = (float)((double) playerMovementInput.moveForward * 0.3D); player.movementInput = playerMovementInput; userTookOver = true; } // Else let the PlayerBody control movement. if(!userTookOver)player.movementInput = customMovementInput; } } @Override public void jump() { toJump = true; } @Override public void jumpHold() { toJump = true; holdJump = true; } @Override public void jumpRelease() { toJump = false; holdJump = false; jumpTicks = 0; } /** * Sneak reduces player speed to 30% ...! * @see MovementInputFromOptions#updatePlayerMoveState() for movement computation code. */ @Override public void startSneaking() { customMovementInput.sneak = true; customMovementInput.moveStrafe = (float)((double)customMovementInput.moveStrafe*0.3D); customMovementInput.moveForward = (float)((double)customMovementInput.moveForward*0.3D); } /** * Sneak reduces player speed to 30% ...! * @see MovementInputFromOptions#updatePlayerMoveState() for movement computation code. */ @Override public void stopSneaking() { customMovementInput.sneak = false; customMovementInput.moveStrafe = customMovementInput.moveStrafe==0?0:(float)((double)customMovementInput.moveStrafe/0.3D); customMovementInput.moveForward = customMovementInput.moveForward==0?0:(float)((double)customMovementInput.moveForward/0.3D); } /** * The default speed for players is 1 ...! * @see MovementInputFromOptions#updatePlayerMoveState() for movement computation code. * @see MovementInput * @see EntityPlayerSP */ @Override public void moveForward() { if(player.isSneaking())customMovementInput.moveForward = 0.3f; else customMovementInput.moveForward = 1.0f; } /** * The default speed for players is 1 ...! * @see MovementInputFromOptions#updatePlayerMoveState() for movement computation code. * @see MovementInput * @see EntityPlayerSP */ @Override public void moveBackward() { if(player.isSneaking())customMovementInput.moveForward = -0.3f; else customMovementInput.moveForward = -1.0f; } /** * The default speed for players is 1 ...! * @see MovementInputFromOptions#updatePlayerMoveState() for movement computation code. * @see MovementInput * @see EntityPlayerSP */ @Override public void strafeLeft() { if(player.isSneaking())customMovementInput.moveStrafe = 0.3f; else customMovementInput.moveStrafe = 1.0f; } /** * The default speed for players is 1 ...! * @see MovementInputFromOptions#updatePlayerMoveState() for movement computation code. * @see MovementInput * @see EntityPlayerSP */ @Override public void strafeRight() { if(player.isSneaking())customMovementInput.moveStrafe = -0.3f; else customMovementInput.moveStrafe = -1.0f; } /** * The default speed for players is 1 ...! * @see MovementInputFromOptions#updatePlayerMoveState() for movement computation code. * @see MovementInput * @see EntityPlayerSP * * @param front A {@link mod.jd.botapi.Bot.BasicActions.MovementFront} object fo Froward/Backward movement. * @param side A {@link mod.jd.botapi.Bot.BasicActions.MovementSide} object fo Left/Right movement. * @param sneak if true the entity starts sneaking. */ @Override public void setMotion(MovementFront front, MovementSide side, boolean sneak) { customMovementInput.sneak = sneak; if(player.isSneaking())customMovementInput.moveForward = front.val*0.3f; else customMovementInput.moveForward = front.val; if(player.isSneaking())customMovementInput.moveStrafe = side.val*0.3f; else customMovementInput.moveStrafe = side.val; } @Override public void stopMoving() { customMovementInput.moveForward = customMovementInput.moveStrafe = 0; customMovementInput.jump = customMovementInput.sneak = false; } @Override public void lookLeft(double degrees) { if(degrees<0)degrees = 360 - (-degrees - 360 * (int)(-degrees)/360); else if(degrees>360)degrees -= 360 * (int)(degrees/360); toTurnYaw = -degrees; } @Override public void lookRight(double degrees) { if(degrees<0)degrees = 360 - (-degrees - 360 * (int)(-degrees)/360); else if(degrees>360)degrees -= 360 * (int)(degrees/360); toTurnYaw = degrees; } @Override public void lookUp(double degrees) { if(degrees<0)lookDown(degrees); else toTurnPitch = -degrees; } @Override public void lookDown(double degrees) { if(degrees<0)lookUp(degrees); else toTurnPitch = degrees; } @Override public void setTurnSpeed(double turnSpeed) { this.turnSpeed = turnSpeed; } @Override public void turnToPitch(double degree) { toTurnPitch = degree; } @Override public void turnToYaw(double degree) { toTurnYaw=degree; } @Override public void interactItemInHand() { toInteract = true; } @Override public void startInteractItemInHand() { toKeepInteract = true; } @Override public void stopInteractItemInHand() { toKeepInteract = false; } @Override public void interactFacingBlock() { toInteract = true; } @Override public void startBreakingBlock() { keephit = true; } @Override public void stopBreakingBlock() { keephit = false; } @Override public void hit() { toHit = true; } } /** * This class extends {@link KeyBinding} to provide control over its response and simulate key presses via code. * It mainly overrides {@link KeyBinding#isPressed()} and {@link KeyBinding#isKeyDown()} functions. * * NOTE : This class is only to be used on the Client Side. * * @see KeyBinding for the main keyBinding controller class. */ class ControllableKeyBinding extends KeyBinding { public KeyBinding originalKeyBinding; public boolean pressed; public int pressTime; ControllableKeyBinding(KeyBinding k) { super(k.getKeyDescription(),k.getKeyConflictContext(),k.getKeyModifier(),k.getKeyCode(),k.getKeyCategory()); originalKeyBinding = k; } /** * Returns true if the key is pressed fresh down. * */ @Override public boolean isPressed() { if(super.isPressed()) return true; if(pressTime == 0) return false; else { --pressTime; return true; } } /** * Returns true if the key is held down. * */ @Override public boolean isKeyDown() { return pressed || super.isKeyDown(); } public void unpressKey() { this.pressTime = 0; this.pressed = false; } }
package net.darkhax.gamestages; import net.darkhax.bookshelf.BookshelfRegistry; import net.darkhax.bookshelf.command.CommandTree; import net.darkhax.bookshelf.lib.LoggingHelper; import net.darkhax.bookshelf.network.NetworkHandler; import net.darkhax.gamestages.commands.CommandStageTree; import net.darkhax.gamestages.data.GameStageSaveHandler; import net.darkhax.gamestages.packet.PacketSyncClient; import net.darkhax.gamestages.proxy.GameStagesServer; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.relauncher.Side; @Mod(modid = "gamestages", name = "Game Stages", version = "@VERSION@", dependencies = "required-after:bookshelf@[2.2.458,);", certificateFingerprint = "@FINGERPRINT@") public class GameStages { public static final LoggingHelper LOG = new LoggingHelper("gamestages"); public static final NetworkHandler NETWORK = new NetworkHandler("gamestages"); public static final CommandTree COMMAND = new CommandStageTree(); public static final String CLIENT_PROXY_CLASS = "net.darkhax.gamestages.proxy.GameStagesClient"; public static final String SERVER_PROXY_CLASS = "net.darkhax.gamestages.proxy.GameStagesServer"; @SidedProxy(clientSide = GameStages.CLIENT_PROXY_CLASS, serverSide = GameStages.SERVER_PROXY_CLASS) public static GameStagesServer proxy; @EventHandler public void preInit (FMLPreInitializationEvent event) { // Packets NETWORK.register(PacketSyncClient.class, Side.CLIENT); BookshelfRegistry.addCommand(COMMAND); GameStageSaveHandler.reloadFakePlayers(); } }
package net.emaze.dysfunctional; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import net.emaze.dysfunctional.collections.CollectionProvider; import net.emaze.dysfunctional.contracts.dbc; import net.emaze.dysfunctional.dispatching.delegates.ConsumeIntoCollection; import net.emaze.dysfunctional.dispatching.delegates.ConsumeIntoOutputIterator; import net.emaze.dysfunctional.dispatching.delegates.FirstElement; import net.emaze.dysfunctional.dispatching.delegates.LastElement; import net.emaze.dysfunctional.dispatching.delegates.OneElement; import net.emaze.dysfunctional.dispatching.delegates.Provider; import net.emaze.dysfunctional.filtering.AtIndex; import net.emaze.dysfunctional.filtering.FilteringIterator; import net.emaze.dysfunctional.filtering.Nth; import net.emaze.dysfunctional.iterations.ArrayIterator; import net.emaze.dysfunctional.options.Maybe; import net.emaze.dysfunctional.options.MaybeFirstElement; import net.emaze.dysfunctional.options.MaybeLastElement; import net.emaze.dysfunctional.options.MaybeOneElement; import net.emaze.dysfunctional.output.OutputIterator; /** * * @author rferranti */ public abstract class Consumers { /** * Yields all elements of the iterator (in the provided collection). * * @param <R> the returned collection type * @param <E> the collection element type * @param iterator the iterator that will be consumed * @param collection the collection where the iterator is consumed * @return the collection filled with iterator values */ public static <R extends Collection<E>, E> R all(Iterator<E> iterator, R collection) { return new ConsumeIntoCollection<R, E>(new CollectionProvider<R, E>(collection)).perform(iterator); } /** * Yields all elements of the iterator (in the provided collection). * * @param <R> the returned collection type * @param <E> the collection element type * @param iterable the iterable that will be consumed * @param collection the collection where the iterator is consumed * @return the collection filled with iterator values */ public static <R extends Collection<E>, E> R all(Iterable<E> iterable, R collection) { dbc.precondition(iterable != null, "cannot call all with a null iterable"); return Consumers.all(iterable.iterator(), collection); } /** * Yields all elements of the array (in the provided collection). * * @param <R> the returned collection type * @param <E> the collection element type * @param array the array that will be consumed * @param collection the collection where the iterator is consumed * @return the collection filled with iterator values */ public static <R extends Collection<E>, E> R all(E[] array, R collection) { return Consumers.all(new ArrayIterator<E>(array), collection); } public static <E, R extends Collection<E>> R all(Iterator<E> iterator, Provider<R> provider) { return new ConsumeIntoCollection<R, E>(provider).perform(iterator); } public static <E, R extends Collection<E>> R all(Iterable<E> iterable, Provider<R> provider) { dbc.precondition(iterable != null, "cannot call all with a null iterable"); return Consumers.all(iterable.iterator(), provider); } public static <R extends Collection<E>, E> R all(E[] array, Provider<R> provider) { return Consumers.all(new ArrayIterator<E>(array), provider); } /** * yields all elements of the iterator (in a list). * * @param <E> the iterator element type * @param iterator the iterator that will be consumed * @return a list filled with iterator values */ public static <E> List<E> all(Iterator<E> iterator) { return Consumers.all(iterator, new ArrayList<E>()); } /** * Yields all elements of the iterable's iterator (in a list). * * @param <E> the iterable element type * @param iterable the iterable that will be consumed * @return a list filled with iterable values */ public static <E> List<E> all(Iterable<E> iterable) { return Consumers.all(iterable, new ArrayList<E>()); } /** * Yields all element of the array in a list. * * @param <E> the array element type * @param array the array that will be consumed * @return a list filled with array values */ public static <E> List<E> all(E[] array) { return Consumers.all(array, new ArrayList<E>()); } /** * Consumes the input iterator to the output iterator. * * @param <E> the iterator element type * @param iterator the iterator that will be consumed * @param outputIterator the iterator that will be filled */ public static <E> void pipe(Iterator<E> iterator, OutputIterator<E> outputIterator) { new ConsumeIntoOutputIterator<E>(outputIterator).perform(iterator); } /** * Consumes the iterable's input iterator to the output iterator. * * @param <E> the iterator element type * @param iterable the iterable that will be consumed * @param outputIterator the iterator that will be filled */ public static <E> void pipe(Iterable<E> iterable, OutputIterator<E> outputIterator) { dbc.precondition(iterable != null, "cannot call pipe with a null iterable"); pipe(iterable.iterator(), outputIterator); } /** * Consumes the array to the output iterator. * * @param <E> the iterator element type * @param array the array that will be consumed * @param outputIterator the iterator that will be filled */ public static <E> void pipe(E[] array, OutputIterator<E> outputIterator) { pipe(new ArrayIterator<E>(array), outputIterator); } /** * Yields the first element if present, nothing otherwise. * * @param <E> the iterable element type * @param iterable the iterable that will be consumed * @return just the first element or nothing */ public static <E> Maybe<E> maybeFirst(Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call maybeFirst with a null iterable"); return new MaybeFirstElement<E>().perform(iterable.iterator()); } /** * Yields the first element if present, nothing otherwise. * * @param <E> the iterator element type * @param iterator the iterator that will be consumed * @return just the first element or nothing */ public static <E> Maybe<E> maybeFirst(Iterator<E> iterator) { return new MaybeFirstElement<E>().perform(iterator); } /** * Yields the first element if present, nothing otherwise. * * @param <E> the array element type * @param array the array that will be consumed * @return just the first element or nothing */ public static <E> Maybe<E> maybeFirst(E[] array) { return new MaybeFirstElement<E>().perform(new ArrayIterator<E>(array)); } public static <E> E first(Iterator<E> iterator) { return new FirstElement<E>().perform(iterator); } public static <E> E first(Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call first with a null iterable"); return new FirstElement<E>().perform(iterable.iterator()); } public static <E> E first(E[] array) { return new FirstElement<E>().perform(new ArrayIterator<E>(array)); } public static <E> Maybe<E> maybeOne(Iterator<E> iterator) { return new MaybeOneElement<E>().perform(iterator); } public static <E> Maybe<E> maybeOne(Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call maybeOne with a null iterable"); return new MaybeOneElement<E>().perform(iterable.iterator()); } public static <E> Maybe<E> maybeOne(E[] array) { return new MaybeOneElement<E>().perform(new ArrayIterator<E>(array)); } public static <E> E one(Iterator<E> iterator) { return new OneElement<E>().perform(iterator); } public static <E> E one(Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call one with a null iterable"); return new OneElement<E>().perform(iterable.iterator()); } public static <E> E one(E[] array) { return new OneElement<E>().perform(new ArrayIterator<E>(array)); } /** * Yields the last element if present, nothing otherwise. * * @param <E> the iterator element type * @param iterator the iterator that will be consumed * @return the last element or nothing */ public static <E> Maybe<E> maybeLast(Iterator<E> iterator) { return new MaybeLastElement<E>().perform(iterator); } /** * Yields the last element if present, nothing otherwise. * * @param <E> the iterable element type * @param iterable the iterable that will be consumed * @return the last element or nothing */ public static <E> Maybe<E> maybeLast(Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call maybeLast with a null iterable"); return new MaybeLastElement<E>().perform(iterable.iterator()); } /** * Yields the last element if present, nothing otherwise. * * @param <E> the array element type * @param array the array that will be consumed * @return the last element or nothing */ public static <E> Maybe<E> maybeLast(E[] array) { return new MaybeLastElement<E>().perform(new ArrayIterator<E>(array)); } public static <E> E last(Iterator<E> iterator) { return new LastElement<E>().perform(iterator); } public static <E> E last(Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call last with a null iterable"); return new LastElement<E>().perform(iterable.iterator()); } public static <E> E last(E[] array) { return new LastElement<E>().perform(new ArrayIterator<E>(array)); } /** * Yields nth (1-based) element of the iterator. * * @param <E> the iterator element type * @param count the element cardinality * @param iterator the iterator that will be consumed * @return the nth element */ public static <E> E nth(long count, Iterator<E> iterator) { final Iterator<E> filtered = new FilteringIterator<E>(iterator, new Nth<E>(count)); return new FirstElement<E>().perform(filtered); } /** * Yields nth (1-based) element of the iterable. * * @param <E> the iterable element type * @param count the element cardinality * @param iterable the iterable that will be consumed * @return the nth element */ public static <E> E nth(long count, Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call nth with a null iterable"); final Iterator<E> filtered = new FilteringIterator<E>(iterable.iterator(), new Nth<E>(count)); return new FirstElement<E>().perform(filtered); } /** * Yields nth (1-based) element of the array. * * @param <E> the array element type * @param count the element cardinality * @param array the array that will be consumed * @return the nth element */ public static <E> E nth(long count, E[] array) { final Iterator<E> filtered = new FilteringIterator<E>(new ArrayIterator<E>(array), new Nth<E>(count)); return new FirstElement<E>().perform(filtered); } /** * Yields nth (1-based) element of the iterator if found or nothing. * * @param <E> the iterator element type * @param count the element cardinality * @param iterator the iterator that will be consumed * @return just the element or nothing */ public static <E> Maybe<E> maybeNth(long count, Iterator<E> iterator) { final Iterator<E> filtered = new FilteringIterator<E>(iterator, new Nth<E>(count)); return new MaybeFirstElement<E>().perform(filtered); } /** * Yields nth (1-based) element of the iterable if found or nothing. * * @param <E> the iterable element type * @param count the element cardinality * @param iterable the iterable that will be consumed * @return just the element or nothing */ public static <E> Maybe<E> maybeNth(long count, Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call maybeNth with a null iterable"); final Iterator<E> filtered = new FilteringIterator<E>(iterable.iterator(), new Nth<E>(count)); return new MaybeFirstElement<E>().perform(filtered); } /** * Yields nth (1-based) element of the array if found or nothing. * * @param <E> the array element type * @param count the element cardinality * @param array the array that will be consumed * @return just the element or nothing */ public static <E> Maybe<E> maybeNth(long count, E[] array) { final Iterator<E> filtered = new FilteringIterator<E>(new ArrayIterator<E>(array), new Nth<E>(count)); return new MaybeFirstElement<E>().perform(filtered); } /** * Yields element at (0-based) position of the iterator. * * @param <E> the iterator element type * @param index the element index * @param iterator the iterator that will be consumed * @return the element */ public static <E> E at(long index, Iterator<E> iterator) { final Iterator<E> filtered = new FilteringIterator<E>(iterator, new AtIndex<E>(index)); return new FirstElement<E>().perform(filtered); } /** * Yields element at (0-based) position of the iterable. * * @param <E> the iterable element type * @param index the element index * @param iterable the iterable that will be consumed * @return the element */ public static <E> E at(long index, Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call at with a null iterable"); final Iterator<E> filtered = new FilteringIterator<E>(iterable.iterator(), new AtIndex<E>(index)); return new FirstElement<E>().perform(filtered); } /** * Yields element at (0-based) position of the array. * * @param <E> the array element type * @param index the element index * @param array the array that will be consumed * @return just the element or nothing */ public static <E> E at(long index, E[] array) { final Iterator<E> filtered = new FilteringIterator<E>(new ArrayIterator<E>(array), new AtIndex<E>(index)); return new FirstElement<E>().perform(filtered); } /** * Yields element at (0-based) position of the iterator if found or nothing. * * @param <E> the iterator element type * @param index the element index * @param iterator the iterator that will be consumed * @return just the element or nothing */ public static <E> Maybe<E> maybeAt(long index, Iterator<E> iterator) { final Iterator<E> filtered = new FilteringIterator<E>(iterator, new AtIndex<E>(index)); return new MaybeFirstElement<E>().perform(filtered); } /** * Yields element at (0-based) position of the iterable if found or nothing. * * @param <E> the iterable element type * @param index the element index * @param iterable the iterable that will be consumed * @return just the element or nothing */ public static <E> Maybe<E> maybeAt(long index, Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call maybeAt with a null iterable"); final Iterator<E> filtered = new FilteringIterator<E>(iterable.iterator(), new AtIndex<E>(index)); return new MaybeFirstElement<E>().perform(filtered); } /** * Yields element at (0-based) position of the array if found or nothing. * * @param <E> the array element type * @param index the element index * @param array the array that will be consumed * @return just the element or nothing */ public static <E> Maybe<E> maybeAt(long index, E[] array) { final Iterator<E> filtered = new FilteringIterator<E>(new ArrayIterator<E>(array), new AtIndex<E>(index)); return new MaybeFirstElement<E>().perform(filtered); } }
/** * @author ElecEntertainment * @team Larry1123, Joshtmathews, Sinzo, Xalbec * @lastedit Jun 24, 2013 7:59:26 AM */ package net.larry1123.lib.logger; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import net.canarymod.logger.Logman; import net.larry1123.lib.config.UtilConfigManager; public class EELogger extends Logman { private static final HashMap<String, FileHandler> fileHandlers = new HashMap<String, FileHandler>(); private static final HashMap<FileHandler, UtilFilter> fileFilters = new HashMap<FileHandler, UtilFilter>(); /** * Logger to log about Logging ... yea I know */ public static final EELogger log = new EELogger("ElecEntertainmentLogger"); /** * Gets the Path for Log files * * @return */ public static String getLogpath() { return UtilConfigManager.getConfig().getLoggerConfig().getLoggerPath(); } /** * Holds All EELoggers */ private final static HashMap<String, EELogger> loggers = new HashMap<String, EELogger>(); static { log.setParent(Logger.getLogger("Minecraft-Server")); log.setLevel(Level.ALL); File logDir = new File(getLogpath()); if (!logDir.exists()) { logDir.mkdirs(); } } private final static String fileHandlerError = log.addLoggerLevel("ElecEntertainmentLogger", "FileHandler"); /** * Gets the EELogger for the given name * * @param name * Name of the Logger * @return */ public static EELogger getLogger(String name) { if (!loggers.containsKey(name)) { EELogger logman = new EELogger(name); loggers.put(logman.getName(), logman); } return loggers.get(name); } /** * Gets the EELogger for the given name as a sub of the given parent * * @param name * @param parent * @return */ public static EELogger getSubLogger(String name, EELogger parent) { if (!loggers.containsKey(parent.getName() + ":" + name)) { EELogger logman = new EELogger(name, parent); loggers.put(logman.getName(), logman); } return loggers.get(parent.getName() + ":" + name); } /** * This is the path for the log files of this logger */ public final String path; public final String logpath; private EELogger(String name) { super(name); path = getLogpath() + name + "/"; logpath = path + name; createDirectoryFromPath(logpath); try { FileHandler handler = gethandler(logpath + ".log"); UtilFilter filter = fileFilters.get(handler); filter.setLogAll(true); handler.setFilter(filter); } catch (SecurityException e) { EELogger.log.logCustom(EELogger.fileHandlerError, "SecurityException", e); } catch (IOException e) { EELogger.log.logCustom(EELogger.fileHandlerError, "IOException", e); } if (log != null) { setParent(log); } } private EELogger(String name, EELogger parent) { super(parent.getName() + ":" + name); path = parent.path; logpath = path + parent.getName() + ":" + name; createDirectoryFromPath(logpath); try { FileHandler handler = gethandler(logpath + ".log"); UtilFilter filter = fileFilters.get(handler); filter.setLogAll(true); handler.setFilter(filter); } catch (SecurityException e) { EELogger.log.logCustom(EELogger.fileHandlerError, "SecurityException", e); } catch (IOException e) { EELogger.log.logCustom(EELogger.fileHandlerError, "IOException", e); } setParent(parent); } /** * Creates a LoggerLevel for this Logger * * Makes the Log look like this: [{LoggerName}] [{LevelName}] {Message} * * @param levelName * @return */ public String addLoggerLevel(String levelName) { return LoggerLevels.addLoggerLevel(levelName, this); } /** * Creates a LoggerLevel for this Logger with a prefix * * Makes the Log look like this: [{LoggerName}] [{LevelName}] [{Prefix}] {Message} * * @param levelName * @param prefix * @return */ public String addLoggerLevel(String levelName, String prefix) { return LoggerLevels.addLoggerLevel(levelName, prefix, this); } /** * Creates a LoggerLevel for this Logger and saves it to a Log file * * Makes the Log look like this: [{LoggerName}] [{LevelName}] {Message} * * @param levelName * @return */ public String addLoggerLevelWFile(String levelName) { String name = LoggerLevels.addLoggerLevel(levelName, this); createDirectoryFromPath(path); String levelPath = logpath + "." + levelName; try { FileHandler handler = gethandler(levelPath + ".log"); UtilFilter filter = fileFilters.get(handler); filter.addLogLevel(name); handler.setFilter(filter); } catch (SecurityException e) { EELogger.log.logCustom(EELogger.fileHandlerError, "SecurityException", e); } catch (IOException e) { EELogger.log.logCustom(EELogger.fileHandlerError, "IOException", e); } return name; } /** * Creates a LoggerLevel for this Logger with a prefix and saves it to a Log file * * Makes the Log look like this: [{LoggerName}] [{LevelName}] [{Prefix}] {Message} * * @param levelName * @param prefix * @return */ public String addLoggerLevelWFile(String levelName, String prefix) { String name = LoggerLevels.addLoggerLevel(levelName, prefix, this); createDirectoryFromPath(path); String levelPath = logpath + "." + levelName + "-" + prefix; try { FileHandler handler = gethandler(levelPath + ".log"); UtilFilter filter = fileFilters.get(handler); filter.addLogLevel(name); handler.setFilter(filter); } catch (SecurityException e) { EELogger.log.logCustom(EELogger.fileHandlerError, "SecurityException", e); } catch (IOException e) { EELogger.log.logCustom(EELogger.fileHandlerError, "IOException", e); } return name; } private FileHandler gethandler(String pathName) throws SecurityException, IOException { if (!fileHandlers.containsKey(pathName)) { FileHandler handler = new FileHandler(pathName, true); UtilsLogFormat lf = new UtilsLogFormat(); UtilFilter uf = new UtilFilter(); fileFilters.put(handler, uf); handler.setFilter(uf); handler.setLevel(Level.ALL); handler.setFormatter(lf); handler.setEncoding("UTF-8"); this.addHandler(handler); fileHandlers.put(pathName, handler); } return fileHandlers.get(pathName); } /** * Get the LoggerLevel for the given name. * * @param name * @return */ public static LoggerLevel getLoggerLevel(String name) { return LoggerLevels.getLoggerLevel(name); } /** * {@inheritDoc} */ @Override public void log(LogRecord logRecord) { Level level = logRecord.getLevel(); String msg = logRecord.getMessage(); if (level instanceof LoggerLevel) { LoggerLevel handle = (LoggerLevel) level; if (!handle.getPrefix().isEmpty()) { logRecord.setMessage("[" + handle.getPrefix() + "] " + msg); } } super.log(logRecord); } /** * Used to Log a Custom Logger Level * * @param lvl * The LoggerLevel object to use * @param msg * Message to be Logged with Level */ public void logCustom(LoggerLevel lvl, String msg) { log(lvl, msg); } /** * Used to Log a Custom Logger Level with a StackTrace * * @param lvl * The LoggerLevel object to use * @param msg * Message to be Logged with Level * @param thrown * The Throwable Error */ public void logCustom(LoggerLevel lvl, String msg, Throwable thrown) { log(lvl, msg, thrown); } /** * Used to Log a Custom Logger Level * * @param lvl * The name of the LoggerLevel to use * @param msg * Message to be Logged with Level */ public void logCustom(String lvl, String msg) { log(LoggerLevels.getLoggerLevel(lvl), msg); } /** * Used to Log a Custom Logger Level with a StackTrace * * @param lvl * The name of the LoggerLevel to use * @param msg * Message to be Logged with Level * @param thrown * The Throwable Error */ public void logCustom(String lvl, String msg, Throwable thrown) { log(LoggerLevels.getLoggerLevel(lvl), msg, thrown); } /** * TODO Change this to be per Logger * * @param name */ public void removeLoggerLevel(String name) { LoggerLevels.removeLoggerLevel(name); if (fileHandlers.containsKey(name)) { removeHandler(fileHandlers.remove(name)); } } private void createDirectoryFromPath(String path) { File logDir = new File(path.substring(0, path.lastIndexOf('/'))); if (!logDir.exists()) { logDir.mkdirs(); } } }
package net.mloehr.mango.selenium; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import lombok.val; import lombok.extern.slf4j.Slf4j; import net.mloehr.mango.Timer; import net.mloehr.mango.XPathNotFoundException; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.UnhandledAlertException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.interactions.Actions; @Slf4j public class WebUser implements DriveSupport { private static final String MANGO_BROWSER_HEIGHT = "mango.browser-height"; private static final String MANGO_BROWSER_MIN_HEIGHT = "mango.browser-min-height"; private static final String MANGO_BROWSER_WIDTH = "mango.browser-width"; private static final String MANGO_BROWSER_MIN_WIDTH = "mango.browser-min-width"; private static final String MANGO_EXECUTION_DELAY = "mango.execution-delay"; private static final String MANGO_EXECUTION_TRACER = "mango.execution-tracer"; private static final String tracerScript = "arguments[0].style='border: 3px dashed red';"; private static final String scrollIntoViewScript = "arguments[0].scrollIntoView(true);"; private WebDriver driver; private Timer timer; private int executionDelay = 0; private boolean showTracer = false; public WebUser(String url) throws Exception { this(null, url, ""); } public WebUser(String url, String options) throws Exception { this(null, url, options); } public WebUser(WebDriver aDriver, String options) throws Exception { this(aDriver, "", options); } public WebUser(WebDriver aDriver, String url, String options) throws Exception { timer = new Timer(Timer.TIMEOUT_IN_SECONDS); Properties preferences = new Properties(); parseOptions(preferences, options); if (aDriver == null) { driver = new FirefoxDriver( useExtensionsAndAcceptUntrustedCertificates(preferences)); driver.manage().deleteAllCookies(); } else { driver = aDriver; } if (!url.equals("")) { driver.get(url); } handleMangoProperties(preferences); } public String getCurrentUrl() { return driver.getCurrentUrl(); } public void goTo(String url) { driver.get(url); } public void goBack() { driver.navigate().back(); } public void refreshPage() { driver.navigate().refresh(); } public void quit() { driver.quit(); } @Override public Object execute(String script, String xpath) throws Exception { if (xpath == null || xpath.length() == 0) { return ((JavascriptExecutor) driver).executeScript(script); } waitForThis(xpath); if (!currentPageHas(xpath)) { throw new XPathNotFoundException(xpath); } val element = driver.findElement(By.xpath(xpath)); return ((JavascriptExecutor) driver).executeScript(script, element); } @Override public WebElement forThis(String xpath) throws Exception { waitForThis(xpath); if (currentPageHas(xpath)) { val element = driver.findElement(By.xpath(xpath)); executeJavaScript(element); return element; } throw new XPathNotFoundException(xpath); } public List<WebElement> forThese(String xpath) throws Exception { return forThese(xpath, true); } @Override public List<WebElement> forThese(String xpath, boolean wait) throws Exception { if (wait) { waitForThis(xpath); } if (currentPageHas(xpath)) { val elements = driver.findElements(By.xpath(xpath)); executeJavaScript(elements); return elements; } throw new XPathNotFoundException(xpath); } public void pause() { Timer.waitFor(executionDelay); } /* * (non-Javadoc) * * @see net.mloehr.mango.selenium.DriveSupport#getActions() */ public Actions getActions() { return new Actions(driver); } private void waitForThis(String xpath) { timer.reset(); while (timer.isNotExpired()) { if (currentPageHas(xpath)) { return; } else { Timer.waitFor(Timer.MILLISECONDS_BETWEEN_ELEMENT_CHECK); } } log.warn("Time-out after {} seconds for xpath {}", timer.getTimeOut(), xpath); } private void executeJavaScript(List<WebElement> elements) { for (val element : elements) { executeJavaScript(element); } } private void executeJavaScript(final org.openqa.selenium.WebElement element) { ((JavascriptExecutor) driver).executeScript(scrollIntoViewScript, element); if (showTracer) { ((JavascriptExecutor) driver).executeScript(tracerScript, element); } } private void handleMangoProperties(Properties preferences) { Dimension browserSize = driver.manage().window().getSize(); int browserWidth = browserSize.width; int browserHeight = browserSize.height; JavascriptExecutor js = (JavascriptExecutor) driver; int screenWidth = ((Long) js.executeScript("return screen.width")) .intValue(); int screenHeight = ((Long) js.executeScript("return screen.height")) .intValue(); if (preferences.containsKey(MANGO_BROWSER_HEIGHT)) { int requestedHeigth = Integer.valueOf( preferences.getProperty(MANGO_BROWSER_HEIGHT)).intValue(); if (requestedHeigth <= screenHeight) { browserHeight = requestedHeigth; } } if (preferences.containsKey(MANGO_BROWSER_MIN_HEIGHT)) { int requestedHeigth = Integer.valueOf( preferences.getProperty(MANGO_BROWSER_MIN_HEIGHT)) .intValue(); if (requestedHeigth > browserHeight) { browserHeight = requestedHeigth; } } if (preferences.containsKey(MANGO_BROWSER_WIDTH)) { int requestedWidth = Integer.valueOf( preferences.getProperty(MANGO_BROWSER_WIDTH)).intValue(); if (requestedWidth <= screenWidth) { browserWidth = requestedWidth; } } if (preferences.containsKey(MANGO_BROWSER_MIN_WIDTH)) { int requestedWidth = Integer.valueOf( preferences.getProperty(MANGO_BROWSER_MIN_WIDTH)) .intValue(); if (requestedWidth > browserWidth) { browserWidth = requestedWidth; } } val dim = new Dimension(browserWidth, browserHeight); driver.manage().window().setSize(dim); if (preferences.containsKey(MANGO_EXECUTION_DELAY)) { executionDelay = Integer.valueOf( preferences.getProperty(MANGO_EXECUTION_DELAY)).intValue(); } if (preferences.containsKey(MANGO_EXECUTION_TRACER)) { showTracer = Boolean.valueOf(preferences .getProperty(MANGO_EXECUTION_TRACER)); } } private void parseOptions(Properties preferences, String options) { if (options != null && options != "") { for (val entry : options.split(";")) { val pair = entry.split("="); preferences.setProperty(pair[0], pair[1]); } } } private boolean currentPageHas(String xpath) { try { driver.findElement(By.xpath(xpath)); return true; } catch (NoSuchElementException e) { return false; } catch (UnhandledAlertException e) { log.warn("Ignored alert: " + e.getAlertText()); return false; } } private FirefoxProfile useExtensionsAndAcceptUntrustedCertificates( Properties preferences) { FirefoxProfile profile = new FirefoxProfile(); addExtensions(profile, preferences); for (val pref : preferences.entrySet()) { profile.setPreference(pref.getKey().toString(), pref.getValue() .toString()); } profile.setAcceptUntrustedCertificates(true); return profile; } private void addExtensions(FirefoxProfile profile, Properties preferences) { File resources = new File("./resources"); String[] files = resources.list(); if (files == null) { log.debug("no extensions found"); return; } for (String file : files) { if (!file.endsWith(".xpi")) { continue; } val extension = new File(resources + "/" + file); String[] parsed = parseNameAndVersion(extension).split(";"); final String name = parsed[0]; final String version = parsed[1]; try { profile.addExtension(extension); preferences.setProperty("extensions." + name + ".currentVersion", version); log.debug("added extension {} {}", name, version); } catch (IOException e) { log.debug("adding extension {}, unexpected: {}", name, e); } } } private String parseNameAndVersion(File file) { String result = ""; Pattern pattern = Pattern.compile("(\\w+)-([\\d\\.]+)-*\\w*\\.xpi"); Matcher matcher = pattern.matcher(file.getName()); if (matcher.find()) { result = matcher.group(1) + ";" + matcher.group(2); } return result; } }
package net.spy.memcached; import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.apache.http.HttpRequest; import org.apache.http.HttpVersion; import org.apache.http.message.BasicHttpRequest; import net.spy.memcached.internal.HttpFuture; import net.spy.memcached.internal.ViewFuture; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.protocol.couch.DocsOperation.DocsCallback; import net.spy.memcached.protocol.couch.DocsOperationImpl; import net.spy.memcached.protocol.couch.HttpOperation; import net.spy.memcached.protocol.couch.NoDocsOperation; import net.spy.memcached.protocol.couch.NoDocsOperationImpl; import net.spy.memcached.protocol.couch.Query; import net.spy.memcached.protocol.couch.ReducedOperation.ReducedCallback; import net.spy.memcached.protocol.couch.ReducedOperationImpl; import net.spy.memcached.protocol.couch.RowWithDocs; import net.spy.memcached.protocol.couch.View; import net.spy.memcached.protocol.couch.ViewOperation.ViewCallback; import net.spy.memcached.protocol.couch.ViewOperationImpl; import net.spy.memcached.protocol.couch.ViewsOperation.ViewsCallback; import net.spy.memcached.protocol.couch.ViewsOperationImpl; import net.spy.memcached.protocol.couch.ViewResponseNoDocs; import net.spy.memcached.protocol.couch.ViewResponseReduced; import net.spy.memcached.protocol.couch.ViewResponseWithDocs; import net.spy.memcached.vbucket.ConfigurationException; import net.spy.memcached.vbucket.config.Bucket; public class CouchbaseClient extends MembaseClient implements CouchbaseClientIF { private static final String MODE_PRODUCTION = "production"; private static final String MODE_DEVELOPMENT = "development"; private static final String DEV_PREFIX = "dev_"; private static final String PROD_PREFIX = ""; public static final String MODE_PREFIX; private static final String MODE_ERROR; private CouchbaseConnection cconn; private final String bucketName; static { String viewmode = null; boolean propsFileExists; try { Properties properties = new Properties(); properties.load(new FileInputStream("config.properties")); viewmode = properties.getProperty("viewmode"); propsFileExists = true; } catch (IOException e) { propsFileExists = false; } if (!propsFileExists) { MODE_ERROR = "Can't find config.properties. Setting viewmode " + "to development mode"; MODE_PREFIX = DEV_PREFIX; } else if (viewmode == null) { MODE_ERROR = "viewmode doesn't exist in config.properties. " + "Setting viewmode to development mode"; MODE_PREFIX = DEV_PREFIX; } else if (viewmode.equals(MODE_PRODUCTION)) { MODE_ERROR = "viewmode set to production mode"; MODE_PREFIX = PROD_PREFIX; } else if (viewmode.equals(MODE_DEVELOPMENT)){ MODE_ERROR = "viewmode set to development mode"; MODE_PREFIX = DEV_PREFIX; } else { MODE_ERROR = "unknown value \"" + viewmode + "\" for property viewmode"; MODE_PREFIX = DEV_PREFIX; } } public CouchbaseClient(List<URI> baseList, String bucketName, String pwd) throws IOException, ConfigurationException { this(baseList, bucketName, bucketName, pwd); } public CouchbaseClient(List<URI> baseList, String bucketName, String usr, String pwd) throws IOException, ConfigurationException { super(new CouchbaseConnectionFactory(baseList, bucketName, usr, pwd), false); this.bucketName = bucketName; CouchbaseConnectionFactory cf = (CouchbaseConnectionFactory)connFactory; List<InetSocketAddress> addrs = AddrUtil.getAddresses(cf.getVBucketConfig().getServers()); List<InetSocketAddress> conv = new LinkedList<InetSocketAddress>(); while (!addrs.isEmpty()) { conv.add(addrs.remove(0)); } while (!conv.isEmpty()) { addrs.add(new InetSocketAddress(conv.remove(0).getHostName(), 5984)); } getLogger().info(MODE_ERROR); cconn = cf.createCouchDBConnection(addrs); cf.getConfigurationProvider().subscribe(cf.getBucket(), this); } /** * Gets a view contained in a design document from the cluster. * * @param designDocumentName the name of the design document. * @param viewName the name of the view to get. * @return a View object from the cluster. * @throws InterruptedException if the operation is interrupted while in flight * @throws ExecutionException if an error occurs during execution */ public HttpFuture<View> asyncGetView(String designDocumentName, final String viewName) { designDocumentName = MODE_PREFIX + designDocumentName; String uri = "/" + bucketName + "/_design/" + designDocumentName; final CountDownLatch couchLatch = new CountDownLatch(1); final HttpFuture<View> crv = new HttpFuture<View>(couchLatch, 60000); final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); final HttpOperation op = new ViewOperationImpl(request, bucketName, designDocumentName, viewName, new ViewCallback() { View view = null; @Override public void receivedStatus(OperationStatus status) { crv.set(view, status); } @Override public void complete() { couchLatch.countDown(); } @Override public void gotData(View v) { view = v; } }); crv.setOperation(op); addOp(op); return crv; } /** * Gets a future with a list of views for a given design document from the cluster. * * @param designDocumentName the name of the design document. * @return a future containing a List of View objects from the cluster. */ public HttpFuture<List<View>> asyncGetViews(String designDocumentName) { designDocumentName = MODE_PREFIX + designDocumentName; String uri = "/" + bucketName + "/_design/" + designDocumentName; final CountDownLatch couchLatch = new CountDownLatch(1); final HttpFuture<List<View>> crv = new HttpFuture<List<View>>(couchLatch, 60000); final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); final HttpOperation op = new ViewsOperationImpl(request, bucketName, designDocumentName, new ViewsCallback() { List<View> views = null; @Override public void receivedStatus(OperationStatus status) { crv.set(views, status); } @Override public void complete() { couchLatch.countDown(); } @Override public void gotData(List<View> v) { views = v; } }); crv.setOperation(op); addOp(op); return crv; } /** * Gets a view contained in a design document from the cluster. * * @param designDocumentName the name of the design document. * @param viewName the name of the view to get. * @return a View object from the cluster. */ public View getView(final String designDocumentName, final String viewName) { try { return asyncGetView(designDocumentName, viewName).get(); }catch (InterruptedException e) { throw new RuntimeException("Interrupted getting views", e); } catch (ExecutionException e) { throw new RuntimeException("Failed getting views", e); } } /** * Gets a list of views for a given design document from the cluster. * * @param designDocumentName the name of the design document. * @return a list of View objects from the cluster. */ public List<View> getViews(final String designDocumentName) { try { return asyncGetViews(designDocumentName).get(); }catch (InterruptedException e) { throw new RuntimeException("Interrupted getting views", e); } catch (ExecutionException e) { throw new RuntimeException("Failed getting views", e); } } /** * Queries a Couchbase view by calling its map function. This type * of query will return the view result along with all of the * documents for each row in the query. * * @param view the view to run the query against. * @param query the type of query to run against the view. * @return a Future containing the results of the query. */ public ViewFuture query(View view, Query query) { String queryString = query.toString(); String params = (queryString.length() > 0) ? "&reduce=false" : "?reduce=false"; String uri = view.getURI() + queryString + params; final CountDownLatch couchLatch = new CountDownLatch(1); final ViewFuture crv = new ViewFuture(couchLatch, 60000); final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); final HttpOperation op = new DocsOperationImpl(request, new DocsCallback() { ViewResponseWithDocs vr = null; @Override public void receivedStatus(OperationStatus status) { Collection<String> ids = new LinkedList<String>(); Iterator<RowWithDocs> itr = vr.iterator(); while (itr.hasNext()) { ids.add(itr.next().getId()); } crv.set(vr, asyncGetBulk(ids), status); } @Override public void complete() { couchLatch.countDown(); } @Override public void gotData(ViewResponseWithDocs response) { vr = response; } }); crv.setOperation(op); addOp(op); return crv; } /** * Queries a Couchbase view by calling it's map function. This type * of query will return the view result but will not get the * documents associated with each row of the query. * * @param view the view to run the query against. * @param query the type of query to run against the view. * @return a Future containing the results of the query. */ public HttpFuture<ViewResponseNoDocs> queryAndExcludeDocs(View view, Query query) { String queryString = query.toString(); String params = (queryString.length() > 0) ? "&reduce=false" : "?reduce=false"; params += "&include_docs=false"; String uri = view.getURI() + queryString + params; final CountDownLatch couchLatch = new CountDownLatch(1); final HttpFuture<ViewResponseNoDocs> crv = new HttpFuture<ViewResponseNoDocs>(couchLatch, 60000); final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); final HttpOperation op = new NoDocsOperationImpl(request, new NoDocsOperation.NoDocsCallback() { ViewResponseNoDocs vr = null; @Override public void receivedStatus(OperationStatus status) { crv.set(vr, status); } @Override public void complete() { couchLatch.countDown(); } @Override public void gotData(ViewResponseNoDocs response) { vr = response; } }); crv.setOperation(op); addOp(op); return crv; } /** * Queries a Couchbase view by calling it's map function and then * the views reduce function. * * @param view the view to run the query against. * @param query the type of query to run against the view. * @return a Future containing the results of the query. */ public HttpFuture<ViewResponseReduced> queryAndReduce(final View view, final Query query){ if (!view.hasReduce()) { throw new RuntimeException("This view doesn't contain a reduce function"); } String uri = view.getURI() + query.toString(); final CountDownLatch couchLatch = new CountDownLatch(1); final HttpFuture<ViewResponseReduced> crv = new HttpFuture<ViewResponseReduced>(couchLatch, 60000); final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); final HttpOperation op = new ReducedOperationImpl(request, new ReducedCallback() { ViewResponseReduced vr = null; @Override public void receivedStatus(OperationStatus status) { crv.set(vr, status); } @Override public void complete() { couchLatch.countDown(); } @Override public void gotData(ViewResponseReduced response) { vr = response; } }); crv.setOperation(op); addOp(op); return crv; } /** * Adds an operation to the queue where it waits to be sent to * Couchbase. This function is for internal use only. */ public void addOp(final HttpOperation op) { cconn.checkState(); cconn.addOp(op); } /** * This function is called when there is a topology change in the * cluster. This function is intended for internal use only. */ @Override public void reconfigure(Bucket bucket) { reconfiguring = true; try { mconn.reconfigure(bucket); cconn.reconfigure(bucket); } catch (IllegalArgumentException ex) { getLogger().warn("Failed to reconfigure client, staying with previous configuration.", ex); } finally { reconfiguring = false; } } /** * Shuts down the client immediately. */ @Override public void shutdown() { shutdown(-1, TimeUnit.MILLISECONDS); } /** * Shut down this client gracefully. * * @param duration the amount of time time for shutdown * @param units the TimeUnit for the timeout * @return result of the shutdown request */ @Override public boolean shutdown(long duration, TimeUnit units) { try { return super.shutdown(duration, units) && cconn.shutdown(); } catch (IOException e) { getLogger().error("Error shutting down CouchbaseClient"); return false; } } }
package net.ucanaccess.converters; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLSyntaxErrorException; import java.sql.SQLWarning; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hsqldb.error.ErrorCode; import net.ucanaccess.complex.ComplexBase; import net.ucanaccess.converters.TypesMap.AccessType; import net.ucanaccess.ext.FunctionType; import net.ucanaccess.jdbc.DBReference; import net.ucanaccess.jdbc.UcanaccessSQLException; import net.ucanaccess.util.Logger; import net.ucanaccess.util.Logger.Messages; import com.healthmarketscience.jackcess.Column; import com.healthmarketscience.jackcess.DataType; import com.healthmarketscience.jackcess.Database; import com.healthmarketscience.jackcess.Index; import com.healthmarketscience.jackcess.PropertyMap; import com.healthmarketscience.jackcess.Row; import com.healthmarketscience.jackcess.Table; import com.healthmarketscience.jackcess.Database.FileFormat; import com.healthmarketscience.jackcess.PropertyMap.Property; import com.healthmarketscience.jackcess.complex.ComplexValueForeignKey; import com.healthmarketscience.jackcess.impl.IndexData; import com.healthmarketscience.jackcess.impl.IndexImpl; import com.healthmarketscience.jackcess.query.Query; public class LoadJet { private static int namingCounter = 0; private final class FunctionsLoader { private HashSet<String> functionsDefinition = new HashSet<String>(); private void addAggregates() { functionsDefinition.add(getAggregate("LONGVARCHAR", "last")); functionsDefinition.add(getAggregate("DECIMAL(100,10)", "last")); functionsDefinition.add(getAggregate("BOOLEAN", "last")); functionsDefinition.add(getAggregate("TIMESTAMP", "last")); functionsDefinition.add(getAggregate("LONGVARCHAR", "first")); functionsDefinition.add(getAggregate("DECIMAL(100,10)", "first")); functionsDefinition.add(getAggregate("BOOLEAN", "first")); functionsDefinition.add(getAggregate("TIMESTAMP", "first")); } private void addFunction(String functionName, String methodName, String returnType, String... parTypes) { StringBuffer funDef = new StringBuffer(); if (DBReference.is2xx()) { funDef.append("CREATE FUNCTION ").append(functionName) .append("("); String comma = ""; for (int i = 0; i < parTypes.length; i++) { funDef.append(comma).append("par").append(i).append(" ") .append(parTypes[i]); comma = ","; } funDef.append(")"); funDef.append(" RETURNS "); funDef.append(returnType); funDef.append(" LANGUAGE JAVA DETERMINISTIC NO SQL EXTERNAL NAME 'CLASSPATH:"); funDef.append(methodName).append("'"); } else { funDef.append("CREATE ALIAS ").append(functionName) .append(" FOR \"").append(methodName).append("\""); } functionsDefinition.add(funDef.toString()); } private void addFunctions(Class<?> clazz) throws SQLException { Method[] mths = clazz.getDeclaredMethods(); HashMap<String, String> tmap = TypesMap.getAccess2HsqlTypesMap(); for (Method mth : mths) { Annotation[] ants = mth.getAnnotations(); for (Annotation ant : ants) { if (ant.annotationType().equals(FunctionType.class)) { FunctionType ft = (FunctionType) ant; String methodName = clazz.getName() + "." + mth.getName(); String functionName = ft.functionName(); if (functionName == null) functionName = methodName; AccessType[] acts = ft.argumentTypes(); AccessType ret = ft.returnType(); String retTypeName = ret.name(); String returnType = tmap.containsKey(retTypeName) ? tmap .get(retTypeName) : retTypeName; if (AccessType.TEXT.equals(ret)) { returnType += "(255)"; } String[] args = new String[acts.length]; for (int i = 0; i < args.length; i++) { String typeName = acts[i].name(); args[i] = tmap.containsKey(typeName) ? tmap .get(typeName) : typeName; if (AccessType.TEXT.equals(acts[i])) { args[i] += "(255)"; } } if (ft.namingConflict()) { SQLConverter.addWAFunctionName(functionName); functionName += "WA"; } addFunction(functionName, methodName, returnType, args); } } } createFunctions(); } private void createFunctions() throws SQLException { for (String functionDef : functionsDefinition) { execCreate(functionDef,true); } functionsDefinition.clear(); } private String getAggregate(String type, String fun) { String createLast = "CREATE AGGREGATE FUNCTION " + fun + "(IN val " + type + ", IN flag BOOLEAN, INOUT register " + type + ", INOUT counter INT) " + " RETURNS " + type + " NO SQL LANGUAGE JAVA " + " EXTERNAL NAME 'CLASSPATH:net.ucanaccess.converters.FunctionsAggregate." + fun + "'"; return createLast; } private void loadMappedFunctions() throws SQLException { addFunctions(Functions.class); addAggregates(); createFunctions(); } } private final class LogsFlusher { private void dumpList(List<String> logs) { dumpList(logs, false); } private void dumpList(List<String> logs, boolean cr) { String comma = ""; StringBuffer sb = new StringBuffer(); String crs = cr ? System.getProperty("line.separator") : ""; for (String log : logs) { sb.append(comma).append(log).append(crs); comma = ", "; } Logger.log(sb.toString()); logs.clear(); } } private final class TablesLoader { private static final int HSQL_FK_ALREADY_EXISTS = -ErrorCode.X_42528; // -5528; private static final int HSQL_UK_ALREADY_EXISTS= -ErrorCode.X_42522;//-5522 private static final String SYSTEM_SCHEMA = "SYS"; private ArrayList<String> unresolvedTables = new ArrayList<String>(); private ArrayList<String> calculatedFieldsTriggers=new ArrayList<String>(); private LinkedList<String> loadingOrder=new LinkedList<String>(); private HashSet<Column> alreadyIndexed=new HashSet<Column>(); private String commaSeparated(List<? extends Index.Column> columns) { String comma = ""; StringBuffer sb = new StringBuffer(" ("); for (Index.Column cd : columns) { sb.append(comma) .append(SQLConverter.escapeIdentifier(cd.getColumn() .getName())); comma = ","; } return sb.append(") ").toString(); } private String schema(String name,boolean systemTable){ if(systemTable){ return SYSTEM_SCHEMA+"."+name; } return name; } private DataType getReturnType(Column cl) throws IOException{ if(cl.getProperties().get( PropertyMap.EXPRESSION_PROP)==null||cl.getProperties().get(PropertyMap.RESULT_TYPE_PROP)==null) return null; byte pos=(Byte) cl.getProperties().get(PropertyMap.RESULT_TYPE_PROP).getValue(); return DataType.fromByte(pos); } private String getHsqldbColumnType(Column cl) throws IOException{ String htype ; DataType dtyp=cl.getType(); DataType rtyp= getReturnType( cl); boolean calcType=false; if( rtyp!=null){ dtyp=rtyp; calcType=true; } if( dtyp.equals(DataType.TEXT)){ int ln=ff1997?cl.getLength():cl.getLengthInUnits(); htype="VARCHAR(" + ln + ")" ; } else if(dtyp.equals(DataType.NUMERIC)&&(cl.getScale()>0||calcType)){ if(calcType){ htype="NUMERIC(100 ,4)"; } else{ htype="NUMERIC("+ (cl.getPrecision()>0?cl.getPrecision():100)+","+ cl.getScale()+")"; } } else if(dtyp.equals(DataType.FLOAT)&&calcType){ htype="NUMERIC("+ (cl.getPrecision()>0?cl.getPrecision():100)+","+ 4+")"; } else{ htype=TypesMap.map2hsqldb(dtyp); } return htype; } private String getCalculatedFieldTrigger(String ntn,Column cl,boolean isCreate) throws IOException{ DataType dt=getReturnType(cl); String fun=null; if(isNumeric(dt)){ fun="formulaToNumeric"; }else if(isBoolean(dt)){ fun="formulaToBoolean"; }else if(isDate(dt)){ fun="formulaToDate"; }else if(isTextual(dt)){ fun="formulaToText"; } String call= fun==null?"%s":fun+"(%s,'"+dt.name()+"')"; String trg=isCreate? "CREATE TRIGGER expr%d after insert ON "+ntn+ " REFERENCING NEW AS newrow FOR EACH ROW "+ " BEGIN ATOMIC "+ " SET newrow."+SQLConverter.escapeIdentifier(cl.getName())+" = "+call+ "; END " : "CREATE TRIGGER expr%d after update ON "+ntn+ " REFERENCING NEW AS newrow OLD AS OLDROW FOR EACH ROW "+ " BEGIN ATOMIC IF %s THEN "+ " SET newrow."+SQLConverter.escapeIdentifier(cl.getName())+" = "+call+ "; ELSEIF newrow."+SQLConverter.escapeIdentifier(cl.getName())+" <> oldrow."+SQLConverter.escapeIdentifier(cl.getName()) +" THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '"+Logger.getMessage(Messages.TRIGGER_UPDATE_CF_ERR.name())+cl.getName()+"'" +"; END IF ; END "; return trg; } private boolean isNumeric(DataType dt){ return typeGroup(dt,DataType.NUMERIC,DataType.MONEY,DataType.DOUBLE,DataType.FLOAT,DataType.LONG,DataType.INT,DataType.BYTE); } private boolean isDate(DataType dt){ return typeGroup(dt,DataType.SHORT_DATE_TIME); } private boolean isBoolean(DataType dt){ return typeGroup(dt,DataType.BOOLEAN); } private boolean isTextual(DataType dt){ return typeGroup(dt,DataType.MEMO,DataType.TEXT); } private boolean typeGroup(DataType dt,DataType...gr){ for(DataType el:gr){ if(el.equals(dt))return true; } return false; } private void createSyncrTable(Table t,boolean systemTable) throws SQLException, IOException { String tn = t.getName(); String ntn =schema( SQLConverter.escapeIdentifier(tn),systemTable); StringBuffer sbC = new StringBuffer("CREATE CACHED TABLE ").append( ntn).append("("); List<? extends Column> lc = t.getColumns(); String comma = ""; for (Column cl : lc) { if("USER".equalsIgnoreCase(cl.getName())){ Logger.logParametricWarning(Messages.USER_AS_COLUMNNAME,t.getName()); } String expr=getExpression(cl); if(expr!=null){ String tgrI=getCalculatedFieldTrigger(ntn,cl,true); String tgrU=getCalculatedFieldTrigger(ntn,cl,false); calculatedFieldsTriggers.add(String.format(tgrI,namingCounter++,SQLConverter.convertFormula(expr))); String uc=getUpdateConditions(cl); if(uc.length()>0){ calculatedFieldsTriggers.add(String.format(tgrU,namingCounter++,uc,SQLConverter.convertFormula(expr))); } } String htype= getHsqldbColumnType(cl) ; sbC.append(comma) .append(SQLConverter.escapeIdentifier(cl.getName())) .append(" ").append(htype); PropertyMap pm = cl.getProperties(); Object required = pm.getValue(PropertyMap.REQUIRED_PROP); if (required != null&& required instanceof Boolean && ((Boolean) required) ) { sbC.append(" NOT NULL "); } comma = ","; } sbC.append(")"); execCreate(sbC.toString(),true); } private String getExpression(Column cl) throws IOException { PropertyMap map=cl.getProperties(); Property exprp=map.get( PropertyMap.EXPRESSION_PROP); if(exprp!=null){ Table tl=cl.getTable(); String expr= SQLConverter.convertPowOperator((String)exprp.getValue()); for(Column cl1:tl.getColumns()){ expr=expr.replaceAll("\\[(?i)("+Pattern.quote(cl1.getName())+")\\]","newrow.$0"); } return expr; } return null; } private String getUpdateConditions(Column cl) throws IOException { PropertyMap map=cl.getProperties(); Property exprp=map.get( PropertyMap.EXPRESSION_PROP); if(exprp!=null){ Set<String> setu=SQLConverter.getFormulaDependencies(exprp.getValue().toString()); if(setu.size()>0){ String or=""; StringBuffer cw=new StringBuffer(); for(String dep:setu){ cw.append(or). append("oldrow.").append(dep).append("<>").append("newrow.").append(dep); or=" OR "; } return cw.toString(); } } return " FALSE "; } private void defaultValues(Table t) throws SQLException, IOException { String tn = t.getName(); String ntn = SQLConverter.escapeIdentifier(tn); List<? extends Column> lc = t.getColumns(); ArrayList<String> arTrigger = new ArrayList<String>(); for (Column cl : lc) { PropertyMap pm = cl.getProperties(); String ncn = SQLConverter.escapeIdentifier(cl.getName()); Object defaulT = pm.getValue(PropertyMap.DEFAULT_VALUE_PROP); if (defaulT != null) { String cdefaulT = SQLConverter.convertSQL(" " + defaulT.toString()); if (cdefaulT.trim().startsWith("=")) { cdefaulT = cdefaulT.trim().substring(1); } if (cl.getType().equals(DataType.BOOLEAN) && ("=yes".equalsIgnoreCase(cdefaulT) || "yes" .equalsIgnoreCase(cdefaulT))) cdefaulT = "true"; if (cl.getType().equals(DataType.BOOLEAN) && ("=no".equalsIgnoreCase(cdefaulT) || "no" .equalsIgnoreCase(cdefaulT))) cdefaulT = "false"; if( (cl.getType().equals(DataType.MEMO)|| cl.getType().equals(DataType.TEXT))&& (!defaulT.toString().startsWith("\"")|| !defaulT.toString().endsWith("\"") ) ){ cdefaulT="'"+cdefaulT.replaceAll("'","''")+"'"; } String guidExp = "GenGUID()"; if (!guidExp.equals(defaulT)) { if (!tryDefault(cdefaulT)) { Logger.logParametricWarning(Messages.UNKNOWN_EXPRESSION, ""+ defaulT, cl.getName(), cl.getTable().getName()); } else { if(cl.getType()==DataType.TEXT && defaulT.toString().startsWith("'")&&defaulT.toString().endsWith("'")&& defaulT.toString().length()>cl.getLengthInUnits() ){ Logger.logParametricWarning(Messages.DEFAULT_VALUES_DELIMETERS, ""+defaulT,cl.getName(),cl.getTable().getName(),""+cl.getLengthInUnits()); } arTrigger .add("CREATE TRIGGER DEFAULT_TRIGGER" + (namingCounter++) + " BEFORE INSERT ON " + ntn + " REFERENCING NEW ROW AS NEW FOR EACH ROW IF NEW." + ncn + " IS NULL THEN " + "SET NEW." + ncn + "= " + cdefaulT + " ; END IF"); } } } } for (String trigger : arTrigger) { execCreate(trigger,true); } } private int countFKs() throws IOException{ int i=0; for (String tn : this.loadingOrder) { Table table = dbIO.getTable(tn); if (!this.unresolvedTables.contains(tn)) { for (Index idxi : table.getIndexes()) { // riw IndexImpl idx = (IndexImpl) idxi; if (idx.isForeignKey() && !idx.getReference().isPrimaryTable()) i++; } } } return i; } private boolean reorder() throws IOException, SQLException { int maxIteration=countFKs()+1; for (int i = 0; i < maxIteration; i++) { boolean change = false; ArrayList<String> loadingOrder0=new ArrayList<String>(); loadingOrder0.addAll(this.loadingOrder); for (String tn : loadingOrder0) { Table table = dbIO.getTable(tn); if (!this.unresolvedTables.contains(tn)) { for (Index idxi : table.getIndexes()) { // riw IndexImpl idx = (IndexImpl) idxi; if (idx.isForeignKey() && !idx.getReference().isPrimaryTable()&&!tryReorder(idx)) change = true; } } } if(!change )return true; } return false; } private boolean tryReorder(Index idxi) throws IOException{ IndexImpl idx=(IndexImpl)idxi; String ctn=idx.getTable().getName(); String rtn=idx.getReferencedIndex().getTable().getName(); int ict=this.loadingOrder.indexOf(ctn); int irt=this.loadingOrder.indexOf(rtn); if(ict<irt){ this.loadingOrder.remove(ctn); this.loadingOrder.add(irt, ctn); return false; } return true; } private void loadForeignKey(Index idxi) throws IOException, SQLException { IndexImpl idx=(IndexImpl)idxi; String ctn=idx.getTable().getName(); String rtn=idx.getReferencedIndex().getTable().getName(); List<IndexData.ColumnDescriptor> cls=idx.getColumns(); if(cls.size()==1){ this.alreadyIndexed.add(cls.get(0).getColumn()); } String ntn = SQLConverter .escapeIdentifier(ctn); if(ntn==null)return; String nin = SQLConverter.escapeIdentifier(idx.getName()); nin = (ntn + "_" + nin).replaceAll("\"", "").replaceAll("\\W", "_"); String colsIdx = commaSeparated(cls); String colsIdxRef = commaSeparated(idx.getReferencedIndex() .getColumns()); StringBuffer ci = new StringBuffer("ALTER TABLE ").append(ntn); ci.append(" ADD CONSTRAINT ").append(nin); String nrt = SQLConverter.escapeIdentifier(rtn); if(nrt==null)return; ci.append(" FOREIGN KEY ").append(colsIdx).append(" REFERENCES ") .append(nrt).append(colsIdxRef); if (idx.getReference().isCascadeDeletes()) { ci.append(" ON DELETE CASCADE "); } if (idx.getReference().isCascadeUpdates()) { ci.append(" ON UPDATE CASCADE "); } try { execCreate(ci.toString(),true); } catch (SQLException e) { if (e.getErrorCode() == HSQL_FK_ALREADY_EXISTS) { Logger.log(e.getMessage()); } else throw e; } loadedIndexes.add("FK on " + ntn + " Columns:" + colsIdx + " References " + nrt + " Columns:" + colsIdxRef); } private void loadIndex(Index idx) throws IOException, SQLException { String ntn = SQLConverter .escapeIdentifier(idx.getTable().getName()); if(ntn==null)return; String nin = SQLConverter.escapeIdentifier(idx.getName()); nin = (ntn + "_" + nin).replaceAll("\"", "").replaceAll("\\W", "_"); boolean uk = idx.isUnique(); boolean pk = idx.isPrimaryKey(); if(!uk&&!pk&&idx.getColumns().size()==1){ Column cl=idx.getColumns().get(0).getColumn(); if(this.alreadyIndexed.contains(cl)) return; } if(uk&&idx.getColumns().size()==1){ Column cl=idx.getColumns().get(0).getColumn(); DataType dt=cl.getType(); if(dt.equals(DataType.COMPLEX_TYPE))return; } StringBuffer ci = new StringBuffer("ALTER TABLE ").append(ntn); String colsIdx = commaSeparated(idx.getColumns()); if (pk) { ci.append(" ADD PRIMARY KEY ").append(colsIdx); } else if (uk) { ci.append(" ADD CONSTRAINT ").append(nin); ci.append(" UNIQUE ").append(colsIdx); } else { ci = new StringBuffer("CREATE INDEX ").append(nin) .append(" ON ").append(ntn).append(colsIdx); } try { execCreate(ci.toString(),true); } catch (SQLException e) { if( HSQL_UK_ALREADY_EXISTS== e.getErrorCode())return ; if (idx.isUnique()) { for (Index.Column cd : idx.getColumns()) { if (cd.getColumn().getType() .equals(DataType.COMPLEX_TYPE)) { return; } } } Logger.logWarning(e.getMessage()); return; } catch (Exception e) { Logger.logWarning(e.getMessage()); return; } String pre = pk ? "Primary Key " : uk ? "Index Unique " : "Index"; loadedIndexes.add(pre + " on " + ntn + " Columns:" + colsIdx); } private void createTable(Table t) throws SQLException, IOException { createTable(t,false) ; } private void createTable(Table t, boolean systemTable) throws SQLException, IOException { String tn = t.getName(); if (tn.indexOf(" ") > 0) { SQLConverter.addWhiteSpacedTableNames(tn); } String ntn = SQLConverter.escapeIdentifier(tn); if (ntn == null) return; createSyncrTable(t,systemTable); } private boolean hasAppendOnly(Table t) { for (Column c:t.getColumns()){ if(c.isAppendOnly()){ return true; } } return false; } private void loadTableData(Table t, boolean systemTable) throws IOException, SQLException { PreparedStatement ps = null; try { int i=0; for (Row row:t) { ArrayList<Object> values = new ArrayList<Object>(); if (row == null) continue; if (ps == null) ps = sqlInsert(t, row,systemTable); Collection< Object> ce = row.values(); int j=0; for (Object obj : ce) { //workaround waiting for a jackcess fix if(obj==null){ Column memo=t.getColumns().get(j); if(DataType.MEMO.equals(memo.getType()) &&memo.getProperties().getValue(PropertyMap.REQUIRED_PROP)!=null &&(Boolean)memo.getProperties().getValue(PropertyMap.REQUIRED_PROP) ){ obj=""; } } //workaround end values.add(value(obj)); j++; } execInsert(ps, values); if((i>0&&i%1000==0)|| i==t.getRowCount()-1 ){ conn.commit(); } i++; } if(i!=t.getRowCount()){ Logger.logParametricWarning(Messages.ROW_COUNT, t.getName(),String.valueOf(t.getRowCount()),String.valueOf(i)); } } finally { if (ps != null) ps.close(); } } private void loadTableFKs(String tableName) throws IOException, SQLException { Table table = dbIO.getTable(tableName); for (Index idxi : table.getIndexes()) { //riw IndexImpl idx=(IndexImpl)idxi; if (idx.isForeignKey() && !idx.getReference().isPrimaryTable()) loadForeignKey(idx); } } private void createCalculatedFieldsTriggers(){ for (String trigger : calculatedFieldsTriggers) { try{ execCreate(trigger,false); }catch(SQLException e){ Logger.logWarning(e.getMessage()); break; } } } private void loadTableIndexesUK(String tableName) throws IOException, SQLException { Table table = dbIO.getTable(tableName); for (Index idx : table.getIndexes()) { if (!idx.isForeignKey() && (idx.isPrimaryKey()||idx.isUnique())) { loadIndex(idx); } } } private void loadTableIndexesNotUK(String tableName) throws IOException, SQLException { Table table = dbIO.getTable(tableName); for (Index idx : table.getIndexes()) { if (!idx.isForeignKey() && !idx.isPrimaryKey() && !idx.isUnique()) { loadIndex(idx); } } } private void createTables() throws SQLException, IOException{ for (String tn : dbIO.getTableNames()) { Table t = null; try { t = dbIO.getTable(tn); } catch (Exception e) { Logger.logWarning(e.getMessage()); this.unresolvedTables.add(tn); } if (t != null){ createTable(t); this.loadingOrder.add(t.getName()); } } } private void createIndexesUK() throws SQLException, IOException{ for (String tn : dbIO.getTableNames()) { if (!this.unresolvedTables.contains(tn)){ this.loadTableIndexesUK(tn); conn.commit(); } } } private void createIndexesNotUK() throws SQLException, IOException{ for (String tn : dbIO.getTableNames()) { if (!this.unresolvedTables.contains(tn)){ this.loadTableIndexesNotUK(tn); conn.commit(); } } } private void createFKs() throws SQLException, IOException{ for (String tn : dbIO.getTableNames()) { if (!this.unresolvedTables.contains(tn)){ this.loadTableFKs(tn); conn.commit(); } } } private void loadTablesData() throws SQLException, IOException{ for (String tn : this.loadingOrder) { if (!this.unresolvedTables.contains(tn)){ Table t = dbIO.getTable(tn); this.loadTableData(t,false); conn.commit(); } } } private void createTriggers() throws IOException, SQLException{ createCalculatedFieldsTriggers(); for (String tn : this.loadingOrder) { if (!this.unresolvedTables.contains(tn)){ Table t = dbIO.getTable(tn); createSyncrTriggers(t); } } } private void createSystemTables() throws SQLException, IOException{ if(sysSchema){ createSystemSchema(); for (String tn : dbIO.getSystemTableNames()) { Table t = null; try { t = dbIO.getSystemTable(tn); if (t != null){ createTable(t,true); loadTableData(t,true); execCreate("SET TABLE "+schema(SQLConverter.escapeIdentifier(t.getName()),true)+" READONLY TRUE ",false); execCreate("GRANT SELECT ON "+schema(SQLConverter.escapeIdentifier(t.getName()),true)+" TO PUBLIC ",false); } } catch (Exception ignore) {} } } } private void loadTables() throws SQLException, IOException { createTables(); createIndexesUK(); boolean reorder=reorder(); if(reorder)createFKs(); createIndexesNotUK(); loadTablesData(); createTriggers(); if(!reorder)createFKs(); createSystemTables(); } private void createSystemSchema() throws SQLException { execCreate("CREATE SCHEMA "+SYSTEM_SCHEMA+" AUTHORIZATION DBA",false); } private void createSyncrTriggers(Table t) throws SQLException, IOException{ defaultValues(t); String ntn = SQLConverter.escapeIdentifier(t.getName()); triggersGenerator.synchronisationTriggers(ntn, hasAutoNumberColumn(t),hasAppendOnly(t)); loadedTables.add(ntn); } private PreparedStatement sqlInsert(Table t, Map<String, Object> row,boolean systemTable) throws IOException, SQLException { String tn = t.getName(); String ntn = schema(SQLConverter.escapeIdentifier(tn),systemTable); String comma = ""; StringBuffer sbI = new StringBuffer(" INSERT INTO ").append(ntn) .append(" ("); StringBuffer sbE = new StringBuffer(" VALUES( "); Set<String> se = row.keySet(); comma = ""; for (String cn : se) { sbI.append(comma).append( SQLConverter.escapeIdentifier(cn)); sbE.append(comma).append(" ? "); comma = ","; } sbI.append(") "); sbE.append(")"); sbI.append(sbE); return conn.prepareStatement(sbI.toString()); } private Object value(Object value) throws SQLException { if (value == null) return null; if (value instanceof Float) { BigDecimal bd = new BigDecimal(value.toString()); return bd; } if (value instanceof Date && !(value instanceof Timestamp)) { Timestamp ts = new Timestamp(((Date) value).getTime()); return ts; } if (value instanceof ComplexValueForeignKey) { try { return ComplexBase.convert((ComplexValueForeignKey) value); } catch (IOException e) { throw new UcanaccessSQLException(e); } } if(value instanceof Byte){ return SQLConverter.asUnsigned((Byte)value); } return value; } } private final class TriggersLoader { private final static String DEFAULT_TRIGGERS_PACKAGE = "net.ucanaccess.triggers"; private void loadTrigger(String tableName, String namePrefix, String when, String className) throws SQLException { String q0 = DBReference.is2xx() ? "" : " QUEUE 0 "; String triggerName = namePrefix + "_" + (tableName.replaceAll("\"", "").replaceAll(" ", "_")); execCreate("CREATE TRIGGER " + triggerName + " " + when + " ON " + tableName + " FOR EACH ROW " + q0 + " CALL \"" + className + "\" ",true); } private void loadTriggerNP(String tableName, String namePrefix, String when, String className) throws SQLException { loadTrigger(tableName, namePrefix, when, DEFAULT_TRIGGERS_PACKAGE + "." + className); } private void synchronisationTriggers(String tableName, boolean hasAutoNumberColumn, boolean hasAutoAppendOnly) throws SQLException { loadTriggerNP(tableName, "genericInsert", "AFTER INSERT", "TriggerInsert"); loadTriggerNP(tableName, "genericUpdate", "AFTER UPDATE", "TriggerUpdate"); loadTriggerNP(tableName, "genericDelete", "AFTER DELETE", "TriggerDelete"); if (hasAutoAppendOnly) { loadTriggerNP(tableName, "appendOnly", "BEFORE INSERT", "TriggerAppendOnly"); loadTriggerNP(tableName, "appendOnly_upd", "BEFORE UPDATE", "TriggerAppendOnly"); } if (hasAutoNumberColumn) { loadTriggerNP(tableName, "autonumber", "BEFORE INSERT", "TriggerAutoNumber"); loadTriggerNP(tableName, "autonumber_validate", "BEFORE UPDATE", "TriggerAutoNumber"); } } } private final class ViewsLoader { private HashMap<String,String> notLoaded = new HashMap<String,String>(); private static final int OBJECT_ALREADY_EXISTS=-ErrorCode.X_42504; private boolean loadView(Query q) throws SQLException { return loadView(q,null); } private boolean loadView(Query q, String queryWKT) throws SQLException { String qnn = SQLConverter.basicEscapingIdentifier(q.getName()); if(qnn==null){ return false; } if (qnn.indexOf(" ") > 0) { SQLConverter.addWhiteSpacedTableNames(q.getName()); } String escqn = qnn.indexOf(' ') > 0 ? "[" + qnn + "]" : qnn; String querySQL =queryWKT==null? q.toSQLString():queryWKT; Pivot pivot = null; if (q.getType().equals(Query.Type.CROSS_TAB)) { pivot = new Pivot(conn); if (!pivot.parsePivot(querySQL) || (querySQL = pivot.toSQL()) == null) { this.notLoaded.put(q.getName(),"cannot load this query"); return false; } } querySQL =new DFunction(conn, querySQL ).toSQL(); StringBuffer sb = new StringBuffer("CREATE VIEW ").append(escqn) .append(" AS ").append(querySQL); String v = null; try { v = SQLConverter.convertSQL(sb.toString(), true); if(v.trim().endsWith(";")) v=v.trim().substring(0, v.length()-1); execCreate(v,false); loadedQueries.add(qnn); this.notLoaded.remove(qnn); if (pivot != null) { pivot.registerPivot(qnn); } return true; } catch (Exception e) { if(e instanceof SQLSyntaxErrorException&&queryWKT==null&&((SQLSyntaxErrorException)e).getErrorCode()==OBJECT_ALREADY_EXISTS){ return loadView( q, solveAmbiguous(querySQL)); } String cause=UcanaccessSQLException.explaneCause(e); this.notLoaded.put(q.getName(),": "+cause); if (!err) { Logger.log("Error occured while loading:" + q.getName()); Logger.log("Converted view was :" + v); Logger.log("Error message was :" + e.getMessage()); err = true; } return false; } } private String solveAmbiguous(String sql) { try{ sql=sql.replaceAll("[\n\r]", " "); Pattern pt=Pattern.compile("(.*)[\n\r\\s]*(?i)SELECT([\n\r\\s].*[\n\r\\s])(?i)FROM([\n\r\\s])(.*)"); Matcher mtc =pt.matcher(sql); if(mtc.find()){ String select =mtc.group(2); String pre=mtc.group(1)==null?"":mtc.group(1); String[] splitted=select.split(",",-1); StringBuffer sb=new StringBuffer (pre+" select "); LinkedList<String> lkl=new LinkedList<String>(); for(String s:splitted){ int j=s.lastIndexOf("."); Pattern aliasPt=Pattern .compile("[\\s\n\r]+(?i)AS[\\s\n\r]+"); boolean alias=aliasPt.matcher(s).find(); if(j<0||alias){ lkl.add(s); }else{ String k=s.substring(j+1); if(lkl.contains(k)){ int idx=lkl.indexOf(k); String old=lkl.get(lkl.indexOf(k)); lkl.remove(old); lkl.add(idx,splitted[idx]+ " AS ["+splitted[idx].trim() +"]"); lkl.add(s + " AS ["+s.trim()+"]"); }else{ lkl.add(k); } } } String comma=""; for(String s:lkl){ sb.append(comma).append(s); comma=","; } sb.append(" FROM ").append(mtc.group(4)); return sb.toString(); } else return sql; }catch(Exception e){ return sql; } } private void loadViews() throws SQLException, IOException { List<Query> lq = null; try { lq = dbIO.getQueries(); Iterator<Query> it = lq.iterator(); while (it.hasNext()) { Query q = it.next(); if (!q.getType().equals(Query.Type.SELECT) && !q.getType().equals(Query.Type.UNION) && !q.getType().equals(Query.Type.CROSS_TAB)) { it.remove(); } } queryPorting(lq); } catch (Exception e) { this.notLoaded.put("",""); } } private void queryPorting(List<Query> lq) throws SQLException { ArrayList<String> arn = new ArrayList<String>(); for (Query q : lq) { arn.add(q.getName().toLowerCase()); } boolean heavy = false; while (lq.size() > 0) { ArrayList<Query> arq = new ArrayList<Query>(); for (Query q : lq) { String qtxt =null; boolean qryGot=true; try{ qtxt = q.toSQLString().toLowerCase(); }catch(Exception ignore){ qryGot=false; } boolean foundDep = false; if (qryGot&&!heavy) for (String name : arn) { if (qtxt.indexOf(name) != -1) { foundDep = true; break; } } if (qryGot&&!foundDep && loadView(q)) { arq.add(q); arn.remove(q.getName()); } } if (arq.size() == 0) { if (heavy) { break; } else { heavy = true; } } lq.removeAll(arq); } } } private Connection conn; private Database dbIO; private boolean err; private FunctionsLoader functionsLoader = new FunctionsLoader(); private ArrayList<String> loadedIndexes = new ArrayList<String>(); private ArrayList<String> loadedQueries = new ArrayList<String>(); private ArrayList<String> loadedTables = new ArrayList<String>(); private LogsFlusher logsFlusher = new LogsFlusher(); private TablesLoader tablesLoader = new TablesLoader(); private TriggersLoader triggersGenerator = new TriggersLoader(); private ViewsLoader viewsLoader = new ViewsLoader(); private boolean sysSchema; private boolean ff1997; public LoadJet(Connection conn, Database dbIO) { super(); this.conn = conn; this.dbIO = dbIO; try { this.ff1997= FileFormat.V1997.equals(this.dbIO.getFileFormat()); } catch (Exception ignore) { // Logger.logWarning(e.getMessage()); } } public void loadDefaultValues(Table t) throws SQLException, IOException{ this.tablesLoader.defaultValues(t); } private static boolean hasAutoNumberColumn(Table t) { List<? extends Column> lc = t.getColumns(); for (Column cl : lc) { if (cl.isAutoNumber()||DataType.BOOLEAN.equals(cl.getType())) { return true; } } return false; } public void addFunctions(Class<?> clazz) throws SQLException { this.functionsLoader.addFunctions(clazz); } private void execCreate(String expression, boolean logging) throws SQLException { Statement st = null; try { st = conn.createStatement(); st.executeUpdate(expression); } catch(SQLException e){ if(logging&&e.getErrorCode()!=TablesLoader.HSQL_FK_ALREADY_EXISTS) Logger.log("Cannot execute:"+expression+" "+e.getMessage()); throw e; } finally { if (st != null) st.close(); } } private void execInsert(PreparedStatement st, ArrayList<Object> values) throws SQLException { int i = 1; for (Object value : values) { st.setObject(i++, value); } st.execute(); } public SQLWarning getLoadingWarnings() { if (this.viewsLoader.notLoaded.size() == 0 && this.tablesLoader.unresolvedTables.size() == 0) { return null; } SQLWarning sqlw = null; for (String s : this.viewsLoader.notLoaded.keySet()) { String message = s.length() > 0 ? "Cannot load view " + s+ " "+this.viewsLoader.notLoaded.get(s) : "Cannot load views "; if (sqlw == null) { sqlw = new SQLWarning(message); } else { sqlw.setNextWarning(new SQLWarning(message)); } } for (String s : this.tablesLoader.unresolvedTables) { String message = "Cannot resolve table " + s; if (sqlw == null) { sqlw = new SQLWarning(message); } else { sqlw.setNextWarning(new SQLWarning(message)); } } return sqlw; } public void loadDB() throws SQLException, IOException { try { this.functionsLoader.loadMappedFunctions(); this.tablesLoader.loadTables(); this.viewsLoader.loadViews(); conn.commit(); SQLConverter.cleanEscaped(); } finally { Logger.log("Loaded Tables:"); logsFlusher.dumpList(this.loadedTables); Logger.log("Loaded Queries:"); logsFlusher.dumpList(this.loadedQueries); Logger.log("Loaded Indexes:"); logsFlusher.dumpList(this.loadedIndexes, true); conn.close(); } } public void synchronisationTriggers(String tableName, boolean hasAutoNumberColumn,boolean hasAppendOnly) throws SQLException { this.triggersGenerator.synchronisationTriggers(tableName, hasAutoNumberColumn,hasAppendOnly); } private boolean tryDefault(Object defaulT) throws SQLException { Statement st = null; try { st = conn.createStatement(); st.executeQuery("SELECT " + defaulT + " FROM INFORMATION_SCHEMA.SYSTEM_TABLES where 2=1"); return true; } catch (Exception e) { return false; } finally { if (st != null) st.close(); } } public void setSysSchema(boolean sysSchema) { this.sysSchema=sysSchema; } }
package org.altbeacon.beacon; import android.annotation.TargetApi; import android.bluetooth.BluetoothDevice; import android.os.Build; import android.util.Log; import org.altbeacon.beacon.logging.LogManager; import org.altbeacon.bluetooth.BleAdvertisement; import org.altbeacon.bluetooth.Pdu; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class BeaconParser { private static final String TAG = "BeaconParser"; private static final Pattern I_PATTERN = Pattern.compile("i\\:(\\d+)\\-(\\d+)([blv]*)?"); private static final Pattern M_PATTERN = Pattern.compile("m\\:(\\d+)-(\\d+)\\=([0-9A-Fa-f]+)"); private static final Pattern S_PATTERN = Pattern.compile("s\\:(\\d+)-(\\d+)\\=([0-9A-Fa-f]+)"); private static final Pattern D_PATTERN = Pattern.compile("d\\:(\\d+)\\-(\\d+)([bl]*)?"); private static final Pattern P_PATTERN = Pattern.compile("p\\:(\\d+)\\-(\\d+)\\:?([\\-\\d]+)?"); private static final Pattern X_PATTERN = Pattern.compile("x"); private static final char[] HEX_ARRAY = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; private static String LITTLE_ENDIAN_SUFFIX = "l"; private static String VARIABLE_LENGTH_SUFFIX = "v"; private Long mMatchingBeaconTypeCode; protected List<Integer> mIdentifierStartOffsets; protected List<Integer> mIdentifierEndOffsets; protected List<Boolean> mIdentifierLittleEndianFlags; protected List<Integer> mDataStartOffsets; protected List<Integer> mDataEndOffsets; protected List<Boolean> mDataLittleEndianFlags; protected List<Boolean> mIdentifierVariableLengthFlags; protected Integer mMatchingBeaconTypeCodeStartOffset; protected Integer mMatchingBeaconTypeCodeEndOffset; protected Integer mServiceUuidStartOffset; protected Integer mServiceUuidEndOffset; protected Long mServiceUuid; protected Boolean mExtraFrame; protected Integer mPowerStartOffset; protected Integer mPowerEndOffset; protected Integer mDBmCorrection; protected Integer mLayoutSize; protected Boolean mAllowPduOverflow; protected int[] mHardwareAssistManufacturers = new int[] { 0x004c }; /** * Makes a new BeaconParser. Should normally be immediately followed by a call to #setLayout */ public BeaconParser() { mIdentifierStartOffsets = new ArrayList<Integer>(); mIdentifierEndOffsets = new ArrayList<Integer>(); mDataStartOffsets = new ArrayList<Integer>(); mDataEndOffsets = new ArrayList<Integer>(); mDataLittleEndianFlags = new ArrayList<Boolean>(); mIdentifierLittleEndianFlags = new ArrayList<Boolean>(); mIdentifierVariableLengthFlags = new ArrayList<Boolean>(); mAllowPduOverflow = true; } /** * <p>Defines a beacon field parsing algorithm based on a string designating the zero-indexed * offsets to bytes within a BLE advertisement.</p> * * <p>If you want to see examples of how other folks have set up BeaconParsers for different * kinds of beacons, try doing a Google search for "getBeaconParsers" (include the quotes in * the search.)</p> * * <p>Four prefixes are allowed in the string:</p> * * <pre> * m - matching byte sequence for this beacon type to parse (exactly one required) * s - ServiceUuid for this beacon type to parse (optional, only for Gatt-based beacons) * i - identifier (at least one required, multiple allowed) * p - power calibration field (exactly one required) * d - data field (optional, multiple allowed) * x - extra layout. Signifies that the layout is secondary to a primary layout with the same * matching byte sequence (or ServiceUuid). Extra layouts do not require power or * identifier fields and create Beacon objects without identifiers. * </pre> * * <p>Each prefix is followed by a colon, then an inclusive decimal byte offset for the field from * the beginning of the advertisement. In the case of the m prefix, an = sign follows the byte * offset, followed by a big endian hex representation of the bytes that must be matched for * this beacon type. When multiple i or d entries exist in the string, they will be added in * order of definition to the identifier or data array for the beacon when parsing the beacon * advertisement. Terms are separated by commas.</p> * * <p>All offsets from the start of the advertisement are relative to the first byte of the * two byte manufacturer code. The manufacturer code is therefore always at position 0-1</p> * * <p>All data field and identifier expressions may be optionally suffixed with the letter l, which * indicates the field should be parsed as little endian. If not present, the field will be presumed * to be big endian. Note: serviceUuid fields are always little endian. * * <p>Identifier fields may be optionally suffixed with the letter v, which * indicates the field is variable length, and may be shorter than the declared length if the * parsed PDU for the advertisement is shorter than needed to parse the full identifier. * * <p>If the expression cannot be parsed, a <code>BeaconLayoutException</code> is thrown.</p> * * <p>Example of a parser string for AltBeacon:</p> * * </pre> * "m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25" * </pre> * * <p>This signifies that the beacon type will be decoded when an advertisement is found with * 0xbeac in bytes 2-3, and a three-part identifier will be pulled out of bytes 4-19, bytes * 20-21 and bytes 22-23, respectively. A signed power calibration value will be pulled out of * byte 24, and a data field will be pulled out of byte 25.</p> * * Note: bytes 0-1 of the BLE manufacturer advertisements are the two byte manufacturer code. * Generally you should not match on these two bytes when using a BeaconParser, because it will * limit your parser to matching only a transmitter made by a specific manufacturer. Software * and operating systems that scan for beacons typically ignore these two bytes, allowing beacon * manufacturers to use their own company code assigned by Bluetooth SIG. The default parser * implementation will already pull out this company code and store it in the * beacon.mManufacturer field. Matcher expressions should therefore start with "m2-3:" followed * by the multi-byte hex value that signifies the beacon type. * * @param beaconLayout * @return the BeaconParser instance */ public BeaconParser setBeaconLayout(String beaconLayout) { String[] terms = beaconLayout.split(","); mExtraFrame = false; // this is not an extra frame by default for (String term : terms) { boolean found = false; Matcher matcher = I_PATTERN.matcher(term); while (matcher.find()) { found = true; try { int startOffset = Integer.parseInt(matcher.group(1)); int endOffset = Integer.parseInt(matcher.group(2)); Boolean littleEndian = matcher.group(3).contains(LITTLE_ENDIAN_SUFFIX); mIdentifierLittleEndianFlags.add(littleEndian); Boolean variableLength = matcher.group(3).contains(VARIABLE_LENGTH_SUFFIX); mIdentifierVariableLengthFlags.add(variableLength); mIdentifierStartOffsets.add(startOffset); mIdentifierEndOffsets.add(endOffset); } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse integer byte offset in term: " + term); } } matcher = D_PATTERN.matcher(term); while (matcher.find()) { found = true; try { int startOffset = Integer.parseInt(matcher.group(1)); int endOffset = Integer.parseInt(matcher.group(2)); Boolean littleEndian = matcher.group(3).contains("l"); mDataLittleEndianFlags.add(littleEndian); mDataStartOffsets.add(startOffset); mDataEndOffsets.add(endOffset); } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse integer byte offset in term: " + term); } } matcher = P_PATTERN.matcher(term); while (matcher.find()) { found = true; try { int startOffset = Integer.parseInt(matcher.group(1)); int endOffset = Integer.parseInt(matcher.group(2)); int dBmCorrection = 0; if (matcher.group(3) != null) { dBmCorrection = Integer.parseInt(matcher.group(3)); } mDBmCorrection=dBmCorrection; mPowerStartOffset=startOffset; mPowerEndOffset=endOffset; } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse integer power byte offset in term: " + term); } } matcher = M_PATTERN.matcher(term); while (matcher.find()) { found = true; try { int startOffset = Integer.parseInt(matcher.group(1)); int endOffset = Integer.parseInt(matcher.group(2)); mMatchingBeaconTypeCodeStartOffset = startOffset; mMatchingBeaconTypeCodeEndOffset = endOffset; } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse integer byte offset in term: " + term); } String hexString = matcher.group(3); try { mMatchingBeaconTypeCode = Long.decode("0x"+hexString); } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse beacon type code: "+hexString+" in term: " + term); } } matcher = S_PATTERN.matcher(term); while (matcher.find()) { found = true; try { int startOffset = Integer.parseInt(matcher.group(1)); int endOffset = Integer.parseInt(matcher.group(2)); mServiceUuidStartOffset = startOffset; mServiceUuidEndOffset = endOffset; } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse integer byte offset in term: " + term); } String hexString = matcher.group(3); try { mServiceUuid = Long.decode("0x"+hexString); } catch (NumberFormatException e) { throw new BeaconLayoutException("Cannot parse serviceUuid: "+hexString+" in term: " + term); } } matcher = X_PATTERN.matcher(term); while (matcher.find()) { found = true; mExtraFrame = true; } if (!found) { LogManager.d(TAG, "cannot parse term %s", term); throw new BeaconLayoutException("Cannot parse beacon layout term: " + term); } } if (!mExtraFrame) { // extra frames do not have to have identifiers or power fields, but other types do if (mIdentifierStartOffsets.size() == 0 || mIdentifierEndOffsets.size() == 0) { throw new BeaconLayoutException("You must supply at least one identifier offset with a prefix of 'i'"); } if (mPowerStartOffset == null || mPowerEndOffset == null) { throw new BeaconLayoutException("You must supply a power byte offset with a prefix of 'p'"); } } if (mMatchingBeaconTypeCodeStartOffset == null || mMatchingBeaconTypeCodeEndOffset == null) { throw new BeaconLayoutException("You must supply a matching beacon type expression with a prefix of 'm'"); } mLayoutSize = calculateLayoutSize(); return this; } public int[] getHardwareAssistManufacturers() { return mHardwareAssistManufacturers; } public void setHardwareAssistManufacturerCodes(int[] manufacturers) { mHardwareAssistManufacturers = manufacturers; } /** * Setting to true indicates that packets should be rejected if the PDU length is too short for * the fields. Some beacons transmit malformed PDU packets that understate their length, so * this defaults to false. * @param enabled */ public void setAllowPduOverflow(Boolean enabled) { mAllowPduOverflow = enabled; } /** * @see #mMatchingBeaconTypeCode * @return */ public Long getMatchingBeaconTypeCode() { return mMatchingBeaconTypeCode; } /** * see #mMatchingBeaconTypeCodeStartOffset * @return */ public int getMatchingBeaconTypeCodeStartOffset() { return mMatchingBeaconTypeCodeStartOffset; } /** * see #mMatchingBeaconTypeCodeEndOffset * @return */ public int getMatchingBeaconTypeCodeEndOffset() { return mMatchingBeaconTypeCodeEndOffset; } /** * @see #mServiceUuid * @return */ public Long getServiceUuid() { return mServiceUuid; } /** * see #mServiceUuidStartOffset * @return */ public int getMServiceUuidStartOffset() { return mServiceUuidStartOffset; } /** * see #mServiceUuidEndOffset * @return */ public int getServiceUuidEndOffset() { return mServiceUuidEndOffset; } /** * Construct a Beacon from a Bluetooth LE packet collected by Android's Bluetooth APIs, * including the raw Bluetooth device info * * @param scanData The actual packet bytes * @param rssi The measured signal strength of the packet * @param device The Bluetooth device that was detected * @return An instance of a <code>Beacon</code> */ @TargetApi(5) public Beacon fromScanData(byte[] scanData, int rssi, BluetoothDevice device) { return fromScanData(scanData, rssi, device, new Beacon()); } @TargetApi(5) protected Beacon fromScanData(byte[] bytesToProcess, int rssi, BluetoothDevice device, Beacon beacon) { BleAdvertisement advert = new BleAdvertisement(bytesToProcess); boolean parseFailed = false; Pdu pduToParse = null; int startByte = 0; ArrayList<Identifier> identifiers = new ArrayList<Identifier>(); ArrayList<Long> dataFields = new ArrayList<Long>(); for (Pdu pdu: advert.getPdus()) { if (pdu.getType() == Pdu.GATT_SERVICE_UUID_PDU_TYPE || pdu.getType() == Pdu.MANUFACTURER_DATA_PDU_TYPE) { pduToParse = pdu; if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "Processing pdu type %02X: %s with startIndex: %d, endIndex: %d", pdu.getType(), bytesToHex(bytesToProcess), pdu.getStartIndex(), pdu.getEndIndex()); } break; } else { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "Ignoring pdu type %02X", pdu.getType()); } } } if (pduToParse == null) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "No PDUs to process in this packet."); } parseFailed = true; } else { byte[] serviceUuidBytes = null; byte[] typeCodeBytes = longToByteArray(getMatchingBeaconTypeCode(), mMatchingBeaconTypeCodeEndOffset - mMatchingBeaconTypeCodeStartOffset + 1); if (getServiceUuid() != null) { serviceUuidBytes = longToByteArray(getServiceUuid(), mServiceUuidEndOffset - mServiceUuidStartOffset + 1, false); } startByte = pduToParse.getStartIndex(); boolean patternFound = false; if (getServiceUuid() == null) { if (byteArraysMatch(bytesToProcess, startByte + mMatchingBeaconTypeCodeStartOffset, typeCodeBytes, 0)) { patternFound = true; } } else { if (byteArraysMatch(bytesToProcess, startByte + mServiceUuidStartOffset, serviceUuidBytes, 0) && byteArraysMatch(bytesToProcess, startByte + mMatchingBeaconTypeCodeStartOffset, typeCodeBytes, 0)) { patternFound = true; } } if (patternFound == false) { // This is not a beacon if (getServiceUuid() == null) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "This is not a matching Beacon advertisement. (Was expecting %s. " + "The bytes I see are: %s", byteArrayToString(typeCodeBytes), bytesToHex(bytesToProcess)); } } else { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "This is not a matching Beacon advertisement. Was expecting %s. " + "The bytes I see are: %s", byteArrayToString(serviceUuidBytes), byteArrayToString(typeCodeBytes), bytesToHex(bytesToProcess)); } } parseFailed = true; beacon = null; } else { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "This is a recognized beacon advertisement -- %s seen", byteArrayToString(typeCodeBytes)); } } if (patternFound) { if (bytesToProcess.length <= startByte+mLayoutSize && mAllowPduOverflow) { // If the layout size is bigger than this PDU, and we allow overflow. Make sure // the byte buffer is big enough by zero padding the end so we don't try to read // outside the byte array of the advertisement if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "Expanding buffer because it is too short to parse: "+bytesToProcess.length+", needed: "+(startByte+mLayoutSize)); } bytesToProcess = ensureMaxSize(bytesToProcess, startByte+mLayoutSize); } for (int i = 0; i < mIdentifierEndOffsets.size(); i++) { int endIndex = mIdentifierEndOffsets.get(i) + startByte; if (endIndex > pduToParse.getEndIndex() && mIdentifierVariableLengthFlags.get(i)) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "Need to truncate identifier by "+(endIndex-pduToParse.getEndIndex())); } // If this is a variable length identifier, we truncate it to the size that // is available in the packet Identifier identifier = Identifier.fromBytes(bytesToProcess, mIdentifierStartOffsets.get(i) + startByte, pduToParse.getEndIndex()+1, mIdentifierLittleEndianFlags.get(i)); identifiers.add(identifier); } else if (endIndex > pduToParse.getEndIndex() && !mAllowPduOverflow) { parseFailed = true; if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "Cannot parse identifier "+i+" because PDU is too short. endIndex: " + endIndex + " PDU endIndex: " + pduToParse.getEndIndex()); } } else { Identifier identifier = Identifier.fromBytes(bytesToProcess, mIdentifierStartOffsets.get(i) + startByte, endIndex+1, mIdentifierLittleEndianFlags.get(i)); identifiers.add(identifier); } } for (int i = 0; i < mDataEndOffsets.size(); i++) { int endIndex = mDataEndOffsets.get(i) + startByte; if (endIndex > pduToParse.getEndIndex() && !mAllowPduOverflow) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "Cannot parse data field "+i+" because PDU is too short. endIndex: " + endIndex + " PDU endIndex: " + pduToParse.getEndIndex()+". Setting value to 0"); } dataFields.add(new Long(0l)); } else { String dataString = byteArrayToFormattedString(bytesToProcess, mDataStartOffsets.get(i) + startByte, endIndex, mDataLittleEndianFlags.get(i)); dataFields.add(Long.parseLong(dataString)); } } if (mPowerStartOffset != null) { int endIndex = mPowerEndOffset + startByte; int txPower = 0; try { if (endIndex > pduToParse.getEndIndex() && !mAllowPduOverflow) { parseFailed = true; if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "Cannot parse power field because PDU is too short. endIndex: " + endIndex + " PDU endIndex: " + pduToParse.getEndIndex()); } } else { String powerString = byteArrayToFormattedString(bytesToProcess, mPowerStartOffset + startByte, mPowerEndOffset + startByte, false); txPower = Integer.parseInt(powerString)+mDBmCorrection; // make sure it is a signed integer if (txPower > 127) { txPower -= 256; } beacon.mTxPower = txPower; } } catch (NumberFormatException e1) { // keep default value } catch (NullPointerException e2) { // keep default value } } } } if (parseFailed) { beacon = null; } else { int beaconTypeCode = 0; String beaconTypeString = byteArrayToFormattedString(bytesToProcess, mMatchingBeaconTypeCodeStartOffset+startByte, mMatchingBeaconTypeCodeEndOffset+startByte, false); beaconTypeCode = Integer.parseInt(beaconTypeString); // TODO: error handling needed on the parse int manufacturer = 0; String manufacturerString = byteArrayToFormattedString(bytesToProcess, startByte, startByte+1, true); manufacturer = Integer.parseInt(manufacturerString); String macAddress = null; String name = null; if (device != null) { macAddress = device.getAddress(); name = device.getName(); } beacon.mIdentifiers = identifiers; beacon.mDataFields = dataFields; beacon.mRssi = rssi; beacon.mBeaconTypeCode = beaconTypeCode; if (mServiceUuid != null) { beacon.mServiceUuid = (int) mServiceUuid.longValue(); } else { beacon.mServiceUuid = -1; } beacon.mBluetoothAddress = macAddress; beacon.mBluetoothName= name; beacon.mManufacturer = manufacturer; } return beacon; } /** * Get BLE advertisement bytes for a Beacon * @param beacon the beacon containing the data to be transmitted * @return the byte array of the advertisement */ public byte[] getBeaconAdvertisementData(Beacon beacon) { byte[] advertisingBytes; int lastIndex = -1; if (mMatchingBeaconTypeCodeEndOffset != null && mMatchingBeaconTypeCodeEndOffset > lastIndex) { lastIndex = mMatchingBeaconTypeCodeEndOffset; } if (mPowerEndOffset != null && mPowerEndOffset > lastIndex) { lastIndex = mPowerEndOffset; } for (int identifierNum = 0; identifierNum < this.mIdentifierStartOffsets.size(); identifierNum++) { if (this.mIdentifierEndOffsets.get(identifierNum) != null && this.mIdentifierEndOffsets.get(identifierNum) > lastIndex) { lastIndex = this.mIdentifierEndOffsets.get(identifierNum); } } for (int identifierNum = 0; identifierNum < this.mDataEndOffsets.size(); identifierNum++) { if (this.mDataEndOffsets.get(identifierNum) != null && this.mDataEndOffsets.get(identifierNum) > lastIndex) { lastIndex = this.mDataEndOffsets.get(identifierNum); } } // we must adjust the lastIndex to account for variable length identifiers, if there are any. int adjustedIdentifiersLength = 0; for (int identifierNum = 0; identifierNum < this.mIdentifierStartOffsets.size(); identifierNum++) { int declaredIdentifierLength = (this.mIdentifierEndOffsets.get(identifierNum) - this.mIdentifierStartOffsets.get(identifierNum)+1); int actualIdentifierLength = beacon.getIdentifier(identifierNum).getByteCount(); adjustedIdentifiersLength += actualIdentifierLength; adjustedIdentifiersLength -= declaredIdentifierLength; } lastIndex += adjustedIdentifiersLength; advertisingBytes = new byte[lastIndex+1-2]; long beaconTypeCode = this.getMatchingBeaconTypeCode(); // set type code for (int index = this.mMatchingBeaconTypeCodeStartOffset; index <= this.mMatchingBeaconTypeCodeEndOffset; index++) { byte value = (byte) (this.getMatchingBeaconTypeCode() >> (8*(this.mMatchingBeaconTypeCodeEndOffset-index)) & 0xff); advertisingBytes[index-2] = value; } // set identifiers for (int identifierNum = 0; identifierNum < this.mIdentifierStartOffsets.size(); identifierNum++) { byte[] identifierBytes = beacon.getIdentifier(identifierNum).toByteArrayOfSpecifiedEndianness(this.mIdentifierLittleEndianFlags.get(identifierNum)); for (int index = this.mIdentifierStartOffsets.get(identifierNum); index <= this.mIdentifierStartOffsets.get(identifierNum)+identifierBytes.length-1; index ++) { int identifierByteIndex = this.mIdentifierEndOffsets.get(identifierNum)-index; if (identifierByteIndex < identifierBytes.length) { advertisingBytes[index-2] = (byte) identifierBytes[this.mIdentifierEndOffsets.get(identifierNum)-index]; } else { advertisingBytes[index-2] = 0; } } } // set power for (int index = this.mPowerStartOffset; index <= this.mPowerEndOffset; index ++) { advertisingBytes[index-2] = (byte) (beacon.getTxPower() >> (8*(index - this.mPowerStartOffset)) & 0xff); } // set data fields for (int dataFieldNum = 0; dataFieldNum < this.mDataStartOffsets.size(); dataFieldNum++) { long dataField = beacon.getDataFields().get(dataFieldNum); for (int index = this.mDataStartOffsets.get(dataFieldNum); index <= this.mDataEndOffsets.get(dataFieldNum); index ++) { int endianCorrectedIndex = index; if (this.mDataLittleEndianFlags.get(dataFieldNum)) { endianCorrectedIndex = this.mDataEndOffsets.get(dataFieldNum) - index; } advertisingBytes[endianCorrectedIndex-2] = (byte) (dataField >> (8*(index - this.mDataStartOffsets.get(dataFieldNum))) & 0xff); } } return advertisingBytes; } public BeaconParser setMatchingBeaconTypeCode(Long typeCode) { mMatchingBeaconTypeCode = typeCode; return this; } /** * Caclculates the byte size of the specified identifier in this format * @param identifierNum * @return bytes */ public int getIdentifierByteCount(int identifierNum) { return mIdentifierEndOffsets.get(identifierNum) - mIdentifierStartOffsets.get(identifierNum) + 1; } /** * @return the number of identifiers in this beacon format */ public int getIdentifierCount() { return mIdentifierStartOffsets.size(); } /** * @return the number of data fields in this beacon format */ public int getDataFieldCount() { return mDataStartOffsets.size(); } /** * @return the correction value in dBm to apply to the calibrated txPower to get a 1m calibrated value. * Some formats like Eddystone use a 0m calibrated value, which requires this correction */ public int getPowerCorrection() { return mDBmCorrection; } protected static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; int v; for ( int j = 0; j < bytes.length; j++ ) { v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } public static class BeaconLayoutException extends RuntimeException { public BeaconLayoutException(String s) { super(s); } } public static byte[] longToByteArray(long longValue, int length) { return longToByteArray(longValue, length, true); } public static byte[] longToByteArray(long longValue, int length, boolean bigEndian) { byte[] array = new byte[length]; for (int i = 0; i < length; i++){ int adjustedI = bigEndian ? i : length - i -1; long mask = 0xffl << (length-adjustedI-1)*8; long shift = (length-adjustedI-1)*8; long value = ((longValue & mask) >> shift); array[i] = (byte) value; } return array; } private int calculateLayoutSize() { int lastEndOffset = 0; if (mIdentifierEndOffsets != null) { for (int endOffset : mIdentifierEndOffsets) { if (endOffset > lastEndOffset) { lastEndOffset = endOffset; } } } if (mDataEndOffsets != null) { for (int endOffset : mDataEndOffsets) { if (endOffset > lastEndOffset) { lastEndOffset = endOffset; } } } if (mPowerEndOffset != null && mPowerEndOffset > lastEndOffset ) { lastEndOffset = mPowerEndOffset; } if (mServiceUuidEndOffset != null && mServiceUuidEndOffset > lastEndOffset) { lastEndOffset = mServiceUuidEndOffset; } return lastEndOffset+1; } private boolean byteArraysMatch(byte[] array1, int offset1, byte[] array2, int offset2) { int minSize = array1.length > array2.length ? array2.length : array1.length; for (int i = 0; i < minSize; i++) { if (array1[i+offset1] != array2[i+offset2]) { return false; } } return true; } private String byteArrayToString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { sb.append(String.format("%02x", bytes[i])); sb.append(" "); } return sb.toString().trim(); } private String byteArrayToFormattedString(byte[] byteBuffer, int startIndex, int endIndex, boolean littleEndian) { byte[] bytes = new byte[endIndex-startIndex+1]; if (littleEndian) { for (int i = 0; i <= endIndex-startIndex; i++) { bytes[i] = byteBuffer[startIndex+bytes.length-1-i]; } } else { for (int i = 0; i <= endIndex-startIndex; i++) { bytes[i] = byteBuffer[startIndex+i]; } } int length = endIndex-startIndex +1; // We treat a 1-4 byte number as decimal string if (length < 5) { long number = 0l; for (int i = 0; i < bytes.length; i++) { long byteValue = (long) (bytes[bytes.length - i-1] & 0xff); long positionValue = (long) Math.pow(256.0,i*1.0); long calculatedValue = (byteValue * positionValue); number += calculatedValue; } return Long.toString(number); } // We treat a 7+ byte number as a hex string String hexString = bytesToHex(bytes); // And if it is a 12 byte number we add dashes to it to make it look like a standard UUID if (bytes.length == 16) { StringBuilder sb = new StringBuilder(); sb.append(hexString.substring(0,8)); sb.append("-"); sb.append(hexString.substring(8,12)); sb.append("-"); sb.append(hexString.substring(12,16)); sb.append("-"); sb.append(hexString.substring(16,20)); sb.append("-"); sb.append(hexString.substring(20,32)); return sb.toString(); } return "0x"+hexString; } @TargetApi(Build.VERSION_CODES.GINGERBREAD) private byte[] ensureMaxSize(byte[] array, int requiredLength) { if (array.length >= requiredLength) { return array; } return Arrays.copyOf(array, requiredLength); } }
package org.animotron.graph; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.util.UUID; import org.animotron.MessageDigester; import org.neo4j.graphdb.Relationship; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class BinanyBuilder extends GraphBuilder { private final static File STORAGE = new File(AnimoGraph.STORAGE, "binany"); static { STORAGE.mkdir(); } private InputStream stream; private String path; public BinanyBuilder(InputStream stream, String path) { this.stream = stream; this.path = path; } public Relationship build() { String txID = UUID.randomUUID().toString(); try { File tmp = new File(STORAGE, txID); tmp.createNewFile(); OutputStream out = new FileOutputStream(tmp); byte buf[]=new byte[1024 * 4]; int len; MessageDigest md = md(); while((len=stream.read(buf))>0) { out.write(buf,0,len); md.update(buf,0,len); } String hash = MessageDigester.byteArrayToHex(md.digest()); out.close(); stream.close(); File l1 = new File(STORAGE, hash.substring(1, 3)); File l2 = new File(l1, hash.substring(1, 5)); File bin = new File(l2, hash); if (bin.exists()) { tmp.delete(); System.out.println("File \"" + bin.getPath() + "\" already stored"); } else { l2.mkdirs(); tmp.renameTo(bin); System.out.println("Store the file \"" + bin.getPath() + "\""); } } catch (IOException e) { e.printStackTrace(); } //TODO: Store binary and build graph for one return getRelationship(); } }
package org.animotron.statement.query; import javolution.util.FastList; import javolution.util.FastMap; import javolution.util.FastSet; import javolution.util.FastTable; import org.animotron.graph.index.Order; import org.animotron.io.Pipe; import org.animotron.manipulator.Evaluator; import org.animotron.manipulator.OnContext; import org.animotron.manipulator.OnQuestion; import org.animotron.manipulator.PFlow; import org.animotron.manipulator.QCAVector; import org.animotron.statement.Statement; import org.animotron.statement.Statements; import org.animotron.statement.operator.*; import org.animotron.statement.relation.SHALL; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.graphdb.traversal.Evaluation; import org.neo4j.graphdb.traversal.TraversalDescription; import org.neo4j.kernel.Traversal; import org.neo4j.kernel.Uniqueness; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Set; import static org.neo4j.graphdb.Direction.OUTGOING; import static org.animotron.graph.RelationshipTypes.RESULT; /** * Query operator 'Get'. Return 'have' relations on provided context. * * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> */ public class GET extends AbstractQuery implements Shift { public static final GET _ = new GET(); private static boolean debug = true; private GET() { super("get", "<~"); } protected GET(String... name) { super(name); } public OnQuestion onCalcQuestion() { return new Calc(); } class Calc extends OnQuestion { @Override public void act(final PFlow pf) throws IOException { //if (debug) System.out.println("GET "+Thread.currentThread()); final Relationship op = pf.getOP(); final Node node = op.getEndNode(); final FastSet<Relationship> visitedREFs = FastSet.newInstance(); final FastSet<Node> thes = FastSet.newInstance(); try { Relationship r = null; Pipe p = AN.getREFs(pf, pf.getVector()); QCAVector theNode; while ((theNode = p.take()) != null) { r = theNode.getClosest(); if (r.isType(AN._)) { try { Pipe pp = Utils.eval(pf.getController(), theNode); QCAVector rr; while ((rr = pp.take()) != null) { thes.add(rr.getClosestEndNode()); } } catch (Throwable t) { pf.sendException(t); return; } } else thes.add(r.getEndNode()); } evalGet(pf, op, node, thes, visitedREFs); } finally { FastSet.recycle(thes); FastSet.recycle(visitedREFs); } } private void evalGet( final PFlow pf, final Relationship op, final Node node, final Set<Node> thes, final Set<Relationship> visitedREFs) throws IOException { if (debug) { Utils.debug(GET._, op, thes); } //check, maybe, result was already calculated if (!Utils.results(pf)) { //no pre-calculated result, calculate it OnContext onContext = new OnContext() { @Override public void onMessage(QCAVector vector) { super.onMessage(vector); if (vector == null) return; if (debug) { System.out.println("GET on context "+Thread.currentThread()); System.out.println("GET ["+op+"] vector "+vector); } get(pf, vector, thes, visitedREFs); } }; //pf.answerChannel().subscribe(onContext); if (Utils.haveContext(pf)) { Evaluator.sendQuestion(pf.getController(), onContext, pf.getVector(), node); onContext.isDone(); } else { if (debug) System.out.println("\nGET ["+op+"] empty "); FastSet<QCAVector> refs = FastSet.newInstance(); try { QCAVector vector = pf.getVector(); if (vector.getContext() != null) { for (QCAVector v : vector.getContext()) { refs.add(v); } } // vector = vector.getPrecedingSibling(); // while (vector != null) { // refs.add(vector); // vector = vector.getPrecedingSibling(); get(pf, refs, thes, visitedREFs, false); } finally { FastSet.recycle(refs); } } } }; } public boolean get(PFlow pf, QCAVector vector, final Set<Node> thes, Set<Relationship> visitedREFs) { FastSet<QCAVector> refs = FastSet.newInstance(); try { refs.add(vector); return get(pf, refs, thes, visitedREFs, true); } finally { FastSet.recycle(refs); } } private boolean check( final PFlow pf, final QCAVector v, final Relationship toCheck, final Node middle, final Set<Node> thes, final Set<Relationship> visitedREFs, final boolean onContext) { if (toCheck == null) return false; if (visitedREFs.contains(toCheck)) return false; //if (toCheck.isType(REF._) && visitedREFs.contains(v.getQuestion())) return false; visitedREFs.add(toCheck); if (searchForHAVE(pf, toCheck, v, middle, thes, onContext)) return true; //if (!pf.isInStack(have[i])) { //set.add(new QCAVector(op, v, have[i])); return false; } public boolean get( final PFlow pf, final Set<QCAVector> REFs, final Set<Node> thes, Set<Relationship> visitedREFs, final boolean onContext) { if (visitedREFs == null) visitedREFs = new FastSet<Relationship>(); FastSet<QCAVector> nextREFs = FastSet.newInstance(); FastSet<QCAVector> newREFs = FastSet.newInstance(); FastSet<QCAVector> tmp = null; try { nextREFs.addAll(REFs); boolean found = false; Relationship t = null; while (true) { if (debug) System.out.println("["+pf.getOP()+"] nextREFs "); QCAVector v = null; for (FastSet.Record r = nextREFs.head(), end = nextREFs.tail(); (r = r.getNext()) != end;) { v = nextREFs.valueOf(r); if (debug) System.out.println("checking "+v); if (v.getQuestion() != null && v.hasAnswer()) { Node middle = null; Statement s = Statements.relationshipType(v.getQuestion()); if (s instanceof ANY) { try { middle = v.getQuestion().getEndNode().getSingleRelationship(REF._, OUTGOING).getEndNode(); } catch (Exception e) { e.printStackTrace(); } } if (!check(pf, v, v.getUnrelaxedAnswer(), middle, thes, visitedREFs, onContext)) { if (v.getAnswers() != null) for (QCAVector vv : v.getAnswers()) { if (check(pf, v, vv.getUnrelaxedAnswer(), middle, thes, visitedREFs, onContext)) found = true; } } else { found = true; } } visitedREFs.add(v.getQuestion()); } if (found) return true; for (FastSet.Record r = nextREFs.head(), end = nextREFs.tail(); (r = r.getNext()) != end;) { v = nextREFs.valueOf(r); List<QCAVector> cs = v.getContext(); if (cs != null) { for (QCAVector c : cs) { checkVector(c, newREFs, visitedREFs); } } t = v.getUnrelaxedAnswer(); if (t != null && !t.equals(v.getQuestion())) { if (! t.isType(AN._)) getOutgoingReferences(pf, v, t, t.getStartNode(), newREFs, visitedREFs); getOutgoingReferences(pf, v, t, t.getEndNode(), newREFs, visitedREFs); } } if (newREFs.size() == 0) return false; //swap tmp = nextREFs; nextREFs = newREFs; newREFs = tmp; newREFs.clear(); } } finally { FastSet.recycle(nextREFs); FastSet.recycle(newREFs); } } private void checkVector(final QCAVector c, final Set<QCAVector> newREFs, final Set<Relationship> visitedREFs) { Relationship t = c.getUnrelaxedAnswer(); if (t != null && !visitedREFs.contains(t)) newREFs.add(c); else { t = c.getQuestion(); if (!visitedREFs.contains(t)) newREFs.add(c); } } private void getOutgoingReferences(PFlow pf, QCAVector vector, Relationship rr, Node node, Set<QCAVector> newREFs, Set<Relationship> visitedREFs) { QCAVector prev = null; IndexHits<Relationship> it = Order._.context(node); try { for (Relationship r : it) { if (visitedREFs != null && visitedREFs.contains(r)) { continue; } prev = vector.question(r, prev); Statement st = Statements.relationshipType(r); if (st instanceof AN) { Pipe p = AN.getREFs(pf, prev); QCAVector v; while ((v = p.take()) != null) { Relationship t = v.getClosest(); prev.addAnswer(v); if (visitedREFs != null && !visitedREFs.contains(t)) { newREFs.add(v); } } } else if (st instanceof Reference) { // if (!pf.isInStack(r)) { //System.out.println("["+pf.getOP()+"] evaluate "+prev); Pipe in = Evaluator._.execute(pf.getController(), prev); QCAVector v; while ((v = in.take()) != null) { prev.addAnswer(v); if (visitedREFs != null && !visitedREFs.contains(v.getAnswer())) newREFs.add(v); } } } } catch (Throwable t) { pf.sendException(t); } finally { it.close(); } } private boolean searchForHAVE( final PFlow pf, final Relationship ref, final QCAVector v, final Node middle, final Set<Node> thes, final boolean onContext) { //search for inside 'HAVE' //return searchForHAVE(pf, ref, ref.getEndNode(), thes); if (getByHave(pf, v, ref, THE._.getActualEndNode(ref), middle, thes, onContext)) return true; //search for local 'HAVE' if (ref.isType(REF._)) { if (getByHave(pf, v, v.getQuestion(), ref.getStartNode(), middle, thes, onContext)) return true; } return false; } private boolean relaxReference(PFlow pf, QCAVector vector, Relationship op) { try{ if (!(op.isType(ANY._) || op.isType(GET._))) { if (debug) System.out.println("["+pf.getOP()+"] answered "+op); pf.sendAnswer(pf.getVector().answered(op, vector), RESULT); //pf.sendAnswer(op); return true; } if (debug) System.out.println("["+pf.getOP()+"] Relaxing "+op+" @ "+vector); try { Pipe in = Evaluator._.execute(pf.getController(), vector.question(op)); //if (!in.hasNext()) return false; boolean answered = false; Relationship res = null; QCAVector v; while ((v = in.take()) != null) { res = v.getAnswer(); if (!pf.isInStack(res)) { if (debug) System.out.println("["+pf.getOP()+"] Relaxing answered "+v.getAnswer()); pf.sendAnswer(vector.answered(v.getAnswer(), v), RESULT); answered = true; } } return answered; } catch (IOException e) { pf.sendException(e); } } catch (Throwable t) { pf.sendException(t); } return false; } private boolean haveMiddle(Path path, Node middle) { for (Node n : path.nodes()) { if (n.equals(middle)) return true; } return false; } private static TraversalDescription prepared = Traversal.description(). depthFirst(). uniqueness(Uniqueness.RELATIONSHIP_PATH). relationships(ANY._, OUTGOING). relationships(AN._, OUTGOING). relationships(REF._, OUTGOING). relationships(GET._, OUTGOING). relationships(SHALL._, OUTGOING); private boolean getByHave( final PFlow pf, QCAVector vector, Relationship op, final Node context, final Node middle, final Set<Node> thes, final boolean onContext) { if (context == null) return false; System.out.println("middle "+middle); TraversalDescription trav = prepared. evaluator(new Searcher(){ @Override public Evaluation evaluate(Path path) { return _evaluate_(path, thes); } }); FastMap<Relationship, List<Path>> paths = FastMap.newInstance(); try { boolean middlePresent = false; List<Path> l; for (Path path : trav.traverse(context)) { if (debug) System.out.println("["+pf.getOP()+"] * "+path); if (path.length() == 1) { if (op == null) { System.out.println("WARNING: DONT KNOW OP"); continue; } if (pf.getOP().equals(op)) continue; l = new FastList<Path>(); l.add(path); paths.put(op, l); continue; } if (path.length() == 2) { //UNDERSTAND: should we check context Relationship r = path.relationships().iterator().next(); if (pf.getVector().getQuestion().getId() == r.getId()) continue; if (relaxReference(pf, vector, r)) return true; } Relationship fR = path.relationships().iterator().next(); List<Path> ps = paths.get(fR); if (ps == null) {// || p.length() > path.length()) { boolean thisMiddle = haveMiddle(path, middle); if (middlePresent) { if (thisMiddle) { l = new FastList<Path>(); l.add(path); paths.put(fR, l); } } else { if (thisMiddle) { middlePresent = thisMiddle; paths.clear(); } l = new FastList<Path>(); l.add(path); paths.put(fR, l); } } else { l = paths.get(fR); if (l.get(0).length() > path.length()) { middlePresent = haveMiddle(path, middle); l.clear(); l.add(path); } else if (l.get(0).length() == path.length()) { boolean thisMiddle = haveMiddle(path, middle); if (middlePresent) { if (thisMiddle) l.add(path); } else { if (thisMiddle) { middlePresent = thisMiddle; l.clear(); l.add(path); } else { l.add(path); } } } } } if (paths.isEmpty()) return false; Relationship startBy = null; int refs = 0; int ANs = 0; //if (op.isType(RESULT)) ANs++; Relationship res = null; Relationship prevRes = null; Relationship prevPrevRes = null; FastTable<Relationship> resByHAVE = FastTable.newInstance(); FastTable<Relationship> resByIS = FastTable.newInstance(); try { for (List<Path> ps : paths.values()) { for (Path path : ps) { res = null; prevRes = null; prevPrevRes = null; if (path.length() == 1 && path.lastRelationship().isType(REF._)) { res = op; } else { Iterator<Relationship> it = path.relationships().iterator(); for (Relationship r = null; it.hasNext(); ) { r = it.next(); if (startBy == null) startBy = r; if (!pf.isInStack(r)) { if (r.isType(AN._)) { res = r; ANs++; } else { if (ANs > 1) { //check is it pseudo HAVE or IS topology. on HAVE return it else last of top if (r.isType(REF._) && it.hasNext()) { r = it.next(); if (r.isType(AN._) && Utils.haveContext(r.getEndNode())) res = r; } break; } ANs = 0; if (r.isType(ANY._)) { if (it.hasNext() && it.next().isType(REF._) && !it.hasNext()) { res = r; } else { res = null; } break; } else if (r.isType(GET._)) { if (it.hasNext()) if (it.next().isType(REF._) && !it.hasNext()) res = r; break; } else if (r.isType(SHALL._)) { res = r; } else if (r.isType(REF._)) { //ignore pseudo IS if (Utils.haveContext(r.getStartNode())) { prevRes = null; if (onContext) break; else if (refs > 1) break; refs++; } else { prevPrevRes = prevRes; prevRes = res; } } } } } } if (prevPrevRes != null) res = prevPrevRes; if (res != null) { if (startBy != null && startBy.isType(REF._)) resByIS.add(res); else resByHAVE.add(res); } startBy = null; } } if (!resByHAVE.isEmpty()) { for (Relationship r : resByHAVE) { relaxReference(pf, vector, r); } } else { if (resByIS.isEmpty()) return false; for (Relationship r : resByIS) { relaxReference(pf, vector, r); } } } finally{ FastTable.recycle(resByHAVE); FastTable.recycle(resByIS); } return true; } finally { FastMap.recycle(paths); } } }
package ahlers.phantom.embedded; import com.google.auto.value.AutoValue; import de.flapdoodle.embed.process.distribution.Distribution; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.concurrent.ConcurrentException; import org.apache.commons.lang3.concurrent.LazyInitializer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author [[mailto:michael@ahlers.consulting Michael Ahlers]] */ @AutoValue public abstract class PhantomSignature implements IPhantomSignature { @Override abstract public Distribution distribution(); @Override abstract public String algorithm(); @Override @SuppressWarnings("mutable") abstract public byte[] digest(); @Override public byte[] digest(final File file) throws IOException { final InputStream stream = new FileInputStream(file); try { final MessageDigest digest = DigestUtils.getDigest(algorithm()); DigestUtils.updateDigest(digest, stream); return digest.digest(); } finally { stream.close(); } } @Override public String toString() { return new ToStringBuilder(this) .append("distribution", distribution()) .append("algorithm", algorithm()) .append("digest", new BigInteger(digest()).toString(16)) .toString(); } static Builder builder() { return new AutoValue_PhantomSignature.Builder(); } @AutoValue.Builder abstract static class Builder { abstract Builder distribution(Distribution value); abstract Builder algorithm(String value); abstract Builder digest(byte[] value); abstract PhantomSignature build(); } private static Map<String, byte[]> getDigests() throws Exception { final InputStream source = PhantomSignature.class.getResourceAsStream("/ahlers/phantom/embedded/SHA256SUMS"); final List<String> lines = IOUtils.readLines(source); source.close(); final Map<String, byte[]> byName = new HashMap<>(); for (final String line : lines) { final String[] parts = line.split("\\s+"); if (2 == parts.length) { final String name = parts[1].trim(); final byte[] digest = Hex.decodeHex(parts[0].toCharArray()); byName.put(name, digest); } } return byName; } /* TODO: Make generic for other signature types as needed. */ private static LazyInitializer<Map<String, byte[]>> digestByName = new LazyInitializer<Map<String, byte[]>>() { @Override protected Map<String, byte[]> initialize() throws ConcurrentException { try { return getDigests(); } catch (final Exception e) { throw new ConcurrentException(e); } } }; public static IPhantomSignature byDistribution(final Distribution distribution) { final String name = PhantomPackageResolver.archivePathFor(distribution); final byte[] digest; try { digest = digestByName.get().get(name); } catch (final Exception e) { throw new IllegalStateException("Couldn't load digests.", e); } if (null == digest) { throw new IllegalArgumentException(String.format("No signature available for \"%s\".", distribution)); } return builder() .distribution(distribution) .algorithm("SHA-256") .digest(Arrays.copyOf(digest, digest.length)) .build(); } }
package broadwick.stochastic; import com.google.common.collect.Table; import com.google.common.collect.TreeBasedTable; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Slf4j public abstract class StochasticSimulator { /** * Creates a new simulator using a given amount manager. * @param amountManager the amount manager used in the simulator. * @param transitionKernel the transition kernel to be used with the stochastic solver. */ public StochasticSimulator(final AmountManager amountManager, final TransitionKernel transitionKernel) { this(amountManager, transitionKernel, false); } /** * Creates a new simulator. * @param amountManager the amount manager used in the simulator. * @param transitionKernel the transition kernel to be used with the stochastic solver. * @param reverseTime true if we wish to go backwards in time. */ public StochasticSimulator(final AmountManager amountManager, final TransitionKernel transitionKernel, final boolean reverseTime) { this.amountManager = amountManager; this.transitionKernel = transitionKernel; this.reverseTime = reverseTime; this.thetaQueue = new ThetaQueue(); } /** * Starts the simulation up to a given time. It just uses a {@link DefaultController} and calls * {@link StochasticSimulator#start(SimulationController)}. * @param time simulation time */ public final void start(final double time) { if (controller == null) { controller = new DefaultController(time); } start(); } /** * Start the simulation with the given {@link SimulationController}. */ public final void start() { // If we haven't set a controller for the process then set the default one with a max time of 5 // (unknonw units). if (controller == null) { controller = new DefaultController(5); } init(); // tell our observers that the simulation has started for (Observer observer : observers) { observer.started(); } while (controller.goOn(this)) { // The performStep() method is implemented by the specifc stochastic algorithm (e.g. Gillespie's) performStep(); // tell our observers that the step has been completed. for (Observer observer : observers) { observer.step(); } } // tell our observers that the simulation has finished. for (Observer observer : observers) { observer.finished(); } } /** * Initializes the algorithm. <ul><li>set currentTime=0</li><li>reset the {@link AmountManager}</li><li>recalculate * the propensities</li></ul> Gets called at the very beginning of * <code>start</code> */ public final void init() { currentTime = startTime; } /** * Fires a reaction. It calls the observers and the {@link AmountManager}. * @param mu reaction to be fired. * @param t time at which the firing occurs. */ protected final void doEvent(final SimulationEvent mu, final double t) { doEvent(mu, t, 1); } /** * Perform an event by informing the subscribed observers and the amountManager. * @param event event to be performed. * @param t time at which the firing occurs. * @param n the number of times mu is to be fired. */ protected final void doEvent(final SimulationEvent event, final double t, final int n) { log.trace("Performing event {}", event); for (Observer observer : observers) { observer.performEvent(event, t, n); } // change the amount of the reactants if (!Double.isInfinite(t)) { amountManager.performEvent(event, n); } } /** * Gets called when the simulator reaches the predetermined time of a theta event. All the observers for the events * that are configured for this time are notified and given a list of events that are triggered. */ protected final void doThetaEvent() { final double nextThetaEventTime = thetaQueue.getNextThetaEventTime(); log.trace("Performing theta events at t = {}", nextThetaEventTime); final Map<Observer, Collection<Object>> nextEvents = thetaQueue.getNextEventDataAndRemove(); for (Map.Entry<Observer, Collection<Object>> entry : nextEvents.entrySet()) { final Observer observer = entry.getKey(); final Collection<Object> events = entry.getValue(); if (events != null) { log.trace("Informing observer of theta events {}", events.toString()); observer.theta(nextThetaEventTime, events); } } log.trace("Finished theta events next = {}", thetaQueue.getNextThetaEventTime()); } /** * Add an observer to the engines list of observers. * @param observer the observer. */ public final void addObserver(final Observer observer) { if (observer.getProcess() != this) { throw new IllegalArgumentException("Observer doesn't belong to this simulator!"); } this.getObservers().add(observer); } /** * Theta defines a moment, where the simulator has to invoke <TT>theta</TT> of a observers. It is used e.g. to * determine the amounts of species at one moments. Extending class just have to call * {@link Simulator#doThetaEvent()} which basically calls the observers. * @return the theta */ public final double getNextThetaEventTime() { return thetaQueue.getNextThetaEventTime(); } /** * Register a new theta event that is triggered at a given time. * @param obs the observers which is registering. * @param thetaTime the time the theta event occurs. * @param event the theta event. */ public final void registerNewTheta(final Observer obs, final double thetaTime, final Object event) { thetaQueue.pushTheta(thetaTime, obs, event); } /** * Get the default observer for the stochastic process. The default observer is first one defined. * @return the default observer. */ public final Observer getDefaultObserver() { return observers.toArray(new Observer[observers.size()])[0]; } /** * Manages the registered theta events. Each registered theta event is stored in a table containing the time of the * event the list of observers for that event and the list of events for that time. */ private class ThetaQueue { /** * Construct an empty theta queue. */ public ThetaQueue() { thetas = TreeBasedTable.create(); if (reverseTime) { nextThetaEventTime = Double.NEGATIVE_INFINITY; } else { nextThetaEventTime = Double.POSITIVE_INFINITY; } } /** * Add a new theta event to the registry, including the time, collection of observers and collection of events. * Each event is stored as an object where it is assumed that the observer * @param time the time the theta event occurs. * @param obs the observers. * @param theta the theta event. */ public void pushTheta(final double time, final Observer obs, final Object theta) { log.trace("Adding new theta event {} at t={}", theta, time); Collection<Object> events = thetas.get(time, obs); if (events == null) { try { log.trace("No theta events registered at t={}; Creating new list", time); events = new HashSet<>(); events.add(theta); thetas.put(time, obs, events); } catch (UnsupportedOperationException | ClassCastException | IllegalArgumentException | IllegalStateException e) { log.error("Could not register theta. {}", e.getLocalizedMessage()); } } else { log.trace("Found {} theta events for t={}; Adding new event", events.size(), time); events.add(theta); } if (reverseTime) { nextThetaEventTime = Math.max(nextThetaEventTime, time); } else { nextThetaEventTime = Math.min(nextThetaEventTime, time); } } /** * Get the next observer and the collection of events they are subscribed to and remove it from the theta queue. * @return a map of the observers and their subscribed data. */ public Map<Observer, Collection<Object>> getNextEventDataAndRemove() { final Map<Observer, Collection<Object>> nextEventData = thetas.row(nextThetaEventTime); // we have a view of the underlying data that we want to return, copy it first then delete the // underlying data. final Map<Observer, Collection<Object>> eventData = new HashMap<>(nextEventData); log.trace("Found {} configured events and observers at t={}", eventData.size(), nextThetaEventTime); for (Observer obs : eventData.keySet()) { final Collection<Object> removed = thetas.remove(nextThetaEventTime, obs); log.trace("Removed {} items from registered theta list", removed.size()); } // Now we need to update the nextThetaEventTime if (reverseTime) { if (thetas.rowKeySet().isEmpty()) { nextThetaEventTime = Double.NEGATIVE_INFINITY; } else { nextThetaEventTime = Collections.max(thetas.rowKeySet()); } } else { if (thetas.rowKeySet().isEmpty()) { nextThetaEventTime = Double.POSITIVE_INFINITY; } else { nextThetaEventTime = Collections.min(thetas.rowKeySet()); } } return eventData; } @Getter private Table<Double, Observer, Collection<Object>> thetas; @Getter private double nextThetaEventTime; } /** * Reset propensities when a event has been executed. */ public abstract void reinitialize(); /** * Performs one simulation step. Between steps the terminating condition is checked. The simulators controller is * passed, if an extending class wants to check it within one step. Implementing algorithms cannot be sure that the * propensities are correct at the beginning of a step (e.g. if the volume changed). They should override * {@link Simulator#setAmount(int, long)} and {@link Simulator#setVolume(double)} if they need correct values! */ public abstract void performStep(); /** * Gets the name of the algorithm. * @return name of the algorithm */ public abstract String getName(); /** * Seed the RNG if required. * @param seed the RNG seed. */ public abstract void setRngSeed(final int seed); @Setter private int startTime = 0; @Setter @Getter private TransitionKernel transitionKernel; @Getter private AmountManager amountManager; @Setter @Getter private double currentTime = 0; @Getter @Setter private SimulationController controller = null; private ThetaQueue thetaQueue = new ThetaQueue(); @Getter private Set<Observer> observers = new HashSet<>(1); protected boolean reverseTime = false; }
package ch.lambdaj.function.closure; import static ch.lambdaj.function.closure.ClosuresFactory.*; import java.lang.reflect.*; import ch.lambdaj.proxy.*; public class ProxyClosure extends InvocationInterceptor { private Closure closure; protected ProxyClosure(Closure closure) { this.closure = closure; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { closure.registerInvocation(method, args); return createProxyClosure(closure, method.getReturnType()); } }
package cn.momia.mapi.api.activity; import cn.momia.api.course.ActivityServiceApi; import cn.momia.api.course.activity.Activity; import cn.momia.api.user.SmsServiceApi; import cn.momia.common.core.http.MomiaHttpResponse; import cn.momia.common.core.util.MomiaUtil; import cn.momia.mapi.api.AbstractApi; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/v1/activity") public class ActivityV1Api extends AbstractApi { private static final Logger LOGGER = LoggerFactory.getLogger(ActivityV1Api.class); @Autowired private ActivityServiceApi activityServiceApi; @Autowired private SmsServiceApi smsServiceApi; @RequestMapping(method = RequestMethod.GET) public MomiaHttpResponse get(@RequestParam int id) { if (id <= 0) return MomiaHttpResponse.FAILED("ID"); Activity activity = activityServiceApi.get(id); activity.setCover(completeSmallImg(activity.getCover())); return MomiaHttpResponse.SUCCESS(activity); } @RequestMapping(value = "/join", method = RequestMethod.POST) public MomiaHttpResponse join(@RequestParam(value = "aid") int activityId, @RequestParam String mobile, @RequestParam(value = "cname") String childName, @RequestParam(required = false, defaultValue = "") String relation) { if (activityId <= 0) return MomiaHttpResponse.FAILED(""); if (MomiaUtil.isInvalidMobile(mobile)) return MomiaHttpResponse.FAILED(""); if (StringUtils.isBlank(childName)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS(activityServiceApi.join(activityId, mobile, childName, relation)); } @RequestMapping(value = "/notify", method = RequestMethod.POST) public MomiaHttpResponse notify(@RequestParam(value = "aid") int activityId, @RequestParam String mobile) { if (activityId <= 0) return MomiaHttpResponse.FAILED(""); if (MomiaUtil.isInvalidMobile(mobile)) return MomiaHttpResponse.FAILED(""); Activity activity = activityServiceApi.get(activityId); if (!activity.exists()) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS(smsServiceApi.notify(mobile, activity.getMessage())); } @RequestMapping(value = "/prepay/alipay", method = RequestMethod.POST) public MomiaHttpResponse prepayAlipay(@RequestParam(value = "eid") long entryId, @RequestParam(defaultValue = "app") String type) { if (entryId <= 0) return MomiaHttpResponse.FAILED("ID"); if (StringUtils.isBlank(type)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS(activityServiceApi.prepayAlipay(entryId, type)); } @RequestMapping(value = "/prepay/weixin", method = RequestMethod.POST) public MomiaHttpResponse prepayWeixin(@RequestParam(value = "eid") long entryId, @RequestParam(defaultValue = "app") final String type, @RequestParam(required = false) String code) { if (entryId <= 0) return MomiaHttpResponse.FAILED("ID"); if (StringUtils.isBlank(type)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS(activityServiceApi.prepayWeixin(entryId, type, code)); } @RequestMapping(value = "/check", method = RequestMethod.POST) public MomiaHttpResponse check(@RequestParam(value = "eid") long entryId) { if (entryId <= 0) return MomiaHttpResponse.FAILED("ID"); return MomiaHttpResponse.SUCCESS(activityServiceApi.checkPayment(entryId)); } }
package org.generator.make; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FilenameUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.generator.config.PropertyHolder; import org.generator.db.ConnectionFactory; import org.generator.entity.Column; import org.generator.entity.Table; import org.generator.type.DBType; import org.generator.type.JdbcTypeNameTranslator; import org.generator.type.SourceType; import org.generator.util.StringUtility; /** * * @author yangziran * @version 1.0 20141116 */ public class GetTableConfig { private final static String SOURCE_TYPE = SourceType.valueOf(PropertyHolder.getJDBCProperty("SourceType")) .getValue(); private final static String DB_TYPE = DBType.valueOf(PropertyHolder.getJDBCProperty("DB")).getValue(); /** * * @return * @throws SQLException * @author yangziran */ public static List<Table> getTableConfig() throws Exception { if (SourceType.DB.getValue().equals(SOURCE_TYPE)) { return getDBTableConfig(); } else { return getExcelTableConfig(); } } /** * * @return * @throws SQLException * @author yangziran */ public static List<Table> getDBTableConfig() throws SQLException { Connection connection = ConnectionFactory.getConnection(); String model = PropertyHolder.getConfigProperty("model"); StringBuilder tableName = new StringBuilder(); if (StringUtility.isNotEmpty(model)) { tableName.append(model).append("_"); } String tablec = PropertyHolder.getConfigProperty("table"); if (StringUtility.isNotEmpty(tablec)) { tableName.append(tablec); } else { tableName.append("%"); } DatabaseMetaData metaData = connection.getMetaData(); ResultSet tables = metaData.getTables( connection.getCatalog(), metaData.getUserName(), DB_TYPE.equals(DBType.ORACLE.getValue()) ? tableName.toString().toUpperCase() : tableName.toString().toLowerCase(), new String[] { "TABLE" }); List<Table> tableList = new ArrayList<Table>(); while (tables.next()) { Table table = new Table(); String TABLE_NAME = tables.getString("TABLE_NAME"); String REMARKS = tables.getString("REMARKS"); table.setTableName(TABLE_NAME); table.setJavaName(StringUtility.convertTableNameToClass(TABLE_NAME.toLowerCase(), "_", false)); table.setRemarks(REMARKS); ResultSet key = metaData.getPrimaryKeys(connection.getCatalog(), metaData.getUserName(), TABLE_NAME); while (key.next()) { Column column = new Column(); String COLUMN_NAME = key.getString("COLUMN_NAME"); if (COLUMN_NAME.indexOf("‘") == 0 && COLUMN_NAME.lastIndexOf("’") > 1) { COLUMN_NAME = COLUMN_NAME.substring(1, COLUMN_NAME.length() - 1); } column.setColumnName(COLUMN_NAME); column.setJavaName(StringUtility.convertFieldToParameter(COLUMN_NAME.toLowerCase(), "_")); column.setPrimaryKeyOrder(String.valueOf(key.getRow())); table.addPrimaryKey(column); } ResultSet exp = metaData.getExportedKeys(connection.getCatalog(), metaData.getUserName(), TABLE_NAME); while (exp.next()) { Column column = new Column(); String PKCOLUMN_NAME = exp.getString("PKCOLUMN_NAME"); if (PKCOLUMN_NAME.indexOf("‘") == 0 && PKCOLUMN_NAME.lastIndexOf("’") > 1) { PKCOLUMN_NAME = PKCOLUMN_NAME.substring(1, PKCOLUMN_NAME.length() - 1); } String COLUMN_NAME = exp.getString("COLUMN_NAME"); if (COLUMN_NAME.indexOf("‘") == 0 && COLUMN_NAME.lastIndexOf("’") > 1) { COLUMN_NAME = COLUMN_NAME.substring(1, COLUMN_NAME.length() - 1); } column.setColumnName(PKCOLUMN_NAME); column.setJavaName(StringUtility.convertFieldToParameter(COLUMN_NAME.toLowerCase(), "_")); table.addExportedKey(column); } ResultSet columns = metaData.getColumns(connection.getCatalog(), metaData.getUserName(), TABLE_NAME, null); while (columns.next()) { Column column = new Column(); String COLUMN_NAME = columns.getString("COLUMN_NAME"); if (COLUMN_NAME.indexOf("‘") == 0 && COLUMN_NAME.lastIndexOf("’") > 1) { COLUMN_NAME = COLUMN_NAME.substring(1, COLUMN_NAME.length() - 1); } column.setSerial(String.valueOf(columns.getRow())); column.setColumnName(COLUMN_NAME); column.setJavaName(StringUtility.convertFieldToParameter(COLUMN_NAME.toLowerCase(), "_")); column.setSqlType(JdbcTypeNameTranslator.getJdbcTypeName(columns.getInt("DATA_TYPE"))); column.setJavaType(JdbcTypeNameTranslator.getJavaType(columns.getInt("DATA_TYPE"))); column.setRemarks(columns.getString("REMARKS")); column.setIsNotNull(columns.getString("IS_NULLABLE")); column.setLength(columns.getInt("COLUMN_SIZE")); table.addCols(column); } tableList.add(table); } for (Table table : tableList) { for (Column column1 : table.getPrimaryKey()) { for (Column column2 : table.getCols()) { if (column1.getJavaName().equals(column2.getJavaName())) { column1.setJavaType(column2.getJavaType()); column1.setSqlType(column2.getSqlType()); column1.setRemarks(column2.getRemarks()); } } } } return tableList; } /** * Excel * @return * @author yangziran * @throws Exception */ public static List<Table> getExcelTableConfig() throws Exception { Workbook wb = null; InputStream is = null; try { File file = new File(PropertyHolder.getJDBCProperty("path.dictionary")); if (file.exists()) { String ext = FilenameUtils.getExtension(file.getName()); // 2007 boolean xlsx = ext.equals("xlsx"); is = new FileInputStream(file); // 2007 XSSFWorkbook95~2003HSSFWorkbook wb = xlsx ? new XSSFWorkbook(is) : new HSSFWorkbook(is); } } catch (FileNotFoundException e) { throw new Exception(e); } catch (IOException e) { throw new Exception(e); } finally { if (wb != null) { wb.close(); } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } List<Table> tableList = new ArrayList<Table>(); // Sheet for (int i = 2; i < wb.getNumberOfSheets(); i++) { // Sheet Sheet sheet = wb.getSheetAt(i); String TABLE_NAME = sheet.getRow(1).getCell(3).getStringCellValue(); String REMARKS = sheet.getRow(0).getCell(3).getStringCellValue(); Table table = new Table(); table.setTableName(TABLE_NAME); table.setJavaName(StringUtility.convertTableNameToClass(TABLE_NAME.toLowerCase(), "_", false)); table.setRemarks(REMARKS); // Sheet1 for (int j = 5; j < sheet.getPhysicalNumberOfRows(); j++) { Row row = sheet.getRow(j); String serial = String.valueOf(row.getCell(0).getNumericCellValue()); String columnName = row.getCell(4).getStringCellValue(); String physical = row.getCell(1).getStringCellValue(); String type = row.getCell(8).getStringCellValue().toUpperCase(); String isNotNull = row.getCell(13).getStringCellValue(); String primaryKey = row.getCell(15).getStringCellValue(); String primaryKeyOrder = String.valueOf(row.getCell(17).getNumericCellValue()); String foreignKey = row.getCell(18).getStringCellValue(); // String remarks = row.getCell(21).getStringCellValue(); Integer length = null; Cell cell = row.getCell(11); if (JdbcTypeNameTranslator.getJdbcTypeName(Types.VARCHAR) .equals(JdbcTypeNameTranslator.getJdbcType(type))) { length = (int) cell.getNumericCellValue(); } Column column = new Column(); column.setSerial(serial); column.setColumnName(columnName); column.setJavaName(StringUtility.convertFieldToParameter(columnName.toLowerCase(), "_")); column.setSqlType(JdbcTypeNameTranslator.getJdbcTypeName(JdbcTypeNameTranslator.getJdbcType(type))); column.setJavaType(JdbcTypeNameTranslator.getJavaType(type)); column.setRemarks(physical); column.setIsNotNull(isNotNull); column.setPrimaryKeyOrder(primaryKeyOrder); column.setForeignKey(foreignKey); column.setLength(length); if (StringUtility.isNotEmpty(primaryKey)) { table.addPrimaryKey(column); } table.addCols(column); } tableList.add(table); } return tableList; } }
package org.jsoup.select.ng.parser; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.jsoup.Jsoup; import org.jsoup.helper.StringUtil; import org.jsoup.helper.Validate; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Evaluator; import org.jsoup.parser.TokenQueue; import org.jsoup.select.ng.AndSelector; import org.jsoup.select.ng.BasicSelector; import org.jsoup.select.ng.HasSelector; import org.jsoup.select.ng.ImmediateParentSelector; import org.jsoup.select.ng.NotSelector; import org.jsoup.select.ng.OrSelector; import org.jsoup.select.ng.ParentSelector; import org.jsoup.select.ng.PrevSiblingSelector; import org.jsoup.select.ng.PreviousSequentSiblingSelector; import org.jsoup.select.ng.SelectMatch; public class Parser { TokenQueue tq; private final static String[] combinators = {",", ">", "+", "~", " "}; String query; //Deque<Evaluator> s = new ArrayDeque<Evaluator>(); List<Evaluator> s = new ArrayList<Evaluator>(); public Parser(String query) { this.query = query; this.tq = new TokenQueue(query); } public static Evaluator parse(String query) { Parser p = new Parser(query); return p.parse(); } public Evaluator parse() { tq.consumeWhitespace(); if (tq.matchesAny(combinators)) { // if starts with a combinator, use root as elements //elements.add(root); combinator(tq.consume()); } else if (tq.matches(":has(")) { //elements.addAll(root.getAllElements()); } else { //addElements(findElements()); // chomp first element matcher off queue findElements(); } while (!tq.isEmpty()) { // hierarchy and extras boolean seenWhite = tq.consumeWhitespace(); if (tq.matchChomp(",")) { // group or OrSelector or = new OrSelector(s); s.clear(); //s.push(or); s.add(or); while (!tq.isEmpty()) { String subQuery = tq.chompTo(","); or.add(parse(subQuery)); } } else if (tq.matchesAny(combinators)) { combinator(tq.consume()); } else if (seenWhite) { combinator(' '); } else { // E.class, E#id, E[attr] etc. AND findElements(); // take next el, #. etc off queue } } if(s.size() == 1) return s.get(0); return new AndSelector(s); } private void combinator(char combinator) { tq.consumeWhitespace(); String subQuery = tq.consumeToAny(combinators); // support multi > childs Evaluator e = null; if(s.size() == 1) e = s.get(0); else { e = new AndSelector(s); } s.clear(); Evaluator f = parse(subQuery); if (combinator == '>') { s.add(BasicSelector.and(f, new ImmediateParentSelector(e))); } else if (combinator == ' ') { s.add(BasicSelector.and(f, new ParentSelector(e))); } else if (combinator == '+') { s.add(BasicSelector.and(f, new PrevSiblingSelector(e))); } else if (combinator == '~') { s.add(BasicSelector.and(f, new PreviousSequentSiblingSelector(e))); } else throw new IllegalStateException("Unknown combinator: " + combinator); } private void findElements() { if (tq.matchChomp(" byId(); } else if (tq.matchChomp(".")) { byClass(); } else if (tq.matchesWord()) { byTag(); } else if (tq.matches("[")) { byAttribute(); } else if (tq.matchChomp("*")) { allElements(); } else if (tq.matchChomp(":lt(")) { indexLessThan(); } else if (tq.matchChomp(":gt(")) { indexGreaterThan(); } else if (tq.matchChomp(":eq(")) { indexEquals(); } else if (tq.matches(":has(")) { has(); } else if (tq.matches(":contains(")) { contains(false); } else if (tq.matches(":containsOwn(")) { contains(true); } else if (tq.matches(":matches(")) { matches(false); } else if (tq.matches(":matchesOwn(")) { matches(true); } else if (tq.matches(":not(")) { not(); } else { // unhandled throw new SelectorParseException("Could not parse query '%s': unexpected token at '%s'", query, tq.remainder()); } } private void byId() { String id = tq.consumeCssIdentifier(); Validate.notEmpty(id); ecPush(new Evaluator.Id(id)); } private void byClass() { String className = tq.consumeCssIdentifier(); Validate.notEmpty(className); ecPush(new Evaluator.Class(className)); } private void byTag() { String tagName = tq.consumeElementSelector(); Validate.notEmpty(tagName); // namespaces: if element name is "abc:def", selector must be "abc|def", so flip: if (tagName.contains("|")) tagName = tagName.replace("|", ":"); ecPush(new Evaluator.Tag(tagName)); } private void byAttribute() { TokenQueue cq = new TokenQueue(tq.chompBalanced('[', ']')); // content queue String key = cq.consumeToAny("=", "!=", "^=", "$=", "*=", "~="); // eq, not, start, end, contain, match, (no val) Validate.notEmpty(key); cq.consumeWhitespace(); if (cq.isEmpty()) { if(key.startsWith("^")) ecPush(new Evaluator.AttributeStarting(key.substring(1))); else ecPush(new Evaluator.Attribute(key)); } else { if (cq.matchChomp("=")) ecPush(new Evaluator.AttributeWithValue(key, cq.remainder())); else if (cq.matchChomp("!=")) ecPush(new Evaluator.AttributeWithValueNot(key, cq.remainder())); else if (cq.matchChomp("^=")) ecPush(new Evaluator.AttributeWithValueStarting(key, cq.remainder())); else if (cq.matchChomp("$=")) ecPush(new Evaluator.AttributeWithValueEnding(key, cq.remainder())); else if (cq.matchChomp("*=")) ecPush(new Evaluator.AttributeWithValueContaining(key, cq.remainder())); else if (cq.matchChomp("~=")) ecPush(new Evaluator.AttributeWithValueMatching(key, Pattern.compile(cq.remainder()))); else throw new SelectorParseException("Could not parse attribute query '%s': unexpected token at '%s'", query, cq.remainder()); } } private void allElements() { //return root.getAllElements(); // TODO: add all parsing } // pseudo selectors :lt, :gt, :eq private void indexLessThan() { ecPush(new Evaluator.IndexLessThan(consumeIndex())); } private void indexGreaterThan() { ecPush(new Evaluator.IndexGreaterThan(consumeIndex())); } private void indexEquals() { ecPush(new Evaluator.IndexEquals(consumeIndex())); } private int consumeIndex() { String indexS = tq.chompTo(")").trim(); Validate.isTrue(StringUtil.isNumeric(indexS), "Index must be numeric"); return Integer.parseInt(indexS); } // pseudo selector :has(el) private void has() { tq.consume(":has"); String subQuery = tq.chompBalanced('(',')'); Validate.notEmpty(subQuery, ":has(el) subselect must not be empty"); s.add(new HasSelector(parse(subQuery))); } // pseudo selector :contains(text), containsOwn(text) private void contains(boolean own) { tq.consume(own ? ":containsOwn" : ":contains"); String searchText = TokenQueue.unescape(tq.chompBalanced('(',')')); Validate.notEmpty(searchText, ":contains(text) query must not be empty"); if(own) s.add(new Evaluator.ContainsOwnText(searchText)); else s.add(new Evaluator.ContainsText(searchText)); } // :matches(regex), matchesOwn(regex) private void matches(boolean own) { tq.consume(own? ":matchesOwn" : ":matches"); String regex = tq.chompBalanced('(', ')'); // don't unescape, as regex bits will be escaped Validate.notEmpty(regex, ":matches(regex) query must not be empty"); if(own) s.add(new Evaluator.MatchesOwn(Pattern.compile(regex))); else s.add(new Evaluator.Matches(Pattern.compile(regex))); } // :not(selector) private void not() { tq.consume(":not"); String subQuery = tq.chompBalanced('(', ')'); Validate.notEmpty(subQuery, ":not(selector) subselect must not be empty"); s.add(new NotSelector(parse(subQuery))); } public static class SelectorParseException extends IllegalStateException { public SelectorParseException(String msg, Object... params) { super(String.format(msg, params)); } } void ecPush(Evaluator e) { /*Evaluator p = s.peek(); if(p == null || !(p instanceof ElementContainerSelector)) { s.push(new ElementContainerSelector().add(e)); return; } ElementContainerSelector ec = (ElementContainerSelector) p;*/ //ec.add(e); s.add(e); } public static void main(String[] args) { // make sure doesn't get nested Evaluator eval = Parser.parse("div.head, div.body"); Document doc = Jsoup.parse("<div id=1><div id=2><div id=3></div></div></div>"); Element div = SelectMatch.match(SelectMatch.match(doc, Parser.parse("div")), Parser.parse(" > div")).first(); } }
package com.adyen.model.checkout; import static com.adyen.constants.ApiConstants.PaymentMethodType.TYPE_SCHEME; import com.adyen.Util.Util; import com.adyen.model.AccountInfo; import com.adyen.model.Address; import com.adyen.model.Amount; import com.adyen.model.BrowserInfo; import com.adyen.model.ForexQuote; import com.adyen.model.Installments; import com.adyen.model.MerchantRiskIndicator; import com.adyen.model.Name; import com.adyen.model.Split; import com.adyen.model.ThreeDS2RequestData; import com.adyen.model.applicationinfo.ApplicationInfo; import com.adyen.serializer.DateSerializer; import com.adyen.serializer.DateTimeGMTSerializer; 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 java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * PaymentsRequest */ public class PaymentsRequest { @SerializedName("accountInfo") private AccountInfo accountInfo = null; @SerializedName("additionalData") private Map<String, String> additionalData = null; @SerializedName("amount") private Amount amount = null; @SerializedName("billingAddress") private Address billingAddress = null; @SerializedName("captureDelayHours") private Integer captureDelayHours = null; @SerializedName("channel") private ChannelEnum channel = null; @SerializedName("company") private Company company = null; @SerializedName("countryCode") private String countryCode = null; @SerializedName("dateOfBirth") @JsonAdapter(DateSerializer.class) private Date dateOfBirth = null; @SerializedName("dccQuote") private ForexQuote dccQuote = null; @SerializedName("deliveryAddress") private Address deliveryAddress = null; @SerializedName("deliveryDate") @JsonAdapter(DateTimeGMTSerializer.class) private Date deliveryDate = null; @SerializedName("enableOneClick") private Boolean enableOneClick = null; @SerializedName("enablePayOut") private Boolean enablePayOut = null; @SerializedName("enableRecurring") private Boolean enableRecurring = null; @SerializedName("entityType") private EntityTypeEnum entityType = null; @SerializedName("fraudOffset") private Integer fraudOffset = null; @SerializedName("installments") private Installments installments = null; @SerializedName("lineItems") private List<LineItem> lineItems = null; @SerializedName("mcc") private String mcc = null; @SerializedName("merchantAccount") private String merchantAccount = null; @SerializedName("merchantOrderReference") private String merchantOrderReference = null; @SerializedName("metadata") private Map<String, String> metadata = null; @SerializedName("orderReference") private String orderReference = null; @SerializedName("paymentMethod") private PaymentMethodDetails paymentMethod = null; @SerializedName("reference") private String reference = null; @SerializedName("returnUrl") private String returnUrl = null; @SerializedName("sessionValidity") private String sessionValidity = null; @SerializedName("shopperEmail") private String shopperEmail = null; @SerializedName("shopperIP") private String shopperIP = null; @SerializedName("shopperInteraction") private ShopperInteractionEnum shopperInteraction = null; @SerializedName("shopperLocale") private String shopperLocale = null; @SerializedName("shopperName") private Name shopperName = null; @SerializedName("shopperReference") private String shopperReference = null; @SerializedName("shopperStatement") private String shopperStatement = null; @SerializedName("socialSecurityNumber") private String socialSecurityNumber = null; @SerializedName("telephoneNumber") private String telephoneNumber = null; @SerializedName("browserInfo") private BrowserInfo browserInfo = null; @SerializedName("deviceFingerprint") private String deviceFingerprint = null; @SerializedName("applicationInfo") private ApplicationInfo applicationInfo; @SerializedName("splits") private List<Split> splits = null; @SerializedName("merchantRiskIndicator") private MerchantRiskIndicator merchantRiskIndicator = null; @SerializedName("threeDS2RequestData") private ThreeDS2RequestData threeDS2RequestData = null; @SerializedName("trustedShopper") private Boolean trustedShopper = null; @SerializedName("origin") private String origin; @SerializedName("configId") private String configId = null; @SerializedName("blockedPaymentMethods") private List<String> blockedPaymentMethods = null; @SerializedName("recurringProcessingModel") private RecurringProcessingModelEnum recurringProcessingModel = null; @SerializedName("merchantData") private String merchantData = null; @SerializedName("mpiData") private ThreeDSecureData mpiData = null; @SerializedName("redirectFromIssuerMethod") private String redirectFromIssuerMethod = null; @SerializedName("redirectToIssuerMethod") private String redirectToIssuerMethod = null; public PaymentsRequest() { if (this.applicationInfo == null) { this.applicationInfo = new ApplicationInfo(); } } public RecurringProcessingModelEnum getRecurringProcessingModel() { return recurringProcessingModel; } public PaymentsRequest recurringProcessingModel(RecurringProcessingModelEnum recurringProcessingModel) { this.recurringProcessingModel = recurringProcessingModel; return this; } public void setRecurringProcessingModel(RecurringProcessingModelEnum recurringProcessingModel) { this.recurringProcessingModel = recurringProcessingModel; } public MerchantRiskIndicator getMerchantRiskIndicator() { return merchantRiskIndicator; } public void setMerchantRiskIndicator(MerchantRiskIndicator merchantRiskIndicator) { this.merchantRiskIndicator = merchantRiskIndicator; } public AccountInfo getAccountInfo() { return accountInfo; } public void setAccountInfo(AccountInfo accountInfo) { this.accountInfo = accountInfo; } public Boolean getEnableOneClick() { return enableOneClick; } public Boolean getEnablePayOut() { return enablePayOut; } public Boolean getEnableRecurring() { return enableRecurring; } public List<Split> getSplits() { return splits; } public void setSplits(List<Split> splits) { this.splits = splits; } public Boolean getTrustedShopper() { return trustedShopper; } public void setTrustedShopper(Boolean trustedShopper) { this.trustedShopper = trustedShopper; } public ThreeDS2RequestData getThreeDS2RequestData() { return threeDS2RequestData; } public void setThreeDS2RequestData(ThreeDS2RequestData threeDS2RequestData) { this.threeDS2RequestData = threeDS2RequestData; } public PaymentsRequest additionalData(Map<String, String> additionalData) { this.additionalData = additionalData; return this; } public PaymentsRequest putAdditionalDataItem(String key, String additionalDataItem) { if (this.additionalData == null) { this.additionalData = new HashMap<>(); } this.additionalData.put(key, additionalDataItem); return this; } public Map<String, String> getAdditionalData() { return additionalData; } public void setAdditionalData(Map<String, String> additionalData) { this.additionalData = additionalData; } public PaymentsRequest amount(Amount amount) { this.amount = amount; return this; } public String getConfigId() { return configId; } public void setConfigId(String configId) { this.configId = configId; } public List<String> getBlockedPaymentMethods() { return blockedPaymentMethods; } public void setBlockedPaymentMethods(List<String> blockedPaymentMethods) { this.blockedPaymentMethods = blockedPaymentMethods; } /** * Get amount * * @return amount **/ public Amount getAmount() { return amount; } public void setAmount(Amount amount) { this.amount = amount; } public PaymentsRequest setAmountData(String amount, String currency) { Amount amountData = Util.createAmount(amount, currency); this.setAmount(amountData); return this; } public PaymentsRequest billingAddress(Address billingAddress) { this.billingAddress = billingAddress; return this; } /** * Get billingAddress * * @return billingAddress **/ public Address getBillingAddress() { return billingAddress; } public void setBillingAddress(Address billingAddress) { this.billingAddress = billingAddress; } public PaymentsRequest captureDelayHours(Integer captureDelayHours) { this.captureDelayHours = captureDelayHours; return this; } /** * The delay between the authorisation and scheduled auto-capture, specified in hours. * * @return captureDelayHours **/ public Integer getCaptureDelayHours() { return captureDelayHours; } public void setCaptureDelayHours(Integer captureDelayHours) { this.captureDelayHours = captureDelayHours; } public PaymentsRequest channel(ChannelEnum channel) { this.channel = channel; return this; } /** * The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we * will try to infer it from the &#x60;sdkVersion&#x60; or token. Possible values: * iOS * Android * Web * * @return channel **/ public ChannelEnum getChannel() { return channel; } public void setChannel(ChannelEnum channel) { this.channel = channel; } public PaymentsRequest company(Company company) { this.company = company; return this; } /** * Get company * * @return company **/ public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public PaymentsRequest countryCode(String countryCode) { this.countryCode = countryCode; return this; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public PaymentsRequest dateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; return this; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public PaymentsRequest dccQuote(ForexQuote dccQuote) { this.dccQuote = dccQuote; return this; } /** * Get dccQuote * * @return dccQuote **/ public ForexQuote getDccQuote() { return dccQuote; } public void setDccQuote(ForexQuote dccQuote) { this.dccQuote = dccQuote; } public PaymentsRequest deliveryAddress(Address deliveryAddress) { this.deliveryAddress = deliveryAddress; return this; } /** * Get deliveryAddress * * @return deliveryAddress **/ public Address getDeliveryAddress() { return deliveryAddress; } public void setDeliveryAddress(Address deliveryAddress) { this.deliveryAddress = deliveryAddress; } public PaymentsRequest deliveryDate(Date deliveryDate) { this.deliveryDate = deliveryDate; return this; } public Date getDeliveryDate() { return deliveryDate; } public void setDeliveryDate(Date deliveryDate) { this.deliveryDate = deliveryDate; } public PaymentsRequest enableOneClick(Boolean enableOneClick) { this.enableOneClick = enableOneClick; return this; } /** * When true and &#x60;shopperReference&#x60; is provided, the shopper will be asked if the payment details should be stored for future one-click payments. * * @return enableOneClick **/ public Boolean isEnableOneClick() { return enableOneClick; } public void setEnableOneClick(Boolean enableOneClick) { this.enableOneClick = enableOneClick; } public PaymentsRequest enablePayOut(Boolean enablePayOut) { this.enablePayOut = enablePayOut; return this; } /** * When true and &#x60;shopperReference&#x60; is provided, the payment details will be tokenized for payouts. * * @return enablePayOut **/ public Boolean isEnablePayOut() { return enablePayOut; } public void setEnablePayOut(Boolean enablePayOut) { this.enablePayOut = enablePayOut; } public PaymentsRequest enableRecurring(Boolean enableRecurring) { this.enableRecurring = enableRecurring; return this; } /** * When true and &#x60;shopperReference&#x60; is provided, the payment details will be tokenized for recurring payments. * * @return enableRecurring **/ public Boolean isEnableRecurring() { return enableRecurring; } public void setEnableRecurring(Boolean enableRecurring) { this.enableRecurring = enableRecurring; } public PaymentsRequest entityType(EntityTypeEnum entityType) { this.entityType = entityType; return this; } /** * The type of the entity the payment is processed for. * * @return entityType **/ public EntityTypeEnum getEntityType() { return entityType; } public void setEntityType(EntityTypeEnum entityType) { this.entityType = entityType; } public PaymentsRequest fraudOffset(Integer fraudOffset) { this.fraudOffset = fraudOffset; return this; } /** * An integer value that is added to the normal fraud score. The value can be either positive or negative. * * @return fraudOffset **/ public Integer getFraudOffset() { return fraudOffset; } public void setFraudOffset(Integer fraudOffset) { this.fraudOffset = fraudOffset; } public PaymentsRequest installments(Installments installments) { this.installments = installments; return this; } /** * Get installments * * @return installments **/ public Installments getInstallments() { return installments; } public void setInstallments(Installments installments) { this.installments = installments; } public PaymentsRequest lineItems(List<LineItem> lineItems) { this.lineItems = lineItems; return this; } public PaymentsRequest addLineItemsItem(LineItem lineItemsItem) { if (this.lineItems == null) { this.lineItems = new ArrayList<>(); } this.lineItems.add(lineItemsItem); return this; } /** * Line items regarding the payment. * * @return lineItems **/ public List<LineItem> getLineItems() { return lineItems; } public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; } public PaymentsRequest mcc(String mcc) { this.mcc = mcc; return this; } public String getMcc() { return mcc; } public void setMcc(String mcc) { this.mcc = mcc; } public PaymentsRequest merchantAccount(String merchantAccount) { this.merchantAccount = merchantAccount; return this; } /** * The merchant account identifier, with which you want to process the transaction. * * @return merchantAccount **/ public String getMerchantAccount() { return merchantAccount; } public void setMerchantAccount(String merchantAccount) { this.merchantAccount = merchantAccount; } public PaymentsRequest merchantOrderReference(String merchantOrderReference) { this.merchantOrderReference = merchantOrderReference; return this; } /** * This reference allows linking multiple transactions to each other. &gt; When providing the &#x60;merchantOrderReference&#x60; value, we also recommend you submit * &#x60;retry.orderAttemptNumber&#x60;, &#x60;retry.chainAttemptNumber&#x60;, and &#x60;retry.skipRetry&#x60; values. * * @return merchantOrderReference **/ public String getMerchantOrderReference() { return merchantOrderReference; } public void setMerchantOrderReference(String merchantOrderReference) { this.merchantOrderReference = merchantOrderReference; } public PaymentsRequest metadata(Map<String, String> metadata) { this.metadata = metadata; return this; } public PaymentsRequest putMetadataItem(String key, String metadataItem) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.put(key, metadataItem); return this; } /** * Metadata consists of entries, each of which includes a key and a value. Limitations: Error \&quot;177\&quot;, \&quot;Metadata size exceeds limit\&quot; * * @return metadata **/ public Map<String, String> getMetadata() { return metadata; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } public PaymentsRequest orderReference(String orderReference) { this.orderReference = orderReference; return this; } /** * The order reference to link multiple partial payments. * * @return orderReference **/ public String getOrderReference() { return orderReference; } public void setOrderReference(String orderReference) { this.orderReference = orderReference; } public PaymentMethodDetails getPaymentMethod() { return paymentMethod; } public void setPaymentMethod(PaymentMethodDetails paymentMethod) { this.paymentMethod = paymentMethod; } public PaymentsRequest paymentMethod(PaymentMethodDetails paymentMethod) { this.paymentMethod = paymentMethod; return this; } public PaymentsRequest addEncryptedCardData(String encryptedCardNumber, String encryptedExpiryMonth, String encryptedExpiryYear, String encryptedSecurityCode, String holderName) { return addEncryptedCardData(encryptedCardNumber, encryptedExpiryMonth, encryptedExpiryYear, encryptedSecurityCode, holderName, null); } public PaymentsRequest addEncryptedCardData(String encryptedCardNumber, String encryptedExpiryMonth, String encryptedExpiryYear, String encryptedSecurityCode, String holderName, Boolean storeDetails) { DefaultPaymentMethodDetails paymentMethodDetails = new DefaultPaymentMethodDetails(); paymentMethodDetails.type(TYPE_SCHEME).encryptedCardNumber(encryptedCardNumber).encryptedExpiryMonth(encryptedExpiryMonth).encryptedExpiryYear(encryptedExpiryYear); if (encryptedSecurityCode != null) { paymentMethodDetails.setEncryptedSecurityCode(encryptedSecurityCode); } if (holderName != null) { paymentMethodDetails.setHolderName(holderName); } if (storeDetails != null) { paymentMethodDetails.setStoreDetails(storeDetails); } this.paymentMethod = paymentMethodDetails; return this; } /** * Add raw card data into the payment request. You need to be PCI compliant! * @param cardNumber card number * @param expiryMonth expiry month * @param expiryYear expiry year * @param holderName holder name * @param securityCode security code * @return paymentMethod payment method */ public PaymentsRequest addCardData(String cardNumber, String expiryMonth, String expiryYear, String securityCode, String holderName) { return addCardData(cardNumber, expiryMonth, expiryYear, securityCode, holderName, null); } public PaymentsRequest addCardData(String cardNumber, String expiryMonth, String expiryYear, String securityCode, String holderName, Boolean storeDetails) { DefaultPaymentMethodDetails paymentMethodDetails = new DefaultPaymentMethodDetails(); paymentMethodDetails.type(TYPE_SCHEME).number(cardNumber).expiryMonth(expiryMonth).expiryYear(expiryYear); if (securityCode != null) { paymentMethodDetails.setCvc(securityCode); } if (holderName != null) { paymentMethodDetails.setHolderName(holderName); } if (storeDetails != null) { paymentMethodDetails.setStoreDetails(storeDetails); } this.paymentMethod = paymentMethodDetails; return this; } public PaymentsRequest addOneClickData(String recurringDetailReference, String encryptedSecurityCode) { DefaultPaymentMethodDetails paymentMethodDetails = new DefaultPaymentMethodDetails(); paymentMethodDetails.type(TYPE_SCHEME).recurringDetailReference(recurringDetailReference).encryptedSecurityCode(encryptedSecurityCode); this.paymentMethod = paymentMethodDetails; return this; } public PaymentsRequest reference(String reference) { this.reference = reference; return this; } /** * The reference to uniquely identify a payment. This reference is used in all communication with you about the payment status. We recommend using a unique value per payment; however, it is not a * requirement. If you need to provide multiple references for a transaction, separate them with hyphens (\&quot;-\&quot;). Maximum length: 80 characters. * * @return reference **/ public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public PaymentsRequest returnUrl(String returnUrl) { this.returnUrl = returnUrl; return this; } /** * The URL to return to. * * @return returnUrl **/ public String getReturnUrl() { return returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public PaymentsRequest sessionValidity(String sessionValidity) { this.sessionValidity = sessionValidity; return this; } /** * The maximum validity of the session. * * @return sessionValidity **/ public String getSessionValidity() { return sessionValidity; } public void setSessionValidity(String sessionValidity) { this.sessionValidity = sessionValidity; } public PaymentsRequest shopperEmail(String shopperEmail) { this.shopperEmail = shopperEmail; return this; } /** * The shopper&#x27;s email address. We recommend that you provide this data, as it is used in velocity fraud checks. * * @return shopperEmail **/ public String getShopperEmail() { return shopperEmail; } public void setShopperEmail(String shopperEmail) { this.shopperEmail = shopperEmail; } public PaymentsRequest shopperIP(String shopperIP) { this.shopperIP = shopperIP; return this; } public String getShopperIP() { return shopperIP; } public void setShopperIP(String shopperIP) { this.shopperIP = shopperIP; } public PaymentsRequest shopperInteraction(ShopperInteractionEnum shopperInteraction) { this.shopperInteraction = shopperInteraction; return this; } /** * Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper * interaction by default. This field has the following possible values: * &#x60;Ecommerce&#x60; - Online transactions where the cardholder is present (online). For better authorisation rates, we * recommend sending the card security code (CSC) along with the request. * &#x60;ContAuth&#x60; - Card on file and/or subscription transactions, where the cardholder is known to the merchant * (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * &#x60;Moto&#x60; - Mail-order and telephone-order * transactions where the shopper is in contact with the merchant via email or telephone. * &#x60;POS&#x60; - Point-of-sale transactions where the shopper is physically present to make a payment * using a secure payment terminal. * * @return shopperInteraction **/ public ShopperInteractionEnum getShopperInteraction() { return shopperInteraction; } public void setShopperInteraction(ShopperInteractionEnum shopperInteraction) { this.shopperInteraction = shopperInteraction; } public PaymentsRequest shopperLocale(String shopperLocale) { this.shopperLocale = shopperLocale; return this; } /** * The combination of a language code and a country code to specify the language to be used in the payment. * * @return shopperLocale **/ public String getShopperLocale() { return shopperLocale; } public void setShopperLocale(String shopperLocale) { this.shopperLocale = shopperLocale; } public PaymentsRequest shopperName(Name shopperName) { this.shopperName = shopperName; return this; } /** * Get shopperName * * @return shopperName **/ public Name getShopperName() { return shopperName; } public void setShopperName(Name shopperName) { this.shopperName = shopperName; } public PaymentsRequest shopperReference(String shopperReference) { this.shopperReference = shopperReference; return this; } /** * The shopper&#x27;s reference to uniquely identify this shopper (e.g. user ID or account ID). &gt; This field is required for recurring payments. * * @return shopperReference **/ public String getShopperReference() { return shopperReference; } public void setShopperReference(String shopperReference) { this.shopperReference = shopperReference; } public PaymentsRequest shopperStatement(String shopperStatement) { this.shopperStatement = shopperStatement; return this; } /** * The text to appear on the shopper&#x27;s bank statement. * * @return shopperStatement **/ public String getShopperStatement() { return shopperStatement; } public void setShopperStatement(String shopperStatement) { this.shopperStatement = shopperStatement; } public PaymentsRequest socialSecurityNumber(String socialSecurityNumber) { this.socialSecurityNumber = socialSecurityNumber; return this; } /** * The shopper&#x27;s social security number. * * @return socialSecurityNumber **/ public String getSocialSecurityNumber() { return socialSecurityNumber; } public void setSocialSecurityNumber(String socialSecurityNumber) { this.socialSecurityNumber = socialSecurityNumber; } public PaymentsRequest telephoneNumber(String telephoneNumber) { this.telephoneNumber = telephoneNumber; return this; } /** * The shopper&#x27;s telephone number. * * @return telephoneNumber **/ public String getTelephoneNumber() { return telephoneNumber; } public void setTelephoneNumber(String telephoneNumber) { this.telephoneNumber = telephoneNumber; } public BrowserInfo getBrowserInfo() { return browserInfo; } public void setBrowserInfo(BrowserInfo browserInfo) { this.browserInfo = browserInfo; } public PaymentsRequest browserInfo(BrowserInfo browserInfo) { this.browserInfo = browserInfo; return this; } public PaymentsRequest addBrowserInfoData(String userAgent, String acceptHeader) { BrowserInfo browserInfo = new BrowserInfo(); browserInfo.setAcceptHeader(acceptHeader); browserInfo.setUserAgent(userAgent); this.setBrowserInfo(browserInfo); return this; } public String getDeviceFingerprint() { return deviceFingerprint; } public void setDeviceFingerprint(String deviceFingerprint) { this.deviceFingerprint = deviceFingerprint; } public PaymentsRequest deviceFingerprint(String deviceFingerprint) { this.deviceFingerprint = deviceFingerprint; return this; } public ApplicationInfo getApplicationInfo() { return applicationInfo; } public void setApplicationInfo(ApplicationInfo applicationInfo) { this.applicationInfo = applicationInfo; } public PaymentsRequest applicationInfo(ApplicationInfo applicationInfo) { this.applicationInfo = applicationInfo; return this; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public PaymentsRequest origin(String origin) { this.origin = origin; return this; } /** * Holds different merchant data points like product, purchase, customer, and so on. It takes data in a JSON string. * * @return the merchant data */ public String getMerchantData() { return merchantData; } public void setMerchantData(String merchantData) { this.merchantData = merchantData; } /** * Authentication data produced by an MPI (Mastercard SecureCode or Verified By Visa). * * @return the mpi data */ public ThreeDSecureData getMpiData() { return mpiData; } public void setMpiData(ThreeDSecureData mpiData) { this.mpiData = mpiData; } /** * Specifies the redirect method (GET or POST) when redirecting back from the issuer. * * @return the redirect from issuer method */ public String getRedirectFromIssuerMethod() { return redirectFromIssuerMethod; } public void setRedirectFromIssuerMethod(String redirectFromIssuerMethod) { this.redirectFromIssuerMethod = redirectFromIssuerMethod; } /** * Specifies the redirect method (GET or POST) when redirecting to the issuer. * * @return the redirect to issuer method */ public String getRedirectToIssuerMethod() { return redirectToIssuerMethod; } public void setRedirectToIssuerMethod(String redirectToIssuerMethod) { this.redirectToIssuerMethod = redirectToIssuerMethod; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PaymentsRequest paymentsRequest = (PaymentsRequest) o; return Objects.equals(this.additionalData, paymentsRequest.additionalData) && Objects.equals(this.amount, paymentsRequest.amount) && Objects.equals(this.billingAddress, paymentsRequest.billingAddress) && Objects.equals(this.captureDelayHours, paymentsRequest.captureDelayHours) && Objects.equals(this.channel, paymentsRequest.channel) && Objects.equals(this.company, paymentsRequest.company) && Objects.equals(this.countryCode, paymentsRequest.countryCode) && Objects.equals(this.dateOfBirth, paymentsRequest.dateOfBirth) && Objects.equals(this.dccQuote, paymentsRequest.dccQuote) && Objects.equals(this.deliveryAddress, paymentsRequest.deliveryAddress) && Objects.equals(this.deliveryDate, paymentsRequest.deliveryDate) && Objects.equals(this.enableOneClick, paymentsRequest.enableOneClick) && Objects.equals(this.enablePayOut, paymentsRequest.enablePayOut) && Objects.equals(this.enableRecurring, paymentsRequest.enableRecurring) && Objects.equals(this.entityType, paymentsRequest.entityType) && Objects.equals(this.fraudOffset, paymentsRequest.fraudOffset) && Objects.equals(this.installments, paymentsRequest.installments) && Objects.equals(this.lineItems, paymentsRequest.lineItems) && Objects.equals(this.mcc, paymentsRequest.mcc) && Objects.equals(this.merchantAccount, paymentsRequest.merchantAccount) && Objects.equals(this.merchantOrderReference, paymentsRequest.merchantOrderReference) && Objects.equals(this.metadata, paymentsRequest.metadata) && Objects.equals(this.orderReference, paymentsRequest.orderReference) && Objects.equals(this.paymentMethod, paymentsRequest.paymentMethod) && Objects.equals(this.reference, paymentsRequest.reference) && Objects.equals(this.returnUrl, paymentsRequest.returnUrl) && Objects.equals(this.recurringProcessingModel, paymentsRequest.recurringProcessingModel) && Objects.equals(this.sessionValidity, paymentsRequest.sessionValidity) && Objects.equals(this.shopperEmail, paymentsRequest.shopperEmail) && Objects.equals(this.shopperIP, paymentsRequest.shopperIP) && Objects.equals(this.shopperInteraction, paymentsRequest.shopperInteraction) && Objects.equals(this.shopperLocale, paymentsRequest.shopperLocale) && Objects.equals(this.shopperName, paymentsRequest.shopperName) && Objects.equals(this.shopperReference, paymentsRequest.shopperReference) && Objects.equals(this.shopperStatement, paymentsRequest.shopperStatement) && Objects.equals(this.socialSecurityNumber, paymentsRequest.socialSecurityNumber) && Objects.equals(this.deviceFingerprint, paymentsRequest.deviceFingerprint) && Objects.equals(this.applicationInfo, paymentsRequest.applicationInfo) && Objects.equals(this.telephoneNumber, paymentsRequest.telephoneNumber) && Objects.equals(this.splits, paymentsRequest.splits) && Objects.equals(this.accountInfo, paymentsRequest.accountInfo) && Objects.equals(this.trustedShopper, paymentsRequest.trustedShopper) && Objects.equals(this.merchantRiskIndicator, paymentsRequest.merchantRiskIndicator) && Objects.equals(this.threeDS2RequestData, paymentsRequest.threeDS2RequestData) && Objects.equals(this.trustedShopper, paymentsRequest.trustedShopper) && Objects.equals(this.origin, paymentsRequest.origin) && Objects.equals(this.metadata, paymentsRequest.metadata) && Objects.equals(this.mpiData, paymentsRequest.mpiData) && Objects.equals(this.redirectFromIssuerMethod, paymentsRequest.redirectFromIssuerMethod) && Objects.equals(this.redirectToIssuerMethod, paymentsRequest.redirectToIssuerMethod); } @Override public int hashCode() { return Objects.hash(additionalData, amount, billingAddress, captureDelayHours, channel, company, countryCode, dateOfBirth, dccQuote, deliveryAddress, deliveryDate, enableOneClick, enablePayOut, enableRecurring, entityType, fraudOffset, installments, lineItems, mcc, merchantAccount, merchantOrderReference, metadata, orderReference, paymentMethod, reference, returnUrl, recurringProcessingModel, sessionValidity, shopperEmail, shopperIP, shopperInteraction, shopperLocale, shopperName, shopperReference, shopperStatement, socialSecurityNumber, deviceFingerprint, applicationInfo, telephoneNumber, accountInfo, splits, trustedShopper, blockedPaymentMethods, configId, metadata, mpiData, redirectFromIssuerMethod, redirectToIssuerMethod); } @Override public String toString() { return "class PaymentsRequest {\n" + " additionalData: " + toIndentedString(additionalData) + "\n" + " amount: " + toIndentedString(amount) + "\n" + " billingAddress: " + toIndentedString(billingAddress) + "\n" + " captureDelayHours: " + toIndentedString(captureDelayHours) + "\n" + " channel: " + toIndentedString(channel) + "\n" + " company: " + toIndentedString(company) + "\n" + " countryCode: " + toIndentedString(countryCode) + "\n" + " dateOfBirth: " + toIndentedString(dateOfBirth) + "\n" + " dccQuote: " + toIndentedString(dccQuote) + "\n" + " deliveryAddress: " + toIndentedString(deliveryAddress) + "\n" + " deliveryDate: " + toIndentedString(deliveryDate) + "\n" + " enableOneClick: " + toIndentedString(enableOneClick) + "\n" + " enablePayOut: " + toIndentedString(enablePayOut) + "\n" + " enableRecurring: " + toIndentedString(enableRecurring) + "\n" + " entityType: " + toIndentedString(entityType) + "\n" + " fraudOffset: " + toIndentedString(fraudOffset) + "\n" + " installments: " + toIndentedString(installments) + "\n" + " lineItems: " + toIndentedString(lineItems) + "\n" + " mcc: " + toIndentedString(mcc) + "\n" + " merchantAccount: " + toIndentedString(merchantAccount) + "\n" + " merchantOrderReference: " + toIndentedString(merchantOrderReference) + "\n" + " metadata: " + toIndentedString(metadata) + "\n" + " orderReference: " + toIndentedString(orderReference) + "\n" + " paymentMethod: " + toIndentedString(paymentMethod) + "\n" + " reference: " + toIndentedString(reference) + "\n" + " recurringProcessingModel: " + toIndentedString(recurringProcessingModel) + "\n" + " " + " returnUrl: " + toIndentedString(returnUrl) + "\n" + " sessionValidity: " + toIndentedString(sessionValidity) + "\n" + " shopperEmail: " + toIndentedString(shopperEmail) + "\n" + " shopperIP: " + toIndentedString(shopperIP) + "\n" + " shopperInteraction: " + toIndentedString(shopperInteraction) + "\n" + " shopperLocale: " + toIndentedString(shopperLocale) + "\n" + " shopperName: " + toIndentedString(shopperName) + "\n" + " shopperReference: " + toIndentedString(shopperReference) + "\n" + " shopperStatement: " + toIndentedString(shopperStatement) + "\n" + " socialSecurityNumber: " + toIndentedString(socialSecurityNumber) + "\n" + " deviceFingerprint: " + toIndentedString(deviceFingerprint) + "\n" + " applicationInfo: " + toIndentedString(applicationInfo) + "\n" + " telephoneNumber: " + toIndentedString(telephoneNumber) + "\n" + " accountInfo: " + toIndentedString(accountInfo) + "\n" + " trustedShopper: " + toIndentedString(trustedShopper) + "\n" + " splits: " + toIndentedString(splits) + "\n" + " merchantRiskIndicator: " + toIndentedString(merchantRiskIndicator) + "\n" + " threeDS2RequestData: " + toIndentedString(threeDS2RequestData) + "\n" + " trustedShopper: " + toIndentedString(trustedShopper) + "\n" + " blockedPaymentMethods: " + toIndentedString(blockedPaymentMethods) + "\n" + " configId: " + toIndentedString(configId) + "\n" + " origin: " + toIndentedString(origin) + "\n" + " metadata: " + toIndentedString(metadata) + "\n" + " mpiData: " + toIndentedString(mpiData) + "\n" + " redirectFromIssuerMethod: " + toIndentedString(redirectFromIssuerMethod) + "\n" + " redirectToIssuerMethod: " + toIndentedString(redirectToIssuerMethod) + "\n" + "}"; } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } /** * The platform where a payment transaction takes place. This field is optional for filtering out payment methods that are only available on specific platforms. If this value is not set, then we * will try to infer it from the &#x60;sdkVersion&#x60; or token. Possible values: * iOS * Android * Web */ @JsonAdapter(ChannelEnum.Adapter.class) public enum ChannelEnum { IOS("iOS"), ANDROID("Android"), WEB("Web"); private String value; ChannelEnum(String value) { this.value = value; } public static ChannelEnum fromValue(String text) { for (ChannelEnum b : ChannelEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static class Adapter extends TypeAdapter<ChannelEnum> { @Override public void write(final JsonWriter jsonWriter, final ChannelEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public ChannelEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return ChannelEnum.fromValue(String.valueOf(value)); } } } /** * The type of the entity the payment is processed for. */ @JsonAdapter(EntityTypeEnum.Adapter.class) public enum EntityTypeEnum { NATURALPERSON("NaturalPerson"), COMPANYNAME("CompanyName"); private String value; EntityTypeEnum(String value) { this.value = value; } public static EntityTypeEnum fromValue(String text) { for (EntityTypeEnum b : EntityTypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static class Adapter extends TypeAdapter<EntityTypeEnum> { @Override public void write(final JsonWriter jsonWriter, final EntityTypeEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public EntityTypeEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return EntityTypeEnum.fromValue(String.valueOf(value)); } } } /** * how the shopper interacts with the system */ public enum RecurringProcessingModelEnum { /** * A transaction for a fixed or variable amount, which follows a fixed schedule. This is the default value. */ @SerializedName("Subscription") SUBSCRIPTION("Subscription"), /** * Card details are stored to enable one-click or omnichannel journeys, or simply to streamline the checkout process. * Any subscription not following a fixed schedule is also considered as a card-on-file transaction. */ @SerializedName("CardOnFile") CARD_ON_FILE("CardOnFile"), /** * A transaction that occurs on a non-fixed schedule and/or have variable amounts. For example, automatic top-ups when a cardholder's balance drops below a certain amount. */ @SerializedName("UnscheduledCardOnFile") UNSCHEDULED_CARD_ON_FILE("UnscheduledCardOnFile"); private String value; RecurringProcessingModelEnum(String value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } } /** * Specifies the sales channel, through which the shopper gives their card details, and whether the shopper is a returning customer. For the web service API, Adyen assumes Ecommerce shopper * interaction by default. This field has the following possible values: * &#x60;Ecommerce&#x60; - Online transactions where the cardholder is present (online). For better authorisation rates, we * recommend sending the card security code (CSC) along with the request. * &#x60;ContAuth&#x60; - Card on file and/or subscription transactions, where the cardholder is known to the merchant * (returning customer). If the shopper is present (online), you can supply also the CSC to improve authorisation (one-click payment). * &#x60;Moto&#x60; - Mail-order and telephone-order * transactions where the shopper is in contact with the merchant via email or telephone. * &#x60;POS&#x60; - Point-of-sale transactions where the shopper is physically present to make a payment * using a secure payment terminal. */ @JsonAdapter(ShopperInteractionEnum.Adapter.class) public enum ShopperInteractionEnum { ECOMMERCE("Ecommerce"), CONTAUTH("ContAuth"), MOTO("Moto"), POS("POS"); private String value; ShopperInteractionEnum(String value) { this.value = value; } public static ShopperInteractionEnum fromValue(String text) { for (ShopperInteractionEnum b : ShopperInteractionEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static class Adapter extends TypeAdapter<ShopperInteractionEnum> { @Override public void write(final JsonWriter jsonWriter, final ShopperInteractionEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public ShopperInteractionEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return ShopperInteractionEnum.fromValue(String.valueOf(value)); } } } }
package org.junit.rules; import static java.lang.String.format; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.junit.internal.matchers.ThrowableCauseMatcher.hasCause; import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.junit.AssumptionViolatedException; import org.junit.runners.model.Statement; /** * The {@code ExpectedException} rule allows you to verify that your code * throws a specific exception. Note that, starting with Java 8, * {@link org.junit.Assert#assertThrows(java.lang.Class, org.junit.function.ThrowingRunnable) * Assert.assertThrows} * is often a better choice since it allows you to express exactly where you * expect the exception to be thrown. Use * {@link org.junit.Assert#expectThrows(java.lang.Class, * org.junit.function.ThrowingRunnable) expectThrows} * if you need to assert something about the thrown exception. * * <h3>Usage</h3> * * <pre> public class SimpleExpectedExceptionTest { * &#064;Rule * public ExpectedException thrown = ExpectedException.none(); * * &#064;Test * public void throwsNothing() { * // no exception expected, none thrown: passes. * } * * &#064;Test * public void throwsExceptionWithSpecificType() { * thrown.expect(NullPointerException.class); * throw new NullPointerException(); * } * }</pre> * * <p>You have to add the {@code ExpectedException} rule to your test. * This doesn't affect your existing tests (see {@code throwsNothing()}). * After specifying the type of the expected exception your test is * successful when such an exception is thrown and it fails if a * different or no exception is thrown. * * <p>This rule does not perform any special magic to make execution continue * as if the exception had not been thrown. So it is nearly always a mistake * for a test method to have statements after the one that is expected to * throw the exception. * * <p>Instead of specifying the exception's type you can characterize the * expected exception based on other criteria, too: * * <ul> * <li>The exception's message contains a specific text: {@link #expectMessage(String)}</li> * <li>The exception's message complies with a Hamcrest matcher: {@link #expectMessage(Matcher)}</li> * <li>The exception's cause complies with a Hamcrest matcher: {@link #expectCause(Matcher)}</li> * <li>The exception itself complies with a Hamcrest matcher: {@link #expect(Matcher)}</li> * </ul> * * <p>You can combine any of the presented expect-methods. The test is * successful if all specifications are met. * <pre> &#064;Test * public void throwsException() { * thrown.expect(NullPointerException.class); * thrown.expectMessage(&quot;happened&quot;); * throw new NullPointerException(&quot;What happened?&quot;); * }</pre> * * <h3>AssumptionViolatedExceptions</h3> * <p>JUnit uses {@link AssumptionViolatedException}s for indicating that a test * provides no useful information. (See {@link org.junit.Assume} for more * information.) You have to call {@code assume} methods before you set * expectations of the {@code ExpectedException} rule. In this case the rule * will not handle consume the exceptions and it can be handled by the * framework. E.g. the following test is ignored by JUnit's default runner. * * <pre> &#064;Test * public void ignoredBecauseOfFailedAssumption() { * assumeTrue(false); // throws AssumptionViolatedException * thrown.expect(NullPointerException.class); * }</pre> * * <h3>AssertionErrors</h3> * * <p>JUnit uses {@link AssertionError}s for indicating that a test is failing. You * have to call {@code assert} methods before you set expectations of the * {@code ExpectedException} rule, if they should be handled by the framework. * E.g. the following test fails because of the {@code assertTrue} statement. * * <pre> &#064;Test * public void throwsUnhandled() { * assertTrue(false); // throws AssertionError * thrown.expect(NullPointerException.class); * }</pre> * * <h3>Missing Exceptions</h3> * <p>By default missing exceptions are reported with an error message * like "Expected test to throw an instance of foo". You can configure a different * message by means of {@link #reportMissingExceptionWithMessage(String)}. You * can use a {@code %s} placeholder for the description of the expected * exception. E.g. "Test doesn't throw %s." will fail with the error message * "Test doesn't throw an instance of foo.". * * @since 4.7 */ public class ExpectedException implements TestRule { /** * Returns a {@linkplain TestRule rule} that expects no exception to * be thrown (identical to behavior without this rule). */ public static ExpectedException none() { return new ExpectedException(); } private final ExpectedExceptionMatcherBuilder matcherBuilder = new ExpectedExceptionMatcherBuilder(); private String missingExceptionMessage= "Expected test to throw %s"; private ExpectedException() { } /** * This method does nothing. Don't use it. * @deprecated AssertionErrors are handled by default since JUnit 4.12. Just * like in JUnit &lt;= 4.10. */ @Deprecated public ExpectedException handleAssertionErrors() { return this; } /** * This method does nothing. Don't use it. * @deprecated AssumptionViolatedExceptions are handled by default since * JUnit 4.12. Just like in JUnit &lt;= 4.10. */ @Deprecated public ExpectedException handleAssumptionViolatedExceptions() { return this; } /** * Specifies the failure message for tests that are expected to throw * an exception but do not throw any. You can use a {@code %s} placeholder for * the description of the expected exception. E.g. "Test doesn't throw %s." * will fail with the error message * "Test doesn't throw an instance of foo.". * * @param message exception detail message * @return the rule itself */ public ExpectedException reportMissingExceptionWithMessage(String message) { missingExceptionMessage = message; return this; } public Statement apply(Statement base, org.junit.runner.Description description) { return new ExpectedExceptionStatement(base); } /** * Verify that your code throws an exception that is matched by * a Hamcrest matcher. * <pre> &#064;Test * public void throwsExceptionThatCompliesWithMatcher() { * NullPointerException e = new NullPointerException(); * thrown.expect(is(e)); * throw e; * }</pre> * * @deprecated use {@code org.hamcrest.junit.ExpectedException.expect()} */ @Deprecated public ExpectedException expect(Matcher<?> matcher) { matcherBuilder.add(matcher); return this; } /** * Verify that your code throws an exception that is an * instance of specific {@code type}. * <pre> &#064;Test * public void throwsExceptionWithSpecificType() { * thrown.expect(NullPointerException.class); * throw new NullPointerException(); * }</pre> */ public ExpectedException expect(Class<? extends Throwable> type) { expect(instanceOf(type)); return this; } /** * Verify that your code throws an exception whose message contains * a specific text. * <pre> &#064;Test * public void throwsExceptionWhoseMessageContainsSpecificText() { * thrown.expectMessage(&quot;happened&quot;); * throw new NullPointerException(&quot;What happened?&quot;); * }</pre> */ public ExpectedException expectMessage(String substring) { expectMessage(containsString(substring)); return this; } /** * Verify that your code throws an exception whose message is matched * by a Hamcrest matcher. * <pre> &#064;Test * public void throwsExceptionWhoseMessageCompliesWithMatcher() { * thrown.expectMessage(startsWith(&quot;What&quot;)); * throw new NullPointerException(&quot;What happened?&quot;); * }</pre> * * @deprecated use {@code org.hamcrest.junit.ExpectedException.expectMessage()} */ @Deprecated public ExpectedException expectMessage(Matcher<String> matcher) { expect(hasMessage(matcher)); return this; } @Deprecated public ExpectedException expectCause(Matcher<? extends Throwable> expectedCause) { expect(hasCause(expectedCause)); return this; } private class ExpectedExceptionStatement extends Statement { private final Statement next; public ExpectedExceptionStatement(Statement base) { next = base; } @Override public void evaluate() throws Throwable { try { next.evaluate(); } catch (Throwable e) { handleException(e); return; } if (isAnyExceptionExpected()) { failDueToMissingException(); } } } private void handleException(Throwable e) throws Throwable { if (isAnyExceptionExpected()) { assertThat(e, matcherBuilder.build()); } else { throw e; } } private boolean isAnyExceptionExpected() { return matcherBuilder.expectsThrowable(); } private void failDueToMissingException() throws AssertionError { fail(missingExceptionMessage()); } private String missingExceptionMessage() { String expectation= StringDescription.toString(matcherBuilder.build()); return format(missingExceptionMessage, expectation); } }
// This code is developed as part of the Java CoG Kit project // This message may not be removed or altered. package org.globus.cog.abstraction.impl.file.webdav; import java.io.File; import java.io.IOException; import java.net.PasswordAuthentication; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Vector; import org.apache.commons.httpclient.HttpURL; import org.apache.commons.httpclient.URIException; import org.apache.log4j.Logger; import org.apache.webdav.lib.WebdavResource; import org.globus.cog.abstraction.impl.common.AbstractionFactory; import org.globus.cog.abstraction.impl.common.IdentityImpl; import org.globus.cog.abstraction.impl.common.task.IllegalSpecException; import org.globus.cog.abstraction.impl.common.task.InvalidSecurityContextException; import org.globus.cog.abstraction.impl.common.task.ServiceContactImpl; import org.globus.cog.abstraction.impl.common.task.TaskSubmissionException; import org.globus.cog.abstraction.impl.file.DirectoryNotFoundException; import org.globus.cog.abstraction.impl.file.FileNotFoundException; import org.globus.cog.abstraction.impl.file.FileResourceUtil; import org.globus.cog.abstraction.impl.file.GeneralException; import org.globus.cog.abstraction.impl.file.GridFileImpl; import org.globus.cog.abstraction.impl.file.IllegalHostException; import org.globus.cog.abstraction.interfaces.ExecutableObject; import org.globus.cog.abstraction.interfaces.FileResource; import org.globus.cog.abstraction.interfaces.GridFile; import org.globus.cog.abstraction.interfaces.GridResource; import org.globus.cog.abstraction.interfaces.Identity; import org.globus.cog.abstraction.interfaces.SecurityContext; import org.globus.cog.abstraction.interfaces.ServiceContact; /** * Implements file resource API for webdav resource Supports only * absolute path names */ public class FileResourceImpl implements FileResource { private final String protocol = FileResource.WebDAV; private ServiceContact serviceContact = null; private SecurityContext securityContext = null; private String name = null; private Identity identity = null; private final int type = GridResource.FILE; private Hashtable attributes = null; private WebdavResource davClient = null; static Logger logger = Logger.getLogger(FileResourceImpl.class.getName()); private boolean started; /** throws exception */ public FileResourceImpl() throws Exception { this.identity = new IdentityImpl(); this.attributes = new Hashtable(); serviceContact = new ServiceContactImpl(); securityContext = AbstractionFactory.newSecurityContext("WebDAV"); } /** constructor to be used normally */ public FileResourceImpl(String name, ServiceContact serviceContact, SecurityContext securityContext) { this.identity = new IdentityImpl(); this.name = name; this.serviceContact = serviceContact; this.securityContext = securityContext; this.attributes = new Hashtable(); } /** Set the name of the resource */ public void setName(String name) { this.name = name; } /** Return name of the resource */ public String getName() { return this.name; } /** Set identity of the resource */ public void setIdentity(Identity identity) { this.identity = identity; } /** Return identity of the resource */ public Identity getIdentity() { return this.identity; } /** Return type = FILE which is defined in GridResource */ public int getType() { return this.type; } /** return protocol ="http" */ public String getProtocol() { return this.protocol; } /** set service contact */ public void setServiceContact(ServiceContact serviceContact) { this.serviceContact = serviceContact; } /** get service contact */ public ServiceContact getServiceContact() { return serviceContact; } /** Set the appropriate SecurityContext for the FileResource */ public void setSecurityContext(SecurityContext securityContext) { this.securityContext = securityContext; } /** Get the securityContext for the remote resource */ public SecurityContext getSecurityContext() { return this.securityContext; } /** * Create the davClient and authenticate with the resource. serviceContact * should be in the form of a url */ public void start() throws IllegalHostException, InvalidSecurityContextException, GeneralException { try { String contact = serviceContact.getContact().toString(); if (!contact.startsWith("http")) { contact = "http://" + contact; } HttpURL hrl = new HttpURL(contact); PasswordAuthentication credentials = (PasswordAuthentication) securityContext .getCredentials(); String username = credentials.getUserName(); String password = String.valueOf(credentials.getPassword()); hrl.setUserinfo(username, password); davClient = new WebdavResource(hrl); started = true; } catch (URIException ue) { throw new IllegalHostException( "Error while communicating with the webdav server", ue); } catch (Exception e) { throw new GeneralException("Cannot connect to the webdav server", e); } } /** Stop the davClient from connecting to the server */ public void stop() throws GeneralException { try { davClient.close(); started = false; } catch (Exception e) { throw new GeneralException( "Error while stopping the Webdav server", e); } } public boolean isStarted() { return started; } /** Equivalent to cd command */ public void setCurrentDirectory(String directory) throws DirectoryNotFoundException, GeneralException { try { davClient.setPath(directory); } catch (IOException ie) { throw new DirectoryNotFoundException(directory + " is not a valid directory", ie); } catch (Exception e) { throw new GeneralException("Cannot set the current directory", e); } } /** Return Current Directory's name */ public String getCurrentDirectory() throws GeneralException { try { return davClient.getPath(); } catch (Exception e) { throw new GeneralException("Cannot get the current directory", e); } } /** Equivalent to ls command in the current directory */ public Collection list() throws GeneralException { Vector listVector = new Vector(); try { if (davClient.isCollection() == true) { String[] listArray = davClient.list(); for (int i = 0; i < listArray.length; i++) { String fileName = getCurrentDirectory() + "/" + listArray[i]; listVector.add(createGridFile(fileName)); } } else { listVector.add(createGridFile(davClient.getName())); } return listVector; } catch (Exception e) { throw new GeneralException( "Cannot list the elements of the current directory", e); } } /** Equivalent to ls command on the given directory */ public Collection list(String directory) throws DirectoryNotFoundException, GeneralException { // Store currentDir String currentDirectory = getCurrentDirectory(); // Change directory setCurrentDirectory(directory); Collection list = list(); // Come back to original directory setCurrentDirectory(currentDirectory); return list; } /** Equivalent to mkdir */ public void createDirectory(String directory) throws GeneralException { try { String currentPath = getCurrentDirectory(); if (davClient.mkcolMethod(directory) == false) { throw new GeneralException("Cannot Create Directory"); } setCurrentDirectory(currentPath); } catch (Exception e) { throw new GeneralException("Cannot create the directory", e); } } public void createDirectories(String directory) throws GeneralException { FileResourceUtil.createDirectories(this, directory); } /** * Remove directory and its files if force = true. Else remove directory * only if empty */ public void deleteDirectory(String directory, boolean force) throws DirectoryNotFoundException, GeneralException { try { Collection list = list(directory); if (list == null || force == true) { davClient.deleteMethod(directory); } } catch (Exception e) { throw new GeneralException("Cannot delete the given directory", e); } } /** Equivalent to rm command */ public void deleteFile(String file) throws FileNotFoundException, GeneralException { try { davClient.deleteMethod(file); } catch (IOException ie) { throw new FileNotFoundException(file + " is not a valid file", ie); } catch (Exception e) { throw new GeneralException("Cannot delete the given file", e); } } /** Equivalent to cp/copy command */ public void getFile(String remoteFilename, String localFileName) throws FileNotFoundException, GeneralException { File localFile = new File(localFileName); try { davClient.getMethod(remoteFilename, localFile); } catch (IOException ie) { throw new FileNotFoundException( "The local file or the remote file is not a valid file", ie); } catch (Exception e) { throw new GeneralException("Cannot retrieve the given file", e); } } /** Copy a local file to a remote file. Default option 'overwrite' */ public void putFile(String localFileName, String remoteFileName) throws FileNotFoundException, GeneralException { File localFile = new File(localFileName); try { davClient.putMethod(remoteFileName, localFile); } catch (IOException ie) { throw new FileNotFoundException( "The local file or the remote file is not a valid file", ie); } catch (Exception e) { throw new GeneralException("Cannot transfer the given file", e); } } /** Equivalent to the cp -r command */ public void getDirectory(String remoteDirName, String localDirName) throws DirectoryNotFoundException, GeneralException { File localDir = new File(localDirName); GridFile gridFile = null; if (!localDir.exists()) { localDir.mkdir(); } if (isDirectory(remoteDirName) == false) { throw new DirectoryNotFoundException("Remote directory not found"); } for (Iterator iterator = list(remoteDirName).iterator(); iterator .hasNext();) { gridFile = (GridFile) iterator.next(); try { if (!isDirectory(gridFile.getAbsolutePathName())) { getFile(gridFile.getAbsolutePathName(), localDirName + File.separator + gridFile.getName()); } else { getDirectory(gridFile.getAbsolutePathName(), localDirName + File.separator + gridFile.getName()); } } catch (Exception ex) { throw new GeneralException("General Exception", ex); } } } /** Equivalent to cp -r command */ public void putDirectory(String localDirName, String remoteDirName) throws DirectoryNotFoundException, GeneralException { File localDir = new File(localDirName); if (!localDir.exists()) { throw new DirectoryNotFoundException("Local directory not found"); } if (localDir.isFile()) { throw new DirectoryNotFoundException(localDirName + " is a file"); } try { if (!exists(remoteDirName)) { createDirectory(remoteDirName); } } catch (FileNotFoundException fe) { throw new DirectoryNotFoundException( "Cannot create the remote directory: " + remoteDirName); } if (!isDirectory(remoteDirName)) { throw new DirectoryNotFoundException(remoteDirName + " is a file"); } String files[] = localDir.list(); for (int index = 0; index < files.length; index++) { File localFile = new File(localDirName + File.separator + files[index]); try { if (!localFile.isDirectory()) { putFile(localDirName + File.separator + files[index], remoteDirName + "/" + files[index]); } else { putDirectory(localDirName + File.separator + files[index], remoteDirName + "/" + files[index]); } } catch (Exception e) { throw new GeneralException("Cannot transfer the directory", e); } } } /** * mget - copy multiple files from remote server */ public void getMultipleFiles(String[] remoteFileNames, String[] localFileNames) throws FileNotFoundException, GeneralException { //If list of sources is not equal to list of destinations then error if (localFileNames.length != remoteFileNames.length) throw new GeneralException( "Number of source and destination file names has to be the same"); //Check every remote file name. If it is a file use getfile else use // getdir for (int index = 0; index < remoteFileNames.length; index++) { try { if (exists(remoteFileNames[index])) { if (isDirectory(remoteFileNames[index]) == false) { getFile(remoteFileNames[index], localFileNames[index]); } else { getDirectory(remoteFileNames[index], localFileNames[index]); } } } catch (Exception e) { throw new GeneralException("Cannot perform mGet", e); } } } /** * mget - copy multiple files from remote server to local dir */ public void getMultipleFiles(String[] remoteFileNames, String localDirName) throws FileNotFoundException, DirectoryNotFoundException, GeneralException { for (int index = 0; index < remoteFileNames.length; index++) { try { // Get the file name only to append to localdir String remoteFileName = remoteFileNames[index] .substring(remoteFileNames[index].lastIndexOf("/") + 1); // Check every remote file name. If it is a file use getfile // else use getdir if (exists(remoteFileNames[index])) { if (isDirectory(remoteFileNames[index]) == false) { getFile(remoteFileNames[index], localDirName + File.separator + remoteFileName); } else { getDirectory(remoteFileNames[index], localDirName + File.separator + remoteFileName); } } } catch (Exception e) { throw new GeneralException("Cannot perform mGet", e); } } } /** * mput - copy multiple files from local machine to remote destinations */ public void putMultipleFiles(String[] localFileNames, String[] remoteFileNames) throws FileNotFoundException, GeneralException { // If list of source not equal to list of destinations then error if (localFileNames.length != remoteFileNames.length) throw new GeneralException( "Number of source and destination file names has to be the same"); //Check every file name given. If file is a directory use putdir else // use putfile for (int index = 0; index < localFileNames.length; index++) { File localFile = new File(localFileNames[index]); try { if (!localFile.isDirectory()) { putFile(localFileNames[index], remoteFileNames[index]); } else { putDirectory(localFileNames[index], remoteFileNames[index]); } } catch (Exception e) { throw new GeneralException("Cannot perform mput", e); } } } /** * mput - copy multiple files from local machines to remote directory */ public void putMultipleFiles(String[] localFileNames, String remoteDirName) throws FileNotFoundException, DirectoryNotFoundException, GeneralException { //Check every file name. If file name is a directory use putdir else // use putfile for (int index = 0; index < localFileNames.length; index++) { File localFile = new File(localFileNames[index]); try { if (!localFile.isDirectory()) { putFile(localFileNames[index], remoteDirName + "/" + localFile.getName()); } else { putDirectory(localFileNames[index], remoteDirName + "/" + localFile.getName()); } } catch (Exception e) { throw new GeneralException("Cannot perform mput", e); } } } /** * Rename a remote file. */ public void rename(String remoteFileName1, String remoteFileName2) throws FileNotFoundException, GeneralException { throw new GeneralException("rename not implemented for webdav"); } public void changeMode(String filename, int mode) throws FileNotFoundException, GeneralException { throw new GeneralException( "chmod(filename, mode) not implemented for webdav"); } public void changeMode(GridFile newGridFile) throws FileNotFoundException, GeneralException { throw new GeneralException( "chmod(GridFile) not implemented for webdav"); } /** get file information */ public GridFile getGridFile(String fileName) throws FileNotFoundException, GeneralException { return createGridFile(fileName); } public boolean exists(String filename) throws FileNotFoundException, GeneralException { String currentPath = getCurrentDirectory(); boolean result = false; try { setCurrentDirectory(filename); result = davClient.exists(); setCurrentDirectory(currentPath); } catch (Exception e) { result = false; } return result; } public boolean isDirectory(String dirName) throws GeneralException { boolean isDir = true; String currentDirectory = getCurrentDirectory(); try { setCurrentDirectory(dirName); if (davClient.isCollection() == false) isDir = false; else isDir = true; setCurrentDirectory(currentDirectory); } catch (Exception e) { isDir = false; } return isDir; } /** Not implemented in Webdav * */ public void submit(ExecutableObject commandWorkflow) throws IllegalSpecException, TaskSubmissionException { } /** Set an attribute * */ public void setAttribute(String name, Object value) { this.attributes.put(name, value); } public Enumeration getAllAttributes() { return this.attributes.elements(); } /** Get an attribute * */ public Object getAttribute(String name) { return this.attributes.get(name); } /** method to create gridfile */ private GridFile createGridFile(Object obj) throws GeneralException { GridFile gridFile = new GridFileImpl(); String fileName = (String) obj; try { String currentPath = getCurrentDirectory(); davClient.setPath(fileName); gridFile.setAbsolutePathName(davClient.getPath()); gridFile.setLastModified(String.valueOf(new Date(davClient .getGetLastModified()))); if (davClient.isCollection() == false) { gridFile.setFileType(GridFile.FILE); } if (davClient.isCollection() == true) { gridFile.setFileType(GridFile.DIRECTORY); } gridFile.setName(davClient.getName()); gridFile.setSize(davClient.getGetContentLength()); davClient.setPath(currentPath); } catch (Exception e) { throw new GeneralException("Exception in creating grid file ", e); } return gridFile; } /** Delete the specified local directory */ private void removeLocalDirectory(String tempDirName) { File tempFile = new File(tempDirName); String[] fileNames = tempFile.list(); if (fileNames != null) { for (int i = 0; i < fileNames.length; i++) { File newFile = new File(tempDirName + File.separator + fileNames[i]); if (newFile.isFile() == true) { newFile.delete(); } else { removeLocalDirectory(newFile.getAbsolutePath()); } } } tempFile.delete(); } }
package org.jvalue.ceps.data; import java.util.LinkedList; import java.util.List; import org.jvalue.ceps.db.DbAccessor; import org.jvalue.ceps.db.DbAccessorFactory; import org.jvalue.ceps.utils.Assert; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; final class DataSourceDb { private static final String DB_NAME = "odsSources"; private static DataSourceDb instance; public static DataSourceDb getInstance() { if (instance == null) instance = new DataSourceDb( DbAccessorFactory.getCouchDbAccessor(DB_NAME)); return instance; } private final ObjectMapper mapper = new ObjectMapper(); private final DbAccessor dbAccessor; private DataSourceDb(DbAccessor dbAccessor) { Assert.assertNotNull(dbAccessor); this.dbAccessor = dbAccessor; } public void add(DataSource source) { Assert.assertNotNull(source); dbAccessor.insert(mapper.valueToTree(source)); } public void remove(DataSource source) { Assert.assertNotNull(source); dbAccessor.delete(mapper.valueToTree(source)); } public List<DataSource> getAll() { List<JsonNode> jsonObjects = dbAccessor.getAll(); List<DataSource> sources = new LinkedList<DataSource>(); for (JsonNode json : jsonObjects) { try { sources.add(mapper.treeToValue(json, DataSource.class)); } catch (JsonProcessingException jpe) { throw new IllegalStateException(jpe); } } return sources; } }
package com.github.gabrielruiu.spring.cloud.config.redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.config.environment.PropertySource; import org.springframework.cloud.config.server.config.ConfigServerProperties; import org.springframework.data.redis.core.StringRedisTemplate; import java.util.*; /** * @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com) */ public class RedisConfigPropertySourceProvider { private StringRedisTemplate stringRedisTemplate; private RedisConfigKeysProvider redisConfigKeysProvider; private RedisConfigKeysUtilities redisConfigKeysUtilities; private ConfigServerProperties configServerProperties; @Autowired public RedisConfigPropertySourceProvider(StringRedisTemplate stringRedisTemplate, RedisConfigKeysProvider redisConfigKeysProvider, RedisConfigKeysUtilities redisConfigKeysUtilities, ConfigServerProperties configServerProperties) { this.stringRedisTemplate = stringRedisTemplate; this.redisConfigKeysProvider = redisConfigKeysProvider; this.redisConfigKeysUtilities = redisConfigKeysUtilities; this.configServerProperties = configServerProperties; } public PropertySource getPropertySource(String application, String profile, String label) { List<String> keys = new ArrayList<>(redisConfigKeysProvider.getKeys(application, profile, label)); if (keys.size() > 0) { List<String> propertyValues = stringRedisTemplate.opsForValue().multiGet(keys); Map<String, String> properties = new HashMap<>(); for (int i=0; i<keys.size(); i++) { String propertyName = formatKey(application, profile, label, keys.get(i)); String propertyValue = propertyValues.get(i); properties.put(propertyName, propertyValue); } return new PropertySource(getPropertySourceName(application, profile), properties); } return null; } private String formatKey(String application, String profile, String label, String key) { return redisConfigKeysUtilities.formatKey(application, profile, label, key); } private String getPropertySourceName(String application, String profile) { if (!Objects.equals(profile, configServerProperties.getDefaultProfile())) { return application + "-" + profile; } return application; } }
package org.lightmare.cache; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.persistence.EntityManagerFactory; import org.apache.log4j.Logger; import org.lightmare.config.Configuration; import org.lightmare.deploy.MetaCreator; import org.lightmare.ejb.exceptions.BeanInUseException; import org.lightmare.libraries.LibraryLoader; import org.lightmare.rest.providers.RestProvider; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.WatchUtils; /** * Container class to save {@link MetaData} for bean interface {@link Class} and * connections ({@link EntityManagerFactory}) for unit names * * @author Levan Tsinadze * @since 0.0.45-SNAPSHOT */ public class MetaContainer { // Cached instance of MetaCreator private static MetaCreator creator; /** * {@link Configuration} container class for server */ public static final Map<String, Configuration> CONFIGS = new ConcurrentHashMap<String, Configuration>(); // Cached bean meta data private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>(); // Cached bean class name by its URL for undeploy processing private static final ConcurrentMap<URL, Collection<String>> EJB_URLS = new ConcurrentHashMap<URL, Collection<String>>(); private static final Logger LOG = Logger.getLogger(MetaContainer.class); /** * Gets cached {@link MetaCreator} object * * @return {@link MetaCreator} */ public static MetaCreator getCreator() { synchronized (MetaContainer.class) { return creator; } } /** * Caches {@link MetaCreator} object * * @param metaCreator */ public static void setCreator(MetaCreator metaCreator) { synchronized (MetaContainer.class) { creator = metaCreator; } } /** * Caches {@link Configuration} for specific {@link URL} array * * @param archives * @param config */ public static void putConfig(URL[] archives, Configuration config) { if (CollectionUtils.valid(archives)) { boolean containsPath; for (URL archive : archives) { String path = WatchUtils.clearPath(archive.getFile()); containsPath = CONFIGS.containsKey(path); if (ObjectUtils.notTrue(containsPath)) { CONFIGS.put(path, config); } } } } /** * Gets {@link Configuration} from cache for specific {@link URL} array * * @param archives * @param config */ public static Configuration getConfig(URL[] archives) { Configuration config; URL archive = CollectionUtils.getFirst(archives); if (ObjectUtils.notNull(archive)) { String path = WatchUtils.clearPath(archive.getFile()); config = CONFIGS.get(path); } else { config = null; } return config; } /** * Adds {@link MetaData} to cache on specified bean name if absent and * returns previous value on this name or null if such value does not exists * * @param beanName * @param metaData * @return */ public static MetaData addMetaData(String beanName, MetaData metaData) { return EJBS.putIfAbsent(beanName, metaData); } /** * Check if {@link MetaData} is ceched for specified bean name if true * throws {@link BeanInUseException} * * @param beanName * @param metaData * @throws BeanInUseException */ public static void checkAndAddMetaData(String beanName, MetaData metaData) throws BeanInUseException { MetaData tmpMeta = addMetaData(beanName, metaData); if (ObjectUtils.notNull(tmpMeta)) { throw BeanInUseException.get(beanName); } } /** * Checks if bean with associated name deployed and if it is, then checks if * deployment is in progress * * @param beanName * @return boolean */ public static boolean checkMetaData(String beanName) { boolean check; MetaData metaData = EJBS.get(beanName); check = metaData == null; if (ObjectUtils.notTrue(check)) { check = metaData.isInProgress(); } return check; } /** * Checks if bean with associated name is already deployed * * @param beanName * @return boolean */ public boolean checkBean(String beanName) { return EJBS.containsKey(beanName); } /** * Waits while passed {@link MetaData} instance is in progress * * @param inProgress * @param metaData * @throws IOException */ private static void awaitProgress(boolean inProgress, MetaData metaData) throws IOException { while (inProgress) { try { metaData.wait(); inProgress = metaData.isInProgress(); } catch (InterruptedException ex) { throw new IOException(ex); } } } /** * Waits while {@link MetaData#isInProgress()} is true * * @param metaData * @throws IOException */ public static void awaitMetaData(MetaData metaData) throws IOException { boolean inProgress = metaData.isInProgress(); if (inProgress) { synchronized (metaData) { awaitProgress(inProgress, metaData); } } } /** * Gets deployed bean {@link MetaData} by name without checking deployment * progress * * @param beanName * @return {@link MetaData} */ public static MetaData getMetaData(String beanName) { return EJBS.get(beanName); } /** * Check if {@link MetaData} with associated name deployed and if it is * waits while {@link MetaData#isInProgress()} true before return it * * @param beanName * @return {@link MetaData} * @throws IOException */ public static MetaData getSyncMetaData(String beanName) throws IOException { MetaData metaData = getMetaData(beanName); if (metaData == null) { throw new IOException(String.format("Bean %s is not deployed", beanName)); } awaitMetaData(metaData); return metaData; } /** * Gets bean name by containing archive {@link URL} address * * @param url * @return {@link Collection}<code><String></code> */ public static Collection<String> getBeanNames(URL url) { synchronized (MetaContainer.class) { return EJB_URLS.get(url); } } /** * checks containing archive {@link URL} address * * @param url * @return <code>boolean</code> */ public static boolean chackDeployment(URL url) { synchronized (MetaContainer.class) { return EJB_URLS.containsKey(url); } } /** * Removes cached bean names {@link Collection} by containing file * {@link URL} as key * * @param url */ public static void removeBeanNames(URL url) { synchronized (MetaContainer.class) { EJB_URLS.remove(url); } } /** * Caches bean name by {@link URL} of jar ear or any file * * @param beanName */ public static void addBeanName(URL url, String beanName) { synchronized (MetaContainer.class) { Collection<String> beanNames = EJB_URLS.get(url); if (CollectionUtils.invalid(beanNames)) { beanNames = new HashSet<String>(); EJB_URLS.put(url, beanNames); } beanNames.add(beanName); } } /** * Lists set for deployed application {@link URL}'s * * @return {@link Set}<URL> */ public static Set<URL> listApplications() { Set<URL> apps = EJB_URLS.keySet(); return apps; } /** * Clears connection from cache * * @param metaData * @throws IOException */ private static void clearConnection(MetaData metaData) throws IOException { Collection<ConnectionData> connections = metaData.getConnections(); if (CollectionUtils.valid(connections)) { for (ConnectionData connection : connections) { // Gets connection to clear String unitName = connection.getUnitName(); ConnectionSemaphore semaphore = connection.getConnection(); if (semaphore == null) { semaphore = ConnectionContainer.getConnection(unitName); } if (ObjectUtils.notNull(semaphore) && semaphore.decrementUser() <= ConnectionSemaphore.MINIMAL_USERS) { ConnectionContainer.removeConnection(unitName); } } } } /** * Removes bean (removes it's {@link MetaData} from cache) by bean class * name * * @param beanName * @throws IOException */ public static void undeployBean(String beanName) throws IOException { MetaData metaData = null; try { metaData = getSyncMetaData(beanName); } catch (IOException ex) { LogUtils.error(LOG, ex, "Could not get bean resources %s cause %s", beanName, ex.getMessage()); } // Removes MetaData from cache removeMeta(beanName); if (ObjectUtils.notNull(metaData)) { // Removes appropriated resource class from REST service if (RestContainer.hasRest()) { RestProvider.remove(metaData.getBeanClass()); } clearConnection(metaData); ClassLoader loader = metaData.getLoader(); LibraryLoader.closeClassLoader(loader); metaData = null; } } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link URL} of * archive file * * @param url * @throws IOException */ public static boolean undeploy(URL url) throws IOException { boolean valid; synchronized (MetaContainer.class) { Collection<String> beanNames = getBeanNames(url); valid = CollectionUtils.valid(beanNames); if (valid) { for (String beanName : beanNames) { undeployBean(beanName); } } removeBeanNames(url); } return valid; } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link File} * of archive file * * @param file * @throws IOException */ public static boolean undeploy(File file) throws IOException { boolean valid; URL url = file.toURI().toURL(); valid = undeploy(url); return valid; } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link File} * path of archive file * * @param path * @throws IOException */ public static boolean undeploy(String path) throws IOException { boolean valid; File file = new File(path); valid = undeploy(file); return valid; } /** * Removed {@link MetaData} from cache * * @param beanName */ public static void removeMeta(String beanName) { EJBS.remove(beanName); } /** * Gets {@link java.util.Iterator}<MetaData> over all cached * {@link org.lightmare.cache.MetaData} * * @return {@link java.util.Iterator}<MetaData> */ public static Iterator<MetaData> getBeanClasses() { return EJBS.values().iterator(); } /** * Removes all cached resources */ public static void clear() { if (ObjectUtils.notNull(creator)) { synchronized (MetaContainer.class) { if (ObjectUtils.notNull(creator)) { creator.clear(); creator = null; } } } CONFIGS.clear(); EJBS.clear(); EJB_URLS.clear(); } }
package com.creativemd.playerrevive; import java.util.UUID; import com.creativemd.creativecore.common.packet.CreativeCorePacket; import com.creativemd.creativecore.gui.container.SubContainer; import com.creativemd.creativecore.gui.container.SubGui; import com.creativemd.creativecore.gui.opener.CustomGuiHandler; import com.creativemd.creativecore.gui.opener.GuiHandler; import com.creativemd.playerrevive.capability.CapaReviveStorage; import com.creativemd.playerrevive.client.PlayerReviveClient; import com.creativemd.playerrevive.gui.SubContainerRevive; import com.creativemd.playerrevive.gui.SubGuiRevive; import com.creativemd.playerrevive.packet.PlayerRevivalPacket; import com.creativemd.playerrevive.packet.PlayerRevivalProgress; import com.creativemd.playerrevive.server.PlayerReviveServer; import com.creativemd.playerrevive.server.ReviveEventServer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.fml.common.Mod.EventHandler; @Mod(modid = PlayerRevive.modid, version = PlayerRevive.version, name = "Player Revive", acceptedMinecraftVersions = "") public class PlayerRevive { @SidedProxy(clientSide = "com.creativemd.playerrevive.client.PlayerReviveClient", serverSide = "com.creativemd.playerrevive.server.PlayerReviveServer") public static PlayerReviveServer proxy; public static final String modid = "playerrevive"; public static final String version = "0.1"; public static float playerReviveTime = 100; public static int playerReviveSurviveTime = 1200; public static int playerHealthAfter = 2; public static int playerFoodAfter = 6; public static boolean banPlayerAfterDeath = false; @EventHandler public void init(FMLInitializationEvent event) { CreativeCorePacket.registerPacket(PlayerRevivalPacket.class, "PLRevival"); CreativeCorePacket.registerPacket(PlayerRevivalProgress.class, "PLProgress"); GuiHandler.registerGuiHandler("plrevive", new CustomGuiHandler() { @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) { return new SubGuiRevive(); } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) { Revival revive = null; if(player.getEntityWorld().isRemote) revive = getClientRevival(); else revive = PlayerReviveServer.playerRevivals.get(EntityPlayer.getUUID(player.getGameProfile())); if(revive != null) return new SubContainerRevive(player, revive, false); return null; } @SideOnly(Side.CLIENT) public Revival getClientRevival() { return PlayerReviveClient.playerRevive; } }); GuiHandler.registerGuiHandler("plreviver", new CustomGuiHandler() { @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) { return new SubGuiRevive(); } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) { Revival revive = null; if(player.getEntityWorld().isRemote) revive = new Revival(); else revive = PlayerReviveServer.playerRevivals.get(UUID.fromString(nbt.getString("uuid"))); if(revive != null) return new SubContainerRevive(player, revive, true); return null; } }); CapabilityManager.INSTANCE.register(Revival.class, new CapaReviveStorage(), new CapaReviveStorage.Factory()); MinecraftForge.EVENT_BUS.register(new ReviveEventServer()); proxy.initSide(); } }
package com.github.steveice10.mc.protocol.packet.ingame.server; import com.github.steveice10.mc.auth.data.GameProfile; import com.github.steveice10.mc.protocol.data.MagicValues; import com.github.steveice10.mc.protocol.data.game.PlayerListEntry; import com.github.steveice10.mc.protocol.data.game.PlayerListEntryAction; import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode; import com.github.steveice10.mc.protocol.data.message.Message; import com.github.steveice10.mc.protocol.packet.MinecraftPacket; import com.github.steveice10.packetlib.io.NetInput; import com.github.steveice10.packetlib.io.NetOutput; import java.io.IOException; import java.util.UUID; public class ServerPlayerListEntryPacket extends MinecraftPacket { private PlayerListEntryAction action; private PlayerListEntry entries[]; @SuppressWarnings("unused") private ServerPlayerListEntryPacket() { } public ServerPlayerListEntryPacket(PlayerListEntryAction action, PlayerListEntry entries[]) { this.action = action; this.entries = entries; } public PlayerListEntryAction getAction() { return this.action; } public PlayerListEntry[] getEntries() { return this.entries; } @Override public void read(NetInput in) throws IOException { this.action = MagicValues.key(PlayerListEntryAction.class, in.readVarInt()); this.entries = new PlayerListEntry[in.readVarInt()]; for(int count = 0; count < this.entries.length; count++) { UUID uuid = in.readUUID(); GameProfile profile; if(this.action == PlayerListEntryAction.ADD_PLAYER) { profile = new GameProfile(uuid, in.readString()); } else { profile = new GameProfile(uuid, null); } PlayerListEntry entry = null; switch(this.action) { case ADD_PLAYER: int properties = in.readVarInt(); for(int index = 0; index < properties; index++) { String propertyName = in.readString(); String value = in.readString(); String signature = null; if(in.readBoolean()) { signature = in.readString(); } profile.getProperties().add(new GameProfile.Property(propertyName, value, signature)); } int g = in.readVarInt(); GameMode gameMode = MagicValues.key(GameMode.class, g < 0 ? 0 : g); int ping = in.readVarInt(); Message displayName = null; if(in.readBoolean()) { displayName = Message.fromString(in.readString()); } entry = new PlayerListEntry(profile, gameMode, ping, displayName); break; case UPDATE_GAMEMODE: g = in.readVarInt(); GameMode mode = MagicValues.key(GameMode.class, g < 0 ? 0 : g); entry = new PlayerListEntry(profile, mode); break; case UPDATE_LATENCY: int png = in.readVarInt(); entry = new PlayerListEntry(profile, png); break; case UPDATE_DISPLAY_NAME: Message disp = null; if(in.readBoolean()) { disp = Message.fromString(in.readString()); } entry = new PlayerListEntry(profile, disp); break; case REMOVE_PLAYER: entry = new PlayerListEntry(profile); break; } this.entries[count] = entry; } } @Override public void write(NetOutput out) throws IOException { out.writeVarInt(MagicValues.value(Integer.class, this.action)); out.writeVarInt(this.entries.length); for(PlayerListEntry entry : this.entries) { out.writeUUID(entry.getProfile().getId()); switch(this.action) { case ADD_PLAYER: out.writeString(entry.getProfile().getName()); out.writeVarInt(entry.getProfile().getProperties().size()); for(GameProfile.Property property : entry.getProfile().getProperties()) { out.writeString(property.getName()); out.writeString(property.getValue()); out.writeBoolean(property.hasSignature()); if(property.hasSignature()) { out.writeString(property.getSignature()); } } out.writeVarInt(MagicValues.value(Integer.class, entry.getGameMode())); out.writeVarInt(entry.getPing()); out.writeBoolean(entry.getDisplayName() != null); if(entry.getDisplayName() != null) { out.writeString(entry.getDisplayName().toJsonString()); } break; case UPDATE_GAMEMODE: out.writeVarInt(MagicValues.value(Integer.class, entry.getGameMode())); break; case UPDATE_LATENCY: out.writeVarInt(entry.getPing()); break; case UPDATE_DISPLAY_NAME: out.writeBoolean(entry.getDisplayName() != null); if(entry.getDisplayName() != null) { out.writeString(entry.getDisplayName().toJsonString()); } break; case REMOVE_PLAYER: break; } } } }
package org.lightmare.cache; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.persistence.EntityManagerFactory; import org.apache.log4j.Logger; import org.lightmare.config.Configuration; import org.lightmare.deploy.MetaCreator; import org.lightmare.ejb.exceptions.BeanInUseException; import org.lightmare.libraries.LibraryLoader; import org.lightmare.rest.providers.RestProvider; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.WatchUtils; /** * Container class to save {@link MetaData} for bean interface {@link Class} and * connections ({@link EntityManagerFactory}) for unit names * * @author Levan * */ public class MetaContainer { // Cached instance of MetaCreator private static MetaCreator creator; /** * {@link Configuration} container class for server */ public static final Map<String, Configuration> CONFIGS = new ConcurrentHashMap<String, Configuration>(); // Cached bean meta data private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>(); // Cached bean class name by its URL for undeploy processing private static final ConcurrentMap<URL, Collection<String>> EJB_URLS = new ConcurrentHashMap<URL, Collection<String>>(); private static final Logger LOG = Logger.getLogger(MetaContainer.class); /** * Gets cached {@link MetaCreator} object * * @return */ public static MetaCreator getCreator() { synchronized (MetaContainer.class) { return creator; } } /** * Caches {@link MetaCreator} object * * @param metaCreator */ public static void setCreator(MetaCreator metaCreator) { synchronized (MetaContainer.class) { creator = metaCreator; } } /** * Caches {@link Configuration} for specific {@link URL} array * * @param archives * @param config */ public static void putConfig(URL[] archives, Configuration config) { if (CollectionUtils.valid(archives)) { boolean containsPath; for (URL archive : archives) { String path = WatchUtils.clearPath(archive.getFile()); containsPath = CONFIGS.containsKey(path); if (ObjectUtils.notTrue(containsPath)) { CONFIGS.put(path, config); } } } } /** * Gets {@link Configuration} from cache for specific {@link URL} array * * @param archives * @param config */ public static Configuration getConfig(URL[] archives) { Configuration config; URL archive = CollectionUtils.getFirst(archives); if (ObjectUtils.notNull(archive)) { String path = WatchUtils.clearPath(archive.getFile()); config = CONFIGS.get(path); } else { config = null; } return config; } /** * Adds {@link MetaData} to cache on specified bean name if absent and * returns previous value on this name or null if such value does not exists * * @param beanName * @param metaData * @return */ public static MetaData addMetaData(String beanName, MetaData metaData) { return EJBS.putIfAbsent(beanName, metaData); } /** * Check if {@link MetaData} is ceched for specified bean name if true * throws {@link BeanInUseException} * * @param beanName * @param metaData * @throws BeanInUseException */ public static void checkAndAddMetaData(String beanName, MetaData metaData) throws BeanInUseException { MetaData tmpMeta = addMetaData(beanName, metaData); if (ObjectUtils.notNull(tmpMeta)) { throw BeanInUseException.get("bean %s is alredy in use", beanName); } } /** * Checks if bean with associated name deployed and if yes if is deployment * in progress * * @param beanName * @return boolean */ public static boolean checkMetaData(String beanName) { boolean check; MetaData metaData = EJBS.get(beanName); check = metaData == null; if (ObjectUtils.notTrue(check)) { check = metaData.isInProgress(); } return check; } /** * Checks if bean with associated name deployed * * @param beanName * @return boolean */ public boolean checkBean(String beanName) { return EJBS.containsKey(beanName); } /** * Waits while passed {@link MetaData} instance is in progress * * @param inProgress * @param metaData * @throws IOException */ private static void awaitProgress(boolean inProgress, MetaData metaData) throws IOException { while (inProgress) { try { metaData.wait(); inProgress = metaData.isInProgress(); } catch (InterruptedException ex) { throw new IOException(ex); } } } /** * Waits while {@link MetaData#isInProgress()} is true * * @param metaData * @throws IOException */ public static void awaitMetaData(MetaData metaData) throws IOException { boolean inProgress = metaData.isInProgress(); if (inProgress) { synchronized (metaData) { awaitProgress(inProgress, metaData); } } } /** * Gets deployed bean {@link MetaData} by name without checking deployment * progress * * @param beanName * @return {@link MetaData} */ public static MetaData getMetaData(String beanName) { return EJBS.get(beanName); } /** * Check if {@link MetaData} with associated name deployed and if it is * waits while {@link MetaData#isInProgress()} true before return it * * @param beanName * @return {@link MetaData} * @throws IOException */ public static MetaData getSyncMetaData(String beanName) throws IOException { MetaData metaData = getMetaData(beanName); if (metaData == null) { throw new IOException(String.format("Bean %s is not deployed", beanName)); } awaitMetaData(metaData); return metaData; } /** * Gets bean name by containing archive {@link URL} address * * @param url * @return */ public static Collection<String> getBeanNames(URL url) { synchronized (MetaContainer.class) { return EJB_URLS.get(url); } } /** * checks containing archive {@link URL} address * * @param url * @return */ public static boolean chackDeployment(URL url) { synchronized (MetaContainer.class) { return EJB_URLS.containsKey(url); } } /** * Removes cached bean names {@link Collection} by containing file * {@link URL} as key * * @param url */ public static void removeBeanNames(URL url) { synchronized (MetaContainer.class) { EJB_URLS.remove(url); } } /** * Caches bean name by {@link URL} of jar ear or any file * * @param beanName */ public static void addBeanName(URL url, String beanName) { synchronized (MetaContainer.class) { Collection<String> beanNames = EJB_URLS.get(url); if (CollectionUtils.invalid(beanNames)) { beanNames = new HashSet<String>(); EJB_URLS.put(url, beanNames); } beanNames.add(beanName); } } /** * Lists set for deployed application {@link URL}'s * * @return {@link Set}<URL> */ public static Set<URL> listApplications() { Set<URL> apps = EJB_URLS.keySet(); return apps; } /** * Clears connection from cache * * @param metaData * @throws IOException */ private static void clearConnection(MetaData metaData) throws IOException { Collection<ConnectionData> connections = metaData.getConnections(); if (CollectionUtils.valid(connections)) { for (ConnectionData connection : connections) { // Gets connection to clear String unitName = connection.getUnitName(); ConnectionSemaphore semaphore = connection.getConnection(); if (semaphore == null) { semaphore = ConnectionContainer.getConnection(unitName); } if (ObjectUtils.notNull(semaphore) && semaphore.decrementUser() <= ConnectionSemaphore.MINIMAL_USERS) { ConnectionContainer.removeConnection(unitName); } } } } /** * Removes bean (removes it's {@link MetaData} from cache) by bean class * name * * @param beanName * @throws IOException */ public static void undeployBean(String beanName) throws IOException { MetaData metaData = null; try { metaData = getSyncMetaData(beanName); } catch (IOException ex) { LogUtils.error(LOG, ex, "Could not get bean resources %s cause %s", beanName, ex.getMessage()); } // Removes MetaData from cache removeMeta(beanName); if (ObjectUtils.notNull(metaData)) { // Removes appropriated resource class from REST service if (RestContainer.hasRest()) { RestProvider.remove(metaData.getBeanClass()); } clearConnection(metaData); ClassLoader loader = metaData.getLoader(); LibraryLoader.closeClassLoader(loader); metaData = null; } } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link URL} of * archive file * * @param url * @throws IOException */ public static boolean undeploy(URL url) throws IOException { synchronized (MetaContainer.class) { Collection<String> beanNames = getBeanNames(url); boolean valid = CollectionUtils.valid(beanNames); if (valid) { for (String beanName : beanNames) { undeployBean(beanName); } } removeBeanNames(url); return valid; } } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link File} * of archive file * * @param file * @throws IOException */ public static boolean undeploy(File file) throws IOException { URL url = file.toURI().toURL(); boolean valid = undeploy(url); return valid; } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link File} * path of archive file * * @param path * @throws IOException */ public static boolean undeploy(String path) throws IOException { File file = new File(path); boolean valid = undeploy(file); return valid; } /** * Removed {@link MetaData} from cache * * @param beanName */ public static void removeMeta(String beanName) { EJBS.remove(beanName); } /** * Gets {@link java.util.Iterator}<MetaData> over all cached * {@link org.lightmare.cache.MetaData} * * @return {@link java.util.Iterator}<MetaData> */ public static Iterator<MetaData> getBeanClasses() { return EJBS.values().iterator(); } /** * Removes all cached resources */ public static void clear() { if (ObjectUtils.notNull(creator)) { synchronized (MetaContainer.class) { if (ObjectUtils.notNull(creator)) { creator.clear(); creator = null; } } } CONFIGS.clear(); EJBS.clear(); EJB_URLS.clear(); } }
package com.darwinsys.springbootdemo; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller() public class NotAServlet { @RequestMapping(value="/notaservlet", method=RequestMethod.GET) public String doWork(@RequestParam("name") String name, ModelMap model) { System.out.println("NotAServlet.doWork()"); model.addAttribute("greetings", String.format("<html><h1>Hello %s!!</h1>", name)); return "hello"; } }
package org.lightmare.cache; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.glassfish.jersey.server.model.Resource; import org.lightmare.rest.RestConfig; import org.lightmare.rest.providers.RestInflector; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Container class to cache REST resource classes * * @author levan * */ public class RestContainer { // Cached REST resource classes private static final ConcurrentMap<Class<?>, Resource> REST_RESOURCES = new ConcurrentHashMap<Class<?>, Resource>(); // Cached running instance of RestConfig class private static RestConfig restConfig; public static void putResource(Class<?> handlerClass, Resource resource) { REST_RESOURCES.putIfAbsent(handlerClass, resource); } /** * Finds if {@link Resource} has handler instances and if they are instance * of {@link RestInflector} and gets appropriate bean class * * @param resource * @return {@link Class} */ private static Class<?> getFromHandlerInstance(Resource resource) { Class<?> handlerClass = null; Set<Object> handlers = resource.getHandlerInstances(); if (CollectionUtils.available(handlers)) { Iterator<Object> iterator = handlers.iterator(); Object handler; RestInflector inflector; while (iterator.hasNext() && handlerClass == null) { handler = iterator.next(); if (handler instanceof RestInflector) { inflector = ObjectUtils.cast(handler, RestInflector.class); handlerClass = inflector.getBeanClass(); } } } return handlerClass; } /** * Gets handler bean class directly from {@link Resource} or from handler * instances * * @param resource * @return {@link Class} */ private static Class<?> getHandlerClass(Resource resource) { Class<?> handlerClass; Set<Class<?>> handlerClasses = resource.getHandlerClasses(); if (CollectionUtils.available(handlerClasses)) { handlerClass = CollectionUtils.getFirst(handlerClasses); } else { handlerClass = getFromHandlerInstance(resource); } return handlerClass; } public static void putResource(Resource resource) { Class<?> handlerClass = getHandlerClass(resource); if (ObjectUtils.notNull(handlerClass)) { putResource(handlerClass, resource); } } public static void putResources(Collection<Resource> resources) { if (CollectionUtils.available(resources)) { for (Resource resource : resources) { putResource(resource); } } } public static Resource getResource(Class<?> resourceClass) { Resource resource = REST_RESOURCES.get(resourceClass); return resource; } public static void removeResource(Class<?> resourceClass) { REST_RESOURCES.remove(resourceClass); } public static void removeResource(Resource resource) { Class<?> handlerClass = getHandlerClass(resource); if (ObjectUtils.notNull(handlerClass)) { REST_RESOURCES.remove(handlerClass); } } public static int size() { return REST_RESOURCES.size(); } public static void removeResources(Set<Resource> existingResources) { if (CollectionUtils.available(existingResources)) { for (Resource existingResource : existingResources) { removeResource(existingResource); } } } /** * Checks if application has REST resources * * @return <code>boolean</code> */ public static boolean hasRest() { synchronized (RestContainer.class) { return ObjectUtils.notNull(restConfig); } } public static void setRestConfig(RestConfig newConfig) { synchronized (RestContainer.class) { restConfig = newConfig; } } public static RestConfig getRestConfig() { return restConfig; } /** * Clears cached rest resources */ public static void clear() { REST_RESOURCES.clear(); } }
package org.sagebionetworks.web.client.widget.entity.controller; import java.util.List; import org.gwtbootstrap3.extras.bootbox.client.callback.PromptCallback; import org.sagebionetworks.web.client.ShowsErrors; import org.sagebionetworks.web.client.utils.Callback; import org.sagebionetworks.web.client.utils.CallbackP; import com.google.gwt.user.client.ui.IsWidget; /** * Abstraction for the view * * @author John * */ public interface EntityActionControllerView extends ShowsErrors, IsWidget { /** * Show the user a confirm dialog. * * @param message * @param callback */ void showConfirmDeleteDialog(String message, Callback callback); /** * Show info to the user. * * @param message */ void showInfo(String message); /** * Show success notification to the user. * * @param message */ void showSuccess(String message); /** * Show info dialog to the user. */ void showInfoDialog(String header, String message); /** * Prompt the user to enter a string value. * * @param title * @param callback */ void showPromptDialog(String title, PromptCallback callback); void setUploadDialogWidget(IsWidget w); void addWidget(IsWidget asWidget); void showMultiplePromptDialog(String title, List<String> prompts, List<String> initialValues, CallbackP<List<String>> newValuesCallback); void setCreateVersionDialogJobTrackingWidget(IsWidget w); void showCreateVersionDialog(); void hideCreateVersionDialog(); }
package com.elmakers.mine.bukkit.api.batch; /** * Represents a batched Block update, usually started by a construction Spell. * * Magic will process pending BlockBatch requests once every tick, up to a * maximum number of Block updates per tick (the default is 1,000). * * Every BlockBatch is required to perform only as many updates as requested, * and to report how many updates were performed. * * A BlockBatch must also report when it is finished, and perform any required * actions on finish, such as registering an UndoBatch for undo. */ public interface Batch { /** * Process one iteration of this batch. * * Return the number of blocks processed. * * @param maxBlocks The maximum number of blocks the batch should process * @return The number of blocks processed. */ public int process(int maxBlocks); /** * Whether or not this batch is finished * * @return true if finished */ public boolean isFinished(); /** * Immediatelly finish this batch. * * This may cancel any remaining operations, but should * clean up, add to undo queues, etc, whatever has been * done so far. */ public void finish(); /** * The size of this batch. May be in blocks, or some * other abstract unit. * * Can be used in conjunction with remaining() for a progress indicator. * * @return The size of this batch. */ public int size(); /** * The remaining size of this batch. May be in blocks, or some * other abstract unit. * * Can be used in conjunction with size() for a progress indicator. * * @return The remaining size of this batch. */ public int remaining(); /** * Return a friendly name to identify this batch. * @return */ public String getName(); }
package org.spongepowered.common.event.tracking.phase.packet.player; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.projectile.EntityThrowable; import net.minecraft.network.Packet; import net.minecraft.network.play.client.CPacketPlayerDigging; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.data.type.HandType; import org.spongepowered.api.data.type.HandTypes; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.projectile.Projectile; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.cause.EventContextKeys; import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.world.Location; import org.spongepowered.asm.util.PrettyPrinter; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.entity.EntityUtil; import org.spongepowered.common.event.ShouldFire; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.IPhaseState; import org.spongepowered.common.event.tracking.TrackingUtil; import org.spongepowered.common.event.tracking.context.ItemDropData; import org.spongepowered.common.event.tracking.phase.block.BlockPhase; import org.spongepowered.common.event.tracking.phase.packet.BasicPacketContext; import org.spongepowered.common.event.tracking.phase.packet.BasicPacketState; import org.spongepowered.common.interfaces.IMixinContainer; import org.spongepowered.common.item.inventory.util.ContainerUtil; import org.spongepowered.common.item.inventory.util.ItemStackUtil; import org.spongepowered.common.util.VecHelper; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import javax.annotation.Nullable; public final class InteractionPacketState extends BasicPacketState { @Override public boolean isInteraction() { return true; } @Override public void populateContext(EntityPlayerMP playerMP, Packet<?> packet, BasicPacketContext context) { final ItemStack stack = ItemStackUtil.cloneDefensive(playerMP.getHeldItemMainhand()); if (stack != null) { context.itemUsed(stack); } context.targetBlock(new Location<>(((Player) playerMP).getWorld(), VecHelper.toVector3d(((CPacketPlayerDigging) packet).getPosition())).createSnapshot()); context.handUsed(HandTypes.MAIN_HAND); } @Override public boolean spawnEntityOrCapture(BasicPacketContext context, Entity entity, int chunkX, int chunkZ) { return context.captureEntity(entity); } @Override public boolean shouldCaptureEntity() { return true; } @Override public boolean doesCaptureEntityDrops(BasicPacketContext context) { return true; } @Override public boolean tracksTileEntityChanges(BasicPacketContext currentContext) { return true; } @Override public boolean hasSpecificBlockProcess(BasicPacketContext context) { return true; } @Override public boolean doesCaptureNeighborNotifications(BasicPacketContext context) { return true; } @Override public boolean canSwitchTo(IPhaseState<?> state) { return state == BlockPhase.State.BLOCK_DECAY || state == BlockPhase.State.BLOCK_DROP_ITEMS; } @Override public boolean tracksBlockSpecificDrops(BasicPacketContext context) { return true; } @Override public boolean alreadyProcessingBlockItemDrops() { return true; } @SuppressWarnings("unchecked") @Override public void unwind(BasicPacketContext phaseContext) { final EntityPlayerMP player = phaseContext.getPacketPlayer(); final ItemStack usedStack = phaseContext.getItemUsed(); final HandType usedHand = phaseContext.getHandUsed(); final ItemStackSnapshot usedSnapshot = ItemStackUtil.snapshotOf(usedStack); final Entity spongePlayer = EntityUtil.fromNative(player); final BlockSnapshot targetBlock = phaseContext.getTargetBlock(); try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(spongePlayer); frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.DROPPED_ITEM); frame.addContext(EventContextKeys.USED_ITEM, usedSnapshot); frame.addContext(EventContextKeys.USED_HAND, usedHand); frame.addContext(EventContextKeys.BLOCK_HIT, targetBlock); final boolean hasBlocks = !phaseContext.getCapturedBlockSupplier().isEmpty(); final List<SpongeBlockSnapshot> capturedBlcoks = phaseContext.getCapturedOriginalBlocksChanged(); final @Nullable BlockSnapshot firstBlockChange = hasBlocks ? capturedBlcoks.get(0) : null; if (hasBlocks) { if (!TrackingUtil.processBlockCaptures(this, phaseContext)) { // Stop entities like XP from being spawned phaseContext.getBlockItemDropSupplier().get().clear(); phaseContext.getCapturedItems().clear(); phaseContext.getPerEntityItemDropSupplier().get().clear(); phaseContext.getCapturedEntities().clear(); return; } } else { phaseContext.getBlockItemDropSupplier().acceptAndClearIfNotEmpty(map -> { if (ShouldFire.DROP_ITEM_EVENT_DESTRUCT) { for (Map.Entry<BlockPos, Collection<EntityItem>> entry : map.asMap().entrySet()) { if (!entry.getValue().isEmpty()) { final List<Entity> items = entry.getValue().stream().map(EntityUtil::fromNative).collect(Collectors.toList()); final DropItemEvent.Destruct event = SpongeEventFactory.createDropItemEventDestruct(Sponge.getCauseStackManager().getCurrentCause(), items); SpongeImpl.postEvent(event); if (!event.isCancelled()) { processSpawnedEntities(player, event); } } } } else { for (Map.Entry<BlockPos, Collection<EntityItem>> entry : map.asMap().entrySet()) { if (!entry.getValue().isEmpty()) { processEntities(player, (Collection<Entity>) (Collection<?>) entry.getValue()); } } } }); } phaseContext.getCapturedItemsSupplier() .acceptAndClearIfNotEmpty(items -> { final ArrayList<Entity> entities = new ArrayList<>(); for (EntityItem item : items) { entities.add(EntityUtil.fromNative(item)); } final DropItemEvent.Dispense dispense = SpongeEventFactory.createDropItemEventDispense(Sponge.getCauseStackManager().getCurrentCause(), entities); SpongeImpl.postEvent(dispense); if (!dispense.isCancelled()) { processSpawnedEntities(player, dispense); } }); phaseContext.getPerEntityItemDropSupplier() .acceptAndClearIfNotEmpty(map -> { if (map.isEmpty()) { return; } final PrettyPrinter printer = new PrettyPrinter(80); printer.add("Processing Interaction").centre().hr(); printer.add("The item stacks captured are: "); for (Map.Entry<UUID, Collection<ItemDropData>> entry : map.asMap().entrySet()) { printer.add(" - Entity with UUID: %s", entry.getKey()); for (ItemDropData stack : entry.getValue()) { printer.add(" - %s", stack); } } printer.trace(System.err); }); phaseContext.getCapturedEntitySupplier().acceptAndClearIfNotEmpty(entities -> { throwEntitySpawnEvents(phaseContext, player, usedSnapshot, firstBlockChange, entities); }); phaseContext.getPerEntityItemEntityDropSupplier().acceptAndClearIfNotEmpty((multimap -> { for (Map.Entry<UUID, Collection<EntityItem>> entry : multimap.asMap().entrySet()) { if (entry.getKey().equals(player.getUniqueID())) { throwEntitySpawnEvents(phaseContext, player, usedSnapshot, firstBlockChange, (Collection<Entity>) (Collection<?>) entry.getValue()); } else { final net.minecraft.entity.Entity spawnedEntity = ((WorldServer) player.world).getEntityFromUuid(entry.getKey()); if (spawnedEntity != null) { try (CauseStackManager.StackFrame entityFrame = Sponge.getCauseStackManager().pushCauseFrame()) { entityFrame.pushCause(spawnedEntity); throwEntitySpawnEvents(phaseContext, player, usedSnapshot, firstBlockChange, (Collection<Entity>) (Collection<?>) entry.getValue()); } } } } })); final IMixinContainer mixinContainer = ContainerUtil.toMixin(player.openContainer); mixinContainer.setCaptureInventory(false); mixinContainer.getCapturedTransactions().clear(); } } private void throwEntitySpawnEvents(BasicPacketContext phaseContext, EntityPlayerMP player, ItemStackSnapshot usedSnapshot, BlockSnapshot firstBlockChange, Collection<Entity> entities) { final List<Entity> projectiles = new ArrayList<>(entities.size()); final List<Entity> spawnEggs = new ArrayList<>(entities.size()); final List<Entity> xpOrbs = new ArrayList<>(entities.size()); final List<Entity> normalPlacement = new ArrayList<>(entities.size()); final List<Entity> items = new ArrayList<>(entities.size()); for (Entity entity : entities) { if (entity instanceof Projectile || entity instanceof EntityThrowable) { projectiles.add(entity); } else if (usedSnapshot.getType() == ItemTypes.SPAWN_EGG) { spawnEggs.add(entity); } else if (entity instanceof EntityItem) { items.add(entity); } else if (entity instanceof EntityXPOrb) { xpOrbs.add(entity); } else { normalPlacement.add(entity); } } if (!projectiles.isEmpty()) { if (ShouldFire.SPAWN_ENTITY_EVENT) { try (CauseStackManager.StackFrame frame2 = Sponge.getCauseStackManager().pushCauseFrame()) { frame2.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.PROJECTILE); frame2.pushCause(usedSnapshot); SpongeCommonEventFactory.callSpawnEntity(projectiles, phaseContext); } } else { processEntities(player, projectiles); } } if (!spawnEggs.isEmpty()) { if (ShouldFire.SPAWN_ENTITY_EVENT) { try (CauseStackManager.StackFrame frame2 = Sponge.getCauseStackManager().pushCauseFrame()) { frame2.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.SPAWN_EGG); frame2.pushCause(usedSnapshot); SpongeCommonEventFactory.callSpawnEntity(spawnEggs, phaseContext); } } else { processEntities(player, spawnEggs); } } if (!items.isEmpty()) { if (ShouldFire.DROP_ITEM_EVENT_DISPENSE) { final DropItemEvent.Dispense dispense = SpongeEventFactory .createDropItemEventDispense(Sponge.getCauseStackManager().getCurrentCause(), items); if (!SpongeImpl.postEvent(dispense)) { processSpawnedEntities(player, dispense); } } else { processEntities(player, items); } } if (!xpOrbs.isEmpty()) { if (ShouldFire.SPAWN_ENTITY_EVENT) { try (final CauseStackManager.StackFrame stackFrame = Sponge.getCauseStackManager().pushCauseFrame()) { if (firstBlockChange != null) { stackFrame.pushCause(firstBlockChange); } stackFrame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.EXPERIENCE); SpongeCommonEventFactory.callSpawnEntity(xpOrbs, phaseContext); } } else { processEntities(player, xpOrbs); } } if (!normalPlacement.isEmpty()) { if (ShouldFire.SPAWN_ENTITY_EVENT) { try (final CauseStackManager.StackFrame stackFrame = Sponge.getCauseStackManager().pushCauseFrame()) { if (firstBlockChange != null) { stackFrame.pushCause(firstBlockChange); } SpongeCommonEventFactory.callSpawnEntity(normalPlacement, phaseContext); } } else { processEntities(player, normalPlacement); } } } @Override public boolean tracksEntitySpecificDrops() { return true; } }
package com.facebook.litho; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.AttrRes; import android.support.annotation.ColorInt; import android.support.annotation.DimenRes; import android.support.annotation.Dimension; import android.support.annotation.DrawableRes; import android.support.annotation.Px; import android.support.annotation.StringRes; import android.util.SparseArray; import com.facebook.yoga.YogaAlign; import com.facebook.yoga.YogaBaselineFunction; import com.facebook.yoga.YogaFlexDirection; import com.facebook.yoga.YogaJustify; import com.facebook.yoga.YogaDirection; import com.facebook.yoga.YogaPositionType; import com.facebook.yoga.YogaWrap; import com.facebook.yoga.YogaEdge; import com.facebook.litho.reference.Reference; import com.facebook.yoga.YogaNodeAPI; import static android.support.annotation.Dimension.DP; /** * Class representing an empty InternalNode with a null ComponentLayout. All methods * have been overridden so no actions are performed, and no exceptions are thrown. */ class NoOpInternalNode extends InternalNode { @Override void init(YogaNodeAPI cssNode, ComponentContext componentContext, Resources resources) {} @Override void setComponent(Component component) { } @Px @Override public int getX() { return 0; } @Px @Override public int getY() { return 0; } @Px @Override public int getWidth() { return 0; } @Px @Override public int getHeight() { return 0; } @Px @Override public int getPaddingLeft() { return 0; } @Px @Override public int getPaddingTop() { return 0; } @Px @Override public int getPaddingRight() { return 0; } @Px @Override public int getPaddingBottom() { return 0; } @Override public void setCachedMeasuresValid(boolean valid) {} @Override public int getLastWidthSpec() { return 0; } @Override public void setLastWidthSpec(int widthSpec) {} @Override public int getLastHeightSpec() { return 0; } @Override public void setLastHeightSpec(int heightSpec) {} @Override void setLastMeasuredWidth(float lastMeasuredWidth) {} @Override void setLastMeasuredHeight(float lastMeasuredHeight) {} @Override void setDiffNode(DiffNode diffNode) {} @Override public InternalNode layoutDirection(YogaDirection direction) { return this; } @Override public InternalNode flexDirection(YogaFlexDirection direction) { return this; } @Override public InternalNode wrap(YogaWrap wrap) { return this; } @Override public InternalNode justifyContent(YogaJustify justifyContent) { return this; } @Override public InternalNode alignItems(YogaAlign alignItems) { return this; } @Override public InternalNode alignContent(YogaAlign alignContent) { return this; } @Override public InternalNode alignSelf(YogaAlign alignSelf) { return this; } @Override public InternalNode positionType(YogaPositionType positionType) { return this; } @Override public InternalNode flex(float flex) { return this; } @Override public InternalNode flexGrow(float flexGrow) { return this; } @Override public InternalNode flexShrink(float flexShrink) { return this; } @Override public InternalNode flexBasisPx(@Px int flexBasis) { return this; } @Override public InternalNode flexBasisAttr(@AttrRes int resId, @DimenRes int defaultResId) { return this; } @Override public InternalNode flexBasisAttr(@AttrRes int resId) { return this; } @Override public InternalNode flexBasisRes(@DimenRes int resId) { return this; } @Override public InternalNode flexBasisDip(@Dimension(unit = DP) int flexBasis) { return this; } @Override public InternalNode flexBasisPercent(float percent) { return this; } @Override public InternalNode importantForAccessibility(int importantForAccessibility) { return this; } @Override public InternalNode duplicateParentState(boolean duplicateParentState) { return this; } @Override
package org.openforis.ceo.local; import static org.openforis.ceo.utils.JsonUtils.elementToArray; import static org.openforis.ceo.utils.JsonUtils.expandResourcePath; import static org.openforis.ceo.utils.JsonUtils.findInJsonArray; import static org.openforis.ceo.utils.JsonUtils.getNextId; import static org.openforis.ceo.utils.JsonUtils.intoJsonArray; import static org.openforis.ceo.utils.JsonUtils.mapJsonFile; import static org.openforis.ceo.utils.JsonUtils.parseJson; import static org.openforis.ceo.utils.JsonUtils.readJsonFile; import static org.openforis.ceo.utils.JsonUtils.toStream; import static org.openforis.ceo.utils.JsonUtils.writeJsonFile; import static org.openforis.ceo.utils.Mail.isEmail; import static org.openforis.ceo.utils.Mail.sendMail; import static org.openforis.ceo.utils.ProjectUtils.getOrZero; import static org.openforis.ceo.utils.ProjectUtils.getOrEmptyString; import static org.openforis.ceo.utils.ProjectUtils.collectTimeIgnoreString; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import java.nio.file.Paths; import java.time.format.DateTimeFormatter; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import org.openforis.ceo.db_api.Users; import org.openforis.ceo.env.CeoConfig; import org.openforis.ceo.utils.Mail; import spark.Request; import spark.Response; public class JsonUsers implements Users { private static final String BASE_URL = CeoConfig.baseUrl; private static final String SMTP_USER = CeoConfig.smtpUser; private static final String SMTP_SERVER = CeoConfig.smtpServer; private static final String SMTP_PORT = CeoConfig.smtpPort; private static final String SMTP_PASSWORD = CeoConfig.smtpPassword; private static final String SMTP_RECIPIENT_LIMIT = CeoConfig.smtpRecipientLimit; public Request login(Request req, Response res) { var inputEmail = req.queryParams("email"); var inputPassword = req.queryParams("password"); var inputReturnURL = req.queryParams("returnurl"); var returnURL = (inputReturnURL == null || inputReturnURL.isEmpty()) ? CeoConfig.documentRoot + "/home" : inputReturnURL; // Check if email exists var users = elementToArray(readJsonFile("user-list.json")); var matchingUser = findInJsonArray(users, user -> user.get("email").getAsString().equals(inputEmail)); if (!matchingUser.isPresent()) { req.session().attribute("flash_message", "No account with email " + inputEmail + " exists."); return req; } else { // Check if password matches var user = matchingUser.get(); var storedId = user.get("id").getAsString(); var storedPassword = user.get("password").getAsString(); var storedRole = user.get("role").getAsString(); if (!inputPassword.equals(storedPassword)) { // Authentication failed req.session().attribute("flash_message", "Invalid email/password combination."); return req; } else { // Authentication successful req.session().attribute("userid", storedId); req.session().attribute("username", inputEmail); req.session().attribute("role", storedRole); res.redirect(returnURL); return req; } } } public synchronized Request register(Request req, Response res) { var inputEmail = req.queryParams("email"); var inputPassword = req.queryParams("password"); var inputPasswordConfirmation = req.queryParams("password-confirmation"); // Validate input params and assign flash_message if invalid if (!isEmail(inputEmail)) { req.session().attribute("flash_message", inputEmail + " is not a valid email address."); return req; } else if (inputPassword.length() < 8) { req.session().attribute("flash_message", "Password must be at least 8 characters."); return req; } else if (!inputPassword.equals(inputPasswordConfirmation)) { req.session().attribute("flash_message", "Password and Password confirmation do not match."); return req; } else { var users = elementToArray(readJsonFile("user-list.json")); var matchingUser = findInJsonArray(users, user -> user.get("email").getAsString().equals(inputEmail)); if (matchingUser.isPresent()) { req.session().attribute("flash_message", "Account " + inputEmail + " already exists."); return req; } else { // Add a new user to user-list.json var newUserId = getNextId(users); var newUserRole = "user"; var newUser = new JsonObject(); newUser.addProperty("id", newUserId); newUser.addProperty("email", inputEmail); newUser.addProperty("password", inputPassword); newUser.addProperty("role", newUserRole); newUser.add("resetKey", null); users.add(newUser); writeJsonFile("user-list.json", users); // Assign the username and role session attributes req.session().attribute("userid", newUserId + ""); req.session().attribute("username", inputEmail); req.session().attribute("role", newUserRole); // Send confirmation email to the user var timestamp = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now()); var body = "Dear " + inputEmail + ",\n\n" + "Thank you for signing up for CEO!\n\n" + "Your Account Summary Details:\n\n" + " Email: " + inputEmail + "\n" + " Created on: " + timestamp + "\n\n" + "Kind Regards,\n" + " The CEO Team"; sendMail(SMTP_USER, Arrays.asList(inputEmail), null, null, SMTP_SERVER, SMTP_PORT, SMTP_PASSWORD, "Welcome to CEO!", body, null); // Redirect to the Home page res.redirect(CeoConfig.documentRoot + "/home"); return req; } } } public Request logout(Request req, Response res) { req.session().removeAttribute("userid"); req.session().removeAttribute("username"); req.session().removeAttribute("role"); res.redirect(CeoConfig.documentRoot + "/home"); return req; } // FIXME back port postgres checks that allow user to change only one part public Request updateAccount(Request req, Response res) { var userId = (String) req.session().attribute("userid"); var inputEmail = req.queryParams("email"); var inputPassword = req.queryParams("password"); var inputPasswordConfirmation = req.queryParams("password-confirmation"); var mailingListSubscription = req.queryParams("mailing-list-subscription"); var inputCurrentPassword = req.queryParams("current-password"); // Validate input params and assign flash_message if invalid if (inputCurrentPassword.length() == 0) { req.session().attribute("flash_message", "Current Password required"); // let user change email without changing password } else if (inputEmail.length() > 0 && !isEmail(inputEmail)) { req.session().attribute("flash_message", inputEmail + " is not a valid email address."); // let user change email without changing password } else if (inputPassword.length() > 0 && inputPassword.length() < 8) { req.session().attribute("flash_message", "New Password must be at least 8 characters."); } else if (!inputPassword.equals(inputPasswordConfirmation)) { req.session().attribute("flash_message", "New Password and Password confirmation do not match."); } else { var users = elementToArray(readJsonFile("user-list.json")); var matchingUser = findInJsonArray(users, user -> user.get("id").getAsString().equals(userId)); if (!matchingUser.isPresent()) { req.session().attribute("flash_message", "The requested user account does not exist."); } else { var foundUser = matchingUser.get(); if (!foundUser.get("password").getAsString().equals(inputCurrentPassword)) { req.session().attribute("flash_message", "Invalid password."); } else { mapJsonFile("user-list.json", user -> { if (user.get("id").getAsString().equals(userId)) { user.addProperty("email", inputEmail.isEmpty() ? foundUser.get("email").getAsString() : inputEmail); user.addProperty("password", inputPassword.isEmpty() ? foundUser.get("password").getAsString() : inputPassword); user.addProperty("mailing-list", mailingListSubscription != null); return user; } else { return user; } }); req.session().attribute("username", inputEmail); req.session().attribute("flash_message", "The user has been updated."); } } } return req; } public Request getPasswordResetKey(Request req, Response res) { var inputEmail = req.queryParams("email"); var users = elementToArray(readJsonFile("user-list.json")); var matchingUser = findInJsonArray(users, user -> user.get("email").getAsString().equals(inputEmail)); if (!matchingUser.isPresent()) { req.session().attribute("flash_message", "There is no user with that email address."); return req; } else { try { var resetKey = UUID.randomUUID().toString(); mapJsonFile("user-list.json", user -> { if (user.get("email").getAsString().equals(inputEmail)) { user.addProperty("resetKey", resetKey); return user; } else { return user; } }); var body = "Hi " + inputEmail + ",\n\n" + " To reset your password, simply click the following link:\n\n" + " " + BASE_URL + "password-reset?email=" + inputEmail + "&password-reset-key=" + resetKey; sendMail(SMTP_USER, Arrays.asList(inputEmail), null, null, SMTP_SERVER, SMTP_PORT, SMTP_PASSWORD, "Password reset on CEO", body, null); req.session().attribute("flash_message", "The reset key has been sent to your email."); return req; } catch (Exception e) { req.session().attribute("flash_message", "An error occurred. Please try again later."); return req; } } } public Request resetPassword(Request req, Response res) { var inputEmail = req.queryParams("email"); var inputResetKey = req.queryParams("password-reset-key"); var inputPassword = req.queryParams("password"); var inputPasswordConfirmation = req.queryParams("password-confirmation"); // Validate input params and assign flash_message if invalid if (inputPassword.length() < 8) { req.session().attribute("flash_message", "Password must be at least 8 characters."); return req; } else if (!inputPassword.equals(inputPasswordConfirmation)) { req.session().attribute("flash_message", "Password and Password confirmation do not match."); return req; } else { var users = elementToArray(readJsonFile("user-list.json")); var matchingUser = findInJsonArray(users, user -> user.get("email").getAsString().equals(inputEmail)); if (!matchingUser.isPresent()) { req.session().attribute("flash_message", "There is no user with that email address."); return req; } else { var foundUser = matchingUser.get(); if (!foundUser.get("resetKey").getAsString().equals(inputResetKey)) { req.session().attribute("flash_message", "Invalid reset key for user " + inputEmail + "."); return req; } else { mapJsonFile("user-list.json", user -> { if (user.get("email").getAsString().equals(inputEmail)) { user.addProperty("password", inputPassword); user.add("resetKey", null); return user; } else { return user; } }); req.session().attribute("flash_message", "Your password has been changed."); return req; } } } } public String getAllUsers(Request req, Response res) { var users = elementToArray(readJsonFile("user-list.json")); return toStream(users) .filter(user -> !user.get("email").getAsString().equals("admin@openforis.org")) .map(user -> { user.remove("password"); user.remove("resetKey"); return user; }) .collect(intoJsonArray) .toString(); } public String getInstitutionUsers(Request req, Response res) { var institutionId = req.queryParams("institutionId"); var users = elementToArray(readJsonFile("user-list.json")); var institutions = elementToArray(readJsonFile("institution-list.json")); var matchingInstitution = findInJsonArray(institutions, institution -> institution.get("id").getAsString().equals(institutionId)); if (matchingInstitution.isPresent()) { var institution = matchingInstitution.get(); var members = institution.getAsJsonArray("members"); var admins = institution.getAsJsonArray("admins"); var pending = institution.getAsJsonArray("pending"); return toStream(users) .filter(user -> !user.get("email").getAsString().equals("admin@openforis.org")) .filter(user -> members.contains(user.get("id")) || pending.contains(user.get("id"))) .map(user -> { user.remove("password"); user.remove("resetKey"); return user; }) .map(user -> { user.addProperty("institutionRole", admins.contains(user.get("id")) ? "admin" : members.contains(user.get("id")) ? "member" : pending.contains(user.get("id")) ? "pending" : "not-member"); return user; }) .collect(intoJsonArray) .toString(); } else { return (new JsonArray()).toString(); } } public String getUserDetails(Request req, Response res) { final var userId = req.queryParams("userId"); var users = elementToArray(readJsonFile("user-list.json")); var matchingUser = findInJsonArray(users, user -> user.get("id").getAsString().equals(userId)); if (!matchingUser.isPresent()) { return ""; } else { var foundUser = matchingUser.get(); var userDetailsObject = new JsonObject(); userDetailsObject.addProperty("mailingListSubscription", foundUser.get("mailing-list").getAsBoolean()); return userDetailsObject.toString(); } } public String getUserStats(Request req, Response res) { final var userName = req.queryParams("userId"); final var projects = elementToArray(readJsonFile("project-list.json")); // Pull out usefull data final var projectData = toStream(projects) .filter(project -> Paths.get(expandResourcePath("/json"), "plot-data-" + project.get("id").getAsString() + ".json").toFile().exists() && project.has("userStats") && toStream(project.get("userStats").getAsJsonArray()) .filter(user -> user.get("user").getAsString().equals(userName)) .collect(intoJsonArray) .size() > 0 ) .map(project -> { var projectObject = new JsonObject(); projectObject.addProperty("id", project.get("id").getAsInt()); projectObject.addProperty("name", project.get("name").getAsString()); projectObject.addProperty("description", project.get("name").getAsString()); projectObject.addProperty("availability", project.get("availability").getAsString()); projectObject.addProperty("numPlots", project.get("numPlots").getAsString()); var userData = toStream(project.get("userStats").getAsJsonArray()) .filter(user -> user.get("user").getAsString().equals(userName)) .findFirst().get(); projectObject.addProperty("plotCount", userData.get("plots").getAsInt()); final var getMiliSec = userData.get("milliSecs").getAsInt(); final var curMiliSec = getMiliSec > 0 && getMiliSec < 10000000 ? getMiliSec : 0; final var timedPlots = userData.get("timedPlots").getAsInt(); projectObject.addProperty("analysisAverage", timedPlots > 0 ? Math.round(curMiliSec / 1.0 / timedPlots / 100.0) / 10.0 : 0); projectObject.addProperty("totalMilliSecond", timedPlots > 0 ? curMiliSec : 0); projectObject.addProperty("timedUserPlots", timedPlots); return projectObject; } ) .sorted((p1, p2)-> p2.get("id").getAsInt() - p1.get("id").getAsInt()) .collect(intoJsonArray); final int totalPlots = toStream(projectData) .map(project -> getOrZero(project, "plotCount").getAsInt()) .mapToInt(Integer::intValue).sum(); final int totalTimedPlots = toStream(projectData) .map(project -> getOrZero(project, "timedUserPlots").getAsInt()) .mapToInt(Integer::intValue).sum(); final int totalMilliseconds = toStream(projectData) .map(project -> getOrZero(project, "totalMilliSecond").getAsInt()) .mapToInt(Integer::intValue).sum(); var userStats = new JsonObject(); userStats.addProperty("totalProjects", projectData.size()); userStats.addProperty("totalPlots", totalPlots); userStats.addProperty("averageTime", Math.round(totalMilliseconds / 100.0 / totalTimedPlots) / 10.0); userStats.add("perProject", projectData); return userStats.toString(); } public static JsonArray sumUserInfo(JsonArray sumArr, JsonObject newData) { if (toStream(sumArr) .filter(user -> user.get("user").getAsString().equals(newData.get("user").getAsString())) .collect(intoJsonArray) .size() > 0) { return toStream(sumArr) .map(user -> { if (user.get("user").getAsString().equals(newData.get("user").getAsString())) { user.addProperty("milliSecs", user.get("milliSecs").getAsInt() + newData.get("milliSecs").getAsInt()); user.addProperty("plots", user.get("plots").getAsInt() + newData.get("plots").getAsInt()); user.addProperty("timedPlots", user.get("timedPlots").getAsInt() + newData.get("timedPlots").getAsInt()); return user; } else { return user; } }).collect(intoJsonArray); } else { sumArr.add(newData); return sumArr; } } public String updateProjectUserStats(Request req, Response res) { mapJsonFile("project-list.json", project -> { if (Paths.get(expandResourcePath("/json"), "plot-data-" + project.get("id").getAsString() + ".json").toFile().exists()) { var plots = elementToArray(readJsonFile("plot-data-" + project.get("id").getAsString() + ".json")); var dataByUsers = toStream(plots) .filter(plot -> getOrEmptyString(plot, "user").getAsString().length() > 0) .map(plot -> { var plotObject = new JsonObject(); plotObject.addProperty("milliSecs", collectTimeIgnoreString(plot) > getOrZero(plot, "collectionStart").getAsLong() ? collectTimeIgnoreString(plot) - getOrZero(plot, "collectionStart").getAsLong() : 0); plotObject.addProperty("plots", 1); plotObject.addProperty("timedPlots", getOrZero(plot, "collectionStart").getAsLong() > 0 ? 1 : 0); plotObject.addProperty("user", plot.get("user").getAsString()); return plotObject; } ) .collect(JsonArray::new, (responce, element) -> sumUserInfo(responce, element), (a, b) -> System.out.println(a) ); project.add("userStats", dataByUsers); project.remove("userMilliSeconds"); project.remove("userPlots"); project.remove("timedUserPlots"); return project; } else { return project; } } ); return ""; } public Map<Integer, String> getInstitutionRoles(int userId) { var institutions = elementToArray(readJsonFile("institution-list.json")); var userIdJson = new JsonPrimitive(userId); return toStream(institutions) .collect(Collectors.toMap(institution -> institution.get("id").getAsInt(), institution -> { var members = institution.getAsJsonArray("members"); var admins = institution.getAsJsonArray("admins"); if (admins.contains(userIdJson)) { return "admin"; } else if (members.contains(userIdJson)) { return "member"; } else { return "not-member"; } }, (a, b) -> b)); } public String updateInstitutionRole(Request req, Response res) { var jsonInputs = parseJson(req.body()).getAsJsonObject(); var userId = jsonInputs.get("userId"); var institutionId = jsonInputs.get("institutionId").getAsInt(); var role = jsonInputs.get("role").getAsString(); mapJsonFile("institution-list.json", institution -> { if (institution.get("id").getAsInt() == institutionId) { var members = institution.getAsJsonArray("members"); var admins = institution.getAsJsonArray("admins"); var pending = institution.getAsJsonArray("pending"); if (role.equals("member")) { if (!members.contains(userId)) { members.add(userId); } if (admins.contains(userId)) { admins.remove(userId); } if (pending.contains(userId)) { pending.remove(userId); } } else if (role.equals("admin")) { if (!members.contains(userId)) { members.add(userId); } if (!admins.contains(userId)) { admins.add(userId); } if (pending.contains(userId)) { pending.remove(userId); } } else { members.remove(userId); admins.remove(userId); pending.remove(userId); } institution.add("members", members); institution.add("admins", admins); institution.add("pending", pending); return institution; } else { return institution; } }); return ""; } public String requestInstitutionMembership(Request req, Response res) { var jsonInputs = parseJson(req.body()).getAsJsonObject(); var userId = jsonInputs.get("userId"); var institutionId = jsonInputs.get("institutionId").getAsInt(); mapJsonFile("institution-list.json", institution -> { if (institution.get("id").getAsInt() == institutionId) { var members = institution.getAsJsonArray("members"); var pending = institution.getAsJsonArray("pending"); if (!members.contains(userId) && !pending.contains(userId)) { pending.add(userId); } institution.add("pending", pending); return institution; } else { return institution; } }); return ""; } public Request sendMailingList(Request req, Response res) { var inputSubject = req.queryParams("subject"); var inputBody = req.queryParams("body"); if (inputSubject == null || inputSubject.isEmpty() || inputBody == null || inputBody.isEmpty()) { req.session().attribute("flash_message", "Subject and Body are mandatory fields."); } else { try { var users = elementToArray(readJsonFile("user-list.json")); var emails = toStream(users) .filter(user -> user.get("mailing-list").getAsBoolean()) .map(user -> user.get("email").getAsString()) .collect(Collectors.toList()); Mail.sendMailingList(SMTP_USER, emails, SMTP_SERVER, SMTP_PORT, SMTP_PASSWORD, inputSubject, inputBody, Mail.CONTENT_TYPE_HTML, Integer.parseInt(SMTP_RECIPIENT_LIMIT)); req.session().attribute("flash_message", "Your message has been sent to the mailing list."); } catch (Exception e) { System.out.println(e.getMessage()); req.session().attribute("flash_message", "There was an issue sending to the mailing list. Please check the server logs."); } } return req; } }
package com.fundynamic.d2tm.game.entities; import com.fundynamic.d2tm.game.behaviors.*; import com.fundynamic.d2tm.game.entities.entitybuilders.EntityBuilderType; import com.fundynamic.d2tm.game.entities.superpowers.SuperPower; import com.fundynamic.d2tm.game.entities.units.RenderQueueEnrichableWithFacingLogic; import com.fundynamic.d2tm.game.map.Cell; import com.fundynamic.d2tm.game.map.Map; import com.fundynamic.d2tm.game.rendering.gui.battlefield.RenderQueue; import com.fundynamic.d2tm.game.types.EntityData; import com.fundynamic.d2tm.math.Coordinate; import com.fundynamic.d2tm.math.MapCoordinate; import com.fundynamic.d2tm.math.Rectangle; import com.fundynamic.d2tm.math.Vector2D; import org.newdawn.slick.GameContainer; import org.newdawn.slick.SpriteSheet; import org.newdawn.slick.state.StateBasedGame; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; /** * <p> * An entity is a 'thing' that 'lives' on the {@link com.fundynamic.d2tm.game.rendering.gui.battlefield.BattleField}. * </p> * <h2>State</h2> * <p> * An entity has state, usually a lifespan or somesort, therefor it is {@link Updateable}. The {@link #update(float)} method * is called by the {@link com.fundynamic.d2tm.game.state.PlayingState#update(GameContainer, StateBasedGame, int)} method. * </p> * <h2>Rendering:</h2> * <p> * An entity is told where on screen it should be rendered by a {@link RenderQueue}. * * This is because the translation * from Map to screen position is done by a {@link com.fundynamic.d2tm.game.rendering.gui.battlefield.BattleField} or * Viewport (To be built). * </p> */ public abstract class Entity implements EnrichableAbsoluteRenderable, Updateable { // Final properties of unit protected final EntityData entityData; protected final SpriteSheet spritesheet; protected final Player player; protected final EntityRepository entityRepository; protected Entity origin; // which entity created this entity? (if applicable) /** * top left *cell* coordinate, not the top-left of unit image! * ie, even a Harvester (with 48x48 image size) is positioned on 32,32, a trike is as well. * both units are rendered differently, but that is taken care of the {@link RenderQueueEnrichableWithFacingLogic} **/ protected Coordinate coordinate; public Entity(Coordinate coordinate, SpriteSheet spritesheet, EntityData entityData, Player player, EntityRepository entityRepository) { this.coordinate = coordinate; this.spritesheet = spritesheet; this.entityData = entityData; this.player = player; this.entityRepository = entityRepository; if (player != null) { // temporarily, because 'particle' does not belong to a player player.addEntity(this); } } /** * Returns the upper-left coordinate of this entity * * @return */ public Coordinate getCoordinate() { return coordinate; } /** * Returns center of this entity as coordinate. Which basically means adding half its size to the top-left coordinate. * * @return */ public Coordinate getCenteredCoordinateOfEntity() { return coordinate.add(getHalfSizeOfEntity()); } /** * Returns distance from this entity to other, using centered coordinates for both entities. * * @param other * @return */ public float distance(Entity other) { return getCenteredCoordinateOfEntity().distance(other.getCenteredCoordinateOfEntity()); } /** * Returns distance from this entity to other Coordinate. Uses centered coordinate as start * coordinate. Does not influence given otherCoordinate param * @param otherCoordinate * @return */ public float distanceTo(Coordinate otherCoordinate) { return getCenteredCoordinateOfEntity().distance(otherCoordinate); } /** * Returns distance from this entity to other Map coordinate in 'cells'. * * @param otherCoordinate * @return */ public int distanceToInMapCoords(MapCoordinate otherCoordinate) { return coordinate.toMapCoordinate().distanceInMapCoords(otherCoordinate); } public int getX() { return coordinate.getXAsInt(); } public int getY() { return coordinate.getYAsInt(); } public int getSight() { return entityData.sight; } public Player getPlayer() { return player; } public boolean belongsToPlayer(Player other) { return other.equals(player); } public boolean isMovable() { return this instanceof Moveable; } public boolean isSelectable() { return this instanceof Selectable; } public boolean isUpdatable() { return this instanceof Updateable; } public boolean isDestructible() { return this instanceof Destructible; } public boolean isDestroyer() { return this instanceof Destroyer; } public boolean isFocusable() { return this instanceof Focusable; } public boolean isSuperPower() { return this instanceof SuperPower; } /** * Capable of harvesting stuff * @return */ public boolean isHarvester() { return entityData.isHarvester; } public abstract EntityType getEntityType(); public boolean isEntityTypeStructure() { return getEntityType().equals(EntityType.STRUCTURE); } public boolean removeFromPlayerSet(Entity entity) { if (player != null) { return player.removeEntity(entity); } return false; } public Coordinate getRandomPositionWithin() { return new Coordinate(Vector2D.random(getX(), getX() + entityData.getWidth(), getY(), getY() + entityData.getHeight())); } public Vector2D getDimensions() { return Vector2D.create(entityData.getWidth(), entityData.getHeight()); } @Override public void enrichRenderQueue(RenderQueue renderQueue) { // by default do nothing } public Vector2D getHalfSizeOfEntity() { return Vector2D.create(entityData.getWidth() / 2, entityData.getHeight() / 2); } /** * Return the metadata about this entity. * @return */ public EntityData getEntityData() { return this.entityData; } public int getWidthInCells() { return entityData.getWidthInCells(); } public int getHeightInCells() { return entityData.getHeightInCells(); } public List<MapCoordinate> getAllCellsAsMapCoordinates() { return entityData.getAllCellsAsCoordinates(coordinate); } public List<Coordinate> getAllCellsAsCoordinates() { List<MapCoordinate> allCellsAsCoordinates = entityData.getAllCellsAsCoordinates(coordinate); return allCellsAsCoordinates.stream().map(mc -> mc.toCoordinate()).collect(Collectors.toList()); } public List<MapCoordinate> getAllSurroundingCellsAsCoordinates() { return getMapCoordinates(coordinate.toMapCoordinate()); // coordinate == top left } // this basically goes 'around' the entity, starting from top-left public List<MapCoordinate> getMapCoordinates(MapCoordinate topLeftMapCoordinate) { int currentX = topLeftMapCoordinate.getXAsInt(); int currentY = topLeftMapCoordinate.getYAsInt(); ArrayList<MapCoordinate> result = new ArrayList<>(); // first row int topRowY = currentY - 1; for (int x = 0; x < (entityData.getWidthInCells() + 2); x++) { int calculatedX = (currentX - 1) + x; result.add(MapCoordinate.create(calculatedX, topRowY)); } int leftX = (currentX - 1); // then all 'sides' of the structure (left and right) for (int y = 0; y < entityData.getHeightInCells(); y++) { int calculatedY = currentY + y; // left side result.add(MapCoordinate.create(leftX, calculatedY)); // right side int rightX = (currentX + entityData.getWidthInCells()); result.add(MapCoordinate.create(rightX, calculatedY)); } // bottom row int bottomRowY = currentY + entityData.getHeightInCells(); for (int x = 0; x < (entityData.getWidthInCells() + 2); x++) { int calculatedX = leftX + x; result.add(MapCoordinate.create(calculatedX, bottomRowY)); } return result; } public boolean isVisibleFor(Player player, Map map) { List<Cell> allCellsOccupiedByEntity = map.getAllCellsOccupiedByEntity(this); for (Cell cell : allCellsOccupiedByEntity) { if (cell.isVisibleFor(player)) return true; } return false; } public Entity setOrigin(Entity origin) { this.origin = origin; return this; } public boolean isEntityBuilder() { return this.entityData.entityBuilderType != EntityBuilderType.NONE; } public boolean isVectorWithin(Coordinate coordinate) { Rectangle entityRectangle = Rectangle.createWithDimensions(getCoordinate(), getDimensions()); boolean result = entityRectangle.isVectorWithin(coordinate); // System.out.println("Checking if Coordinate (" + result + ") : " + coordinate + " is within Rectangle of [" + this.getEntityData().key + "] : " + entityRectangle); return result; } protected final java.util.Map<EventType, List<EventSubscription<? extends Entity>>> eventTypeListMap = new HashMap(); public <T extends Entity> void onEvent(EventType eventType, T subscriber, Function<T, Void> eventHandler) { this.onEvent(eventType, subscriber, eventHandler, true); } protected <T extends Entity> void onEvent(EventType eventType, T subscriber, Function<T, Void> eventHandler, boolean registerDestroyEventHandler) { if (!eventTypeListMap.containsKey(eventType)) { eventTypeListMap.put(eventType, new LinkedList<>()); } addEventSubscription(eventType, subscriber, eventHandler); if (registerDestroyEventHandler) { // when the subscriber gets destroyed, let this entity know it happened. subscriber.onEvent(EventType.ENTITY_DESTROYED, this, s -> s.removeEventSubscription(subscriber), false); if (subscriber != this) { // when this gets destroyed, tell the *other* subscriber that it happened. this.onEvent(EventType.ENTITY_DESTROYED, subscriber, s -> s.removeEventSubscription(this), false); } } } private <T extends Entity> EventSubscription addEventSubscription(EventType eventType, T subscriber, Function<T, Void> eventHandler) { EventSubscription eventSubscription = new EventSubscription(subscriber, eventHandler); if (!eventTypeListMap.get(eventType).contains(eventSubscription)) { eventTypeListMap.get(eventType).add(eventSubscription); } return eventSubscription; } protected <T extends Entity> Void removeEventSubscription(T subscriber) { System.out.println(this + " received removeEventSubscription, Entity destroyed is " + subscriber); for (List<EventSubscription<? extends Entity>> subscriptions : eventTypeListMap.values()) { // find all event subscriptions that have this subscriber List<EventSubscription<? extends Entity>> toBeDeleted = new ArrayList<>(); for (EventSubscription subscription : subscriptions) { if (subscription.getSubscriber() == subscriber) { // check by reference! toBeDeleted.add(subscription); } } // delete those for (EventSubscription subscription : toBeDeleted) { subscriptions.remove(subscription); } } return null; } public void destroy() { emitEvent(EventType.ENTITY_DESTROYED); // tell all who are interested that we are destroyed eventTypeListMap.clear(); // now clear all our subscriptions explicitly } public void emitEvent(EventType eventType) { if (eventTypeListMap.containsKey(eventType)) { for (EventSubscription eventSubscription : eventTypeListMap.get(eventType)){ System.out.println(this.toString() + " emits event " + eventType); eventSubscription.invoke(); } } } class EventSubscription<T extends Entity> { private T subscriber; private Function<T, Void> eventHandler; public EventSubscription(T subscriber, Function<T, Void> eventHandler) { this.subscriber = subscriber; this.eventHandler = eventHandler; } public void invoke() { eventHandler.apply(subscriber); } public T getSubscriber() { return subscriber; } } }
package org.roi.itlab.cassandra; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; public class PoiLoader { private PoiLoader() {} public static List<Poi> loadFromCsv(String filename) throws IOException { final Function<String, Poi> mapToPoi = line -> { String[] p = line.split("\\|"); return new Poi(p[1], p[4], Integer.parseInt(p[0]), Double.parseDouble(p[2]), Double.parseDouble(p[3])); }; return Files.lines(Paths.get(filename)).map(mapToPoi) .collect(Collectors.toList()); } }
package com.github.apixandru.games.rummikub; /** * @author Alexandru-Constantin Bledea * @since Sep 16, 2015 */ public enum Rank { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN, TWELVE, THIRTEEN; /** * @return */ public static Rank next(final Rank rank) { if (null == rank || rank.ordinal() >= values().length - 1) { return null; } return values()[rank.ordinal() + 1]; } }
package com.github.bednar.aap.model.api; import java.util.List; import com.google.common.collect.Lists; public final class ApiModel { public String path = ""; public String[] consumes = new String[]{}; public String[] produces = new String[]{}; public String shortDescription = ""; public List<OperationModel> operations = Lists.newArrayList(); }
package org.ccnx.ccn.impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.NotYetConnectedException; import java.util.ArrayList; import java.util.Set; import java.util.SortedMap; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import org.ccnx.ccn.CCNFilterListener; import org.ccnx.ccn.CCNInterestListener; import org.ccnx.ccn.ContentVerifier; import org.ccnx.ccn.KeyManager; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.impl.CCNStats.CCNEnumStats; import org.ccnx.ccn.impl.CCNStats.CCNEnumStats.IStatsEnum; import org.ccnx.ccn.impl.InterestTable.Entry; import org.ccnx.ccn.impl.encoding.XMLEncodable; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.ContentEncodingException; import org.ccnx.ccn.profiles.ccnd.CCNDaemonException; import org.ccnx.ccn.profiles.ccnd.PrefixRegistrationManager; import org.ccnx.ccn.profiles.ccnd.PrefixRegistrationManager.ForwardingEntry; import org.ccnx.ccn.profiles.context.ServiceDiscoveryProfile; import org.ccnx.ccn.profiles.security.KeyProfile; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; import org.ccnx.ccn.protocol.WirePacket; /** * The low level interface to ccnd. Connects to a ccnd. For UDP it must maintain the connection by * sending heartbeats to it. Other functions include reading and writing interests and content * to/from the ccnd, starting handler threads to feed interests and content to registered handlers, * and refreshing unsatisfied interests. * * This class attempts to notice when a ccnd has died and to reconnect to a ccnd when it is restarted. * * It also handles the low level output "tap" functionality - this allows inspection or logging of * all the communications with ccnd. * * Starts a separate thread to listen to, decode and handle incoming data from ccnd. */ public class CCNNetworkManager implements Runnable { public static final int DEFAULT_AGENT_PORT = 9695; // ccnx registered port public static final String DEFAULT_AGENT_HOST = "localhost"; public static final String PROP_AGENT_PORT = "ccn.agent.port"; public static final String PROP_AGENT_HOST = "ccn.agent.host"; public static final String PROP_TAP = "ccn.tap"; public static final String ENV_TAP = "CCN_TAP"; // match C library public static final int PERIOD = 2000; // period for occasional ops in ms. public static final int MAX_PERIOD = PERIOD * 8; public static final String KEEPALIVE_NAME = "/HereIAm"; public static final int THREAD_LIFE = 8; // in seconds public static final int MAX_PAYLOAD = 8800; // number of bytes in UDP payload /** * Definitions for which network protocol to use. This allows overriding * the current default. */ public enum NetworkProtocol { UDP (17), TCP (6); NetworkProtocol(Integer i) { this._i = i; } private final Integer _i; public Integer value() { return _i; } } /* * This ccndId is set on the first connection with 'ccnd' and is the * 'device name' that all of our control communications will use to * ensure that we are talking to our local 'ccnd'. */ protected static Integer _idSyncer = new Integer(0); protected static PublisherPublicKeyDigest _ccndId = null; protected Integer _faceID = null; protected CCNDIdGetter _getter = null; /* * Static singleton. */ protected Thread _thread = null; // the main processing thread protected ThreadPoolExecutor _threadpool = null; // pool service for callback threads protected CCNNetworkChannel _channel = null; // for use by run thread only! protected boolean _run = true; // protected ContentObject _keepalive; protected FileOutputStream _tapStreamOut = null; protected FileOutputStream _tapStreamIn = null; protected long _lastHeartbeat = 0; protected int _port = DEFAULT_AGENT_PORT; protected String _host = DEFAULT_AGENT_HOST; protected NetworkProtocol _protocol = SystemConfiguration.AGENT_PROTOCOL; // For handling protocol to speak to ccnd, must have keys protected KeyManager _keyManager; protected int _localPort = -1; // Tables of interests/filters: users must synchronize on collection protected InterestTable<InterestRegistration> _myInterests = new InterestTable<InterestRegistration>(); protected InterestTable<Filter> _myFilters = new InterestTable<Filter>(); public static final boolean DEFAULT_PREFIX_REG = true; protected boolean _usePrefixReg = DEFAULT_PREFIX_REG; protected PrefixRegistrationManager _prefixMgr = null; protected Timer _periodicTimer = null; protected boolean _timersSetup = false; protected TreeMap<ContentName, RegisteredPrefix> _registeredPrefixes = new TreeMap<ContentName, RegisteredPrefix>(); /** * Keep track of prefixes that are actually registered with ccnd (as opposed to Filters used * to dispatch interests). There may be several filters for each registered prefix. */ public class RegisteredPrefix implements CCNInterestListener { private int _refCount = 1; private ForwardingEntry _forwarding = null; // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds. The refresh code needs // to understand this. This isn't a problem for now because the lifetime we request when we register a // prefix we use Integer.MAX_VALUE as the requested lifetime. private long _lifetime = -1; // in seconds private long _nextRefresh = -1; private boolean _closing = false; public RegisteredPrefix(ForwardingEntry forwarding) { _forwarding = forwarding; if (null != forwarding) { _lifetime = forwarding.getLifetime(); _nextRefresh = System.currentTimeMillis() + (_lifetime / 2); } } /** * Waiter for prefixes being deregistered. This is because we don't want to * wait for the prefix to be deregistered normally, but if we try to re-register * it we have to to avoid races. */ public Interest handleContent(ContentObject data, Interest interest) { synchronized (this) { notifyAll(); } synchronized (_registeredPrefixes) { _registeredPrefixes.remove(_forwarding.getPrefixName()); } return null; } } /** * Do scheduled interest and registration refreshes */ private class PeriodicWriter extends TimerTask { // TODO Interest refresh time is supposed to "decay" over time but there are currently // unresolved problems with this. public void run() { //this method needs to do a few things // - reopen connection to ccnd if down // - refresh interests // - refresh prefix registrations // - heartbeats boolean refreshError = false; if (_protocol == NetworkProtocol.UDP) { if (!_channel.isConnected()) { //we are not connected. reconnect attempt is in the heartbeat function... _channel.heartbeat(); } } if (!_channel.isConnected()) { //we tried to reconnect and failed, try again next loop Log.fine(Log.FAC_NETMANAGER, "Not Connected to ccnd, try again in {0}ms", CCNNetworkChannel.SOCKET_TIMEOUT); _lastHeartbeat = 0; if (_run) _periodicTimer.schedule(new PeriodicWriter(), CCNNetworkChannel.SOCKET_TIMEOUT); return; } long ourTime = System.currentTimeMillis(); long minInterestRefreshTime = PERIOD + ourTime; // Library.finest("Refreshing interests (size " + _myInterests.size() + ")"); // Re-express interests that need to be re-expressed try { synchronized (_myInterests) { for (Entry<InterestRegistration> entry : _myInterests.values()) { InterestRegistration reg = entry.value(); // allow some slop for scheduling if (ourTime + 20 > reg.nextRefresh) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Refresh interest: {0}", reg.interest); _lastHeartbeat = ourTime; reg.nextRefresh = ourTime + reg.nextRefreshPeriod; try { write(reg.interest); } catch (NotYetConnectedException nyce) { refreshError = true; } } if (minInterestRefreshTime > reg.nextRefresh) minInterestRefreshTime = reg.nextRefresh; } } } catch (ContentEncodingException xmlex) { Log.severe(Log.FAC_NETMANAGER, "PeriodicWriter interest refresh thread failure (Malformed datagram): {0}", xmlex.getMessage()); Log.warningStackTrace(xmlex); refreshError = true; } // Re-express prefix registrations that need to be re-expressed // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds. The refresh code needs // to understand this. This isn't a problem for now because the lifetime we request when we register a // prefix we use Integer.MAX_VALUE as the requested lifetime. // FIXME: so lets not go around the loop doing nothing... for now. long minFilterRefreshTime = PERIOD + ourTime; if (false && _usePrefixReg) { synchronized (_registeredPrefixes) { for (ContentName prefix : _registeredPrefixes.keySet()) { RegisteredPrefix rp = _registeredPrefixes.get(prefix); if (null != rp._forwarding && rp._lifetime != -1 && rp._nextRefresh != -1) { if (ourTime > rp._nextRefresh) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Refresh registration: {0}", prefix); rp._nextRefresh = -1; try { ForwardingEntry forwarding = _prefixMgr.selfRegisterPrefix(prefix); if (null != forwarding) { rp._lifetime = forwarding.getLifetime(); // filter.nextRefresh = new Date().getTime() + (filter.lifetime / 2); _lastHeartbeat = System.currentTimeMillis(); rp._nextRefresh = _lastHeartbeat + (rp._lifetime / 2); } rp._forwarding = forwarding; } catch (CCNDaemonException e) { Log.warning(e.getMessage()); // XXX - don't think this is right rp._forwarding = null; rp._lifetime = -1; rp._nextRefresh = -1; refreshError = true; } } if (minFilterRefreshTime > rp._nextRefresh) minFilterRefreshTime = rp._nextRefresh; } } // for (Entry<Filter> entry: _myFilters.values()) } // synchronized (_myFilters) } // _usePrefixReg if (refreshError) { Log.warning(Log.FAC_NETMANAGER, "we have had an error when refreshing an interest or prefix registration... do we need to reconnect to ccnd?"); } long currentTime = System.currentTimeMillis(); long checkInterestDelay = minInterestRefreshTime - currentTime; if (checkInterestDelay < 0) checkInterestDelay = 0; if (checkInterestDelay > PERIOD) checkInterestDelay = PERIOD; long checkPrefixDelay = minFilterRefreshTime - currentTime; if (checkPrefixDelay < 0) checkPrefixDelay = 0; if (checkPrefixDelay > PERIOD) checkPrefixDelay = PERIOD; long useMe; if (checkInterestDelay < checkPrefixDelay) { useMe = checkInterestDelay; } else { useMe = checkPrefixDelay; } if (_protocol == NetworkProtocol.UDP) { //we haven't sent anything... maybe need to send a heartbeat if ((currentTime - _lastHeartbeat) >= CCNNetworkChannel.HEARTBEAT_PERIOD) { _lastHeartbeat = currentTime; _channel.heartbeat(); } //now factor in heartbeat time long timeToHeartbeat = CCNNetworkChannel.HEARTBEAT_PERIOD - (currentTime - _lastHeartbeat); if (useMe > timeToHeartbeat) useMe = timeToHeartbeat; } if (useMe < 20) { useMe = 20; } if (_run) _periodicTimer.schedule(new PeriodicWriter(), useMe); } /* run */ } /* private class PeriodicWriter extends TimerTask */ /** * First time startup of timing stuff after first registration * We don't bother to "unstartup" if everything is deregistered * @throws IOException */ private void setupTimers() throws IOException { if (!_timersSetup) { _timersSetup = true; _channel.init(); if (_protocol == NetworkProtocol.UDP) { _channel.heartbeat(); _lastHeartbeat = System.currentTimeMillis(); } // Create timer for periodic behavior _periodicTimer = new Timer(true); _periodicTimer.schedule(new PeriodicWriter(), PERIOD); } } /** Generic superclass for registration objects that may have a listener * Handles invalidation and pending delivery consistently to enable * subclass to call listener callback without holding any library locks, * yet avoid delivery to a cancelled listener. */ protected abstract class ListenerRegistration implements Runnable { protected Object listener; protected CCNNetworkManager manager; public Semaphore sema = null; //used to block thread waiting for data or null if none public Object owner = null; protected boolean deliveryPending = false; protected long id; public abstract void deliver(); /** * This is called when removing interest or content handlers. It's purpose * is to insure that once the remove call begins it completes atomically without more * handlers being triggered. Note that there is still not full atomicity here * because a dispatch to handler might be in progress and we don't hold locks * throughout the dispatch to avoid deadlocks. */ public void invalidate() { // There may be a pending delivery in progress, and it doesn't // happen while holding this lock because that would give the // application callback code power to block library processing. // Instead, we use a flag that is checked and set under this lock // to be sure that on exit from invalidate() there will be. // Back off to avoid livelock for (int i = 0; true; i = (2 * i + 1) & 63) { synchronized (this) { // Make invalid, this will prevent any new delivery that comes // along from doing anything. this.listener = null; this.sema = null; // Return only if no delivery is in progress now (or if we are // called out of our own handler) if (!deliveryPending || (Thread.currentThread().getId() == id)) { return; } } if (i == 0) { Thread.yield(); } else { if (i > 3) Log.finer(Log.FAC_NETMANAGER, "invalidate spin {0}", i); try { Thread.sleep(i); } catch (InterruptedException e) { } } } } /** * Calls the client handler */ public void run() { id = Thread.currentThread().getId(); synchronized (this) { // Mark us pending delivery, so that any invalidate() that comes // along will not return until delivery has finished this.deliveryPending = true; } try { // Delivery may synchronize on this object to access data structures // but should hold no locks when calling the listener deliver(); } catch (Exception ex) { Log.warning(Log.FAC_NETMANAGER, "failed delivery: {0}", ex); } finally { synchronized(this) { this.deliveryPending = false; } } } /** Equality based on listener if present, so multiple objects can * have the same interest registered without colliding */ public boolean equals(Object obj) { if (obj instanceof ListenerRegistration) { ListenerRegistration other = (ListenerRegistration)obj; if (this.owner == other.owner) { if (null == this.listener && null == other.listener){ return super.equals(obj); } else if (null != this.listener && null != other.listener) { return this.listener.equals(other.listener); } } } return false; } public int hashCode() { if (null != this.listener) { if (null != owner) { return owner.hashCode() + this.listener.hashCode(); } else { return this.listener.hashCode(); } } else { return super.hashCode(); } } } /* protected abstract class ListenerRegistration implements Runnable */ /** * Record of Interest * listener must be set (non-null) for cases of standing Interest that holds * until canceled by the application. The listener should be null when a * thread is blocked waiting for data, in which case the thread will be * blocked on semaphore. */ protected class InterestRegistration extends ListenerRegistration { public final Interest interest; ContentObject data = null; protected long nextRefresh; // next time to refresh the interest protected long nextRefreshPeriod = SystemConfiguration.INTEREST_REEXPRESSION_DEFAULT; // period to wait before refresh // All internal client interests must have an owner public InterestRegistration(CCNNetworkManager mgr, Interest i, CCNInterestListener l, Object owner) { manager = mgr; interest = i; listener = l; this.owner = owner; if (null == listener) { sema = new Semaphore(0); } nextRefresh = System.currentTimeMillis() + nextRefreshPeriod; } /** * Return true if data was added. * If data is already pending for delivery for this interest, the * interest is already consumed and this new data cannot be delivered. * @throws NullPointerException If obj is null */ public synchronized boolean add(ContentObject obj) { if (null == data) { // No data pending, this obj will consume interest this.data = obj; // we let this raise exception if obj == null return true; } else { // Data is already pending, this interest is already consumed, cannot add obj return false; } } /** * This used to be called just data, but its similarity * to a simple accessor made the fact that it cleared the data * really confusing and error-prone... * Pull the available data out for processing. * @return */ public synchronized ContentObject popData() { ContentObject result = this.data; this.data = null; return result; } /** * Deliver content to a registered handler */ public void deliver() { try { if (null != this.listener) { // Standing interest: call listener callback ContentObject pending = null; CCNInterestListener listener = null; synchronized (this) { if (null != this.data && null != this.listener) { pending = this.data; this.data = null; listener = (CCNInterestListener)this.listener; } } // Call into client code without holding any library locks if (null != pending) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Interest callback (" + pending + " data) for: {0}", this.interest.name()); synchronized (this) { // DKS -- dynamic interests, unregister the interest here and express new one if we have one // previous interest is final, can't update it this.deliveryPending = false; } manager.unregisterInterest(this); // paul r. note - contract says interest will be gone after the call into user's code. // Eventually this may be modified for "pipelining". // DKS TODO tension here -- what object does client use to cancel? // Original implementation had expressInterest return a descriptor // used to cancel it, perhaps we should go back to that. Otherwise // we may need to remember at least the original interest for cancellation, // or a fingerprint representation that doesn't include the exclude filter. // DKS even more interesting -- how do we update our interest? Do we? // it's final now to avoid contention, but need to change it or change // the registration. Interest updatedInterest = listener.handleContent(pending, interest); // Possibly we should optimize here for the case where the same interest is returned back // (now we would unregister it, then reregister it) but need to be careful that the timing // behavior is right if we do that if (null != updatedInterest) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Interest callback: updated interest to express: {0}", updatedInterest.name()); // luckily we saved the listener // if we want to cancel this one before we get any data, we need to remember the // updated interest in the listener manager.expressInterest(this.owner, updatedInterest, listener); } } else { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Interest callback skipped (no data) for: {0}", this.interest.name()); } } else { synchronized (this) { if (null != this.sema) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Data consumes pending get: {0}", this.interest.name()); // Waiting thread will pickup data -- wake it up // If this interest came from net or waiting thread timed out, // then no thread will be waiting but no harm is done if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "releasing {0}", this.sema); this.sema.release(); } } if (null == this.sema) { // this is no longer valid registration if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Interest callback skipped (not valid) for: {0}", this.interest.name()); } } } catch (Exception ex) { Log.warning(Log.FAC_NETMANAGER, "failed to deliver data: {0}", ex); Log.warningStackTrace(ex); } } /** * Start a thread to deliver data to a registered handler */ public void run() { synchronized (this) { // For now only one piece of data may be delivered per InterestRegistration // This might change when "pipelining" is implemented if (deliveryPending) return; } super.run(); } } /* protected class InterestRegistration extends ListenerRegistration */ /** * Record of a filter describing portion of namespace for which this * application can respond to interests. Used to deliver incoming interests * to registered interest handlers */ protected class Filter extends ListenerRegistration { protected Interest interest; // interest to be delivered // extra interests to be delivered: separating these allows avoidance of ArrayList obj in many cases protected ArrayList<Interest> extra = new ArrayList<Interest>(1); protected ContentName prefix = null; public Filter(CCNNetworkManager mgr, ContentName n, CCNFilterListener l, Object o) { prefix = n; listener = l; owner = o; manager = mgr; } public synchronized boolean add(Interest i) { if (null == interest) { interest = i; return true; } else { // Special case, more than 1 interest pending for delivery // Only 1 interest gets added at a time, but more than 1 // may arrive before a callback is dispatched if (null == extra) { extra = new ArrayList<Interest>(1); } extra.add(i); return false; } } /** * Deliver interest to a registered handler */ public void deliver() { try { Interest pending = null; ArrayList<Interest> pendingExtra = null; CCNFilterListener listener = null; // Grab pending interest(s) under the lock synchronized (this) { if (null != this.interest && null != this.listener) { pending = interest; interest = null; if (null != this.extra) { pendingExtra = extra; extra = null; // Don't create new ArrayList for extra here, will be done only as needed in add() } } listener = (CCNFilterListener)this.listener; } // pending signifies whether there is anything if (null != pending) { // Call into client code without holding any library locks if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Filter callback for: {0}", prefix); listener.handleInterest(pending); // Now extra callbacks for additional interests if (null != pendingExtra) { int countExtra = 0; for (Interest pi : pendingExtra) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) { countExtra++; Log.finer(Log.FAC_NETMANAGER, "Filter callback (extra {0} of {1}) for: {2}", countExtra, pendingExtra.size(), prefix); } listener.handleInterest(pi); } } } else { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Filter callback skipped (no interests) for: {0}", prefix); } } catch (RuntimeException ex) { Log.warning(Log.FAC_NETMANAGER, "failed to deliver interest: {0}", ex); Log.warningStackTrace(ex); } } @Override public String toString() { return prefix.toString(); } } /* protected class Filter extends ListenerRegistration */ private class CCNDIdGetter implements Runnable { CCNNetworkManager _networkManager; KeyManager _keyManager; @SuppressWarnings("unused") public CCNDIdGetter(CCNNetworkManager networkManager, KeyManager keyManager) { _networkManager = networkManager; _keyManager = keyManager; } public void run() { boolean isNull = false; PublisherPublicKeyDigest sentID = null; synchronized (_idSyncer) { isNull = (null == _ccndId); } if (isNull) { try { sentID = fetchCCNDId(_networkManager, _keyManager); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (null == sentID) { Log.severe(Log.FAC_NETMANAGER, "CCNDIdGetter: call to fetchCCNDId returned null."); } synchronized(_idSyncer) { _ccndId = sentID; if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "CCNDIdGetter: ccndId {0}", ContentName.componentPrintURI(sentID.digest())); } } /* null == _ccndId */ } /* run() */ } /* private class CCNDIdGetter implements Runnable */ /** * The constructor. Attempts to connect to a ccnd at the currently specified port number * @throws IOException if the port is invalid */ public CCNNetworkManager(KeyManager keyManager) throws IOException { if (null == keyManager) { // Unless someone gives us one later, we won't be able to register filters. Log this. if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "CCNNetworkManager: being created with null KeyManager. Must set KeyManager later to be able to register filters."); } _keyManager = keyManager; // Determine port at which to contact agent String portval = System.getProperty(PROP_AGENT_PORT); if (null != portval) { try { _port = new Integer(portval); } catch (Exception ex) { throw new IOException("Invalid port '" + portval + "' specified in " + PROP_AGENT_PORT); } Log.warning(Log.FAC_NETMANAGER, "Non-standard CCN agent port " + _port + " per property " + PROP_AGENT_PORT); } String hostval = System.getProperty(PROP_AGENT_HOST); if (null != hostval && hostval.length() > 0) { _host = hostval; Log.warning(Log.FAC_NETMANAGER, "Non-standard CCN agent host " + _host + " per property " + PROP_AGENT_HOST); } _protocol = SystemConfiguration.AGENT_PROTOCOL; if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "Contacting CCN agent at " + _host + ":" + _port); String tapname = System.getProperty(PROP_TAP); if (null == tapname) { tapname = System.getenv(ENV_TAP); } if (null != tapname) { long msecs = System.currentTimeMillis(); long secs = msecs/1000; msecs = msecs % 1000; String unique_tapname = tapname + "-T" + Thread.currentThread().getId() + "-" + secs + "-" + msecs; setTap(unique_tapname); } _channel = new CCNNetworkChannel(_host, _port, _protocol, _tapStreamIn); _ccndId = null; _channel.open(); // Create callback threadpool and main processing thread _threadpool = (ThreadPoolExecutor)Executors.newCachedThreadPool(); _threadpool.setKeepAliveTime(THREAD_LIFE, TimeUnit.SECONDS); _thread = new Thread(this, "CCNNetworkManager"); _thread.start(); } /** * Shutdown the connection to ccnd and all threads associated with this network manager */ public void shutdown() { Log.info(Log.FAC_NETMANAGER, "Shutdown requested"); _run = false; if (_periodicTimer != null) _periodicTimer.cancel(); if (null != _channel) { try { setTap(null); _channel.close(); } catch (IOException io) { // Ignore since we're shutting down } } } /** * Get the protocol this network manager is using * @return the protocol */ public NetworkProtocol getProtocol() { return _protocol; } /** * Turns on writing of all packets to a file for test/debug * Overrides any previous setTap or environment/property setting. * Pass null to turn off tap. * @param pathname name of tap file */ public void setTap(String pathname) throws IOException { // Turn off any active tap if (null != _tapStreamOut) { FileOutputStream closingStream = _tapStreamOut; _tapStreamOut = null; closingStream.close(); } if (null != _tapStreamIn) { FileOutputStream closingStream = _tapStreamIn; _tapStreamIn = null; closingStream.close(); } if (pathname != null && pathname.length() > 0) { _tapStreamOut = new FileOutputStream(new File(pathname + "_out")); _tapStreamIn = new FileOutputStream(new File(pathname + "_in")); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "Tap writing to {0}", pathname); } } /** * Get the CCN Name of the 'ccnd' we're connected to. * * @return the CCN Name of the 'ccnd' this CCNNetworkManager is connected to. * @throws IOException */ public PublisherPublicKeyDigest getCCNDId() throws IOException { /* * Now arrange to have the ccndId read. We can't do that here because we need * to return back to the create before we know we get the answer back. We can * cause the prefix registration to wait. */ PublisherPublicKeyDigest sentID = null; boolean doFetch = false; synchronized (_idSyncer) { if (null == _ccndId) { doFetch = true; } else { return _ccndId; } } if (doFetch) { sentID = fetchCCNDId(this, _keyManager); if (null == sentID) { Log.severe(Log.FAC_NETMANAGER, "getCCNDId: call to fetchCCNDId returned null."); return null; } } synchronized (_idSyncer) { _ccndId = sentID; return _ccndId; } } public KeyManager getKeyManager() { return _keyManager; } public void setKeyManager(KeyManager manager) { _keyManager = manager; } /** * Write content to ccnd * * @param co the content * @return the same content that was passed into the method * * TODO - code doesn't actually throw either of these exceptions but need to fix upper * level code to compensate when they are removed. * @throws IOException * @throws InterruptedException */ public ContentObject put(ContentObject co) throws IOException, InterruptedException { _stats.increment(StatsEnum.Puts); try { write(co); } catch (ContentEncodingException e) { Log.warning(Log.FAC_NETMANAGER, "Exception in lowest-level put for object {0}! {1}", co.name(), e); } return co; } /** * get content matching an interest from ccnd. Expresses an interest, waits for ccnd to * return matching the data, then removes the interest and returns the data to the caller. * * TODO should probably handle InterruptedException at this level instead of throwing it to * higher levels * * @param interest the interest * @param timeout time to wait for return in ms * @return ContentObject or null on timeout * @throws IOException on incorrect interest data * @throws InterruptedException if process is interrupted during wait */ public ContentObject get(Interest interest, long timeout) throws IOException, InterruptedException { _stats.increment(StatsEnum.Gets); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "get: {0} with timeout: {1}", interest, timeout); InterestRegistration reg = new InterestRegistration(this, interest, null, null); expressInterest(reg); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "blocking for {0} on {1}", interest.name(), reg.sema); // Await data to consume the interest if (timeout == SystemConfiguration.NO_TIMEOUT) reg.sema.acquire(); // currently no timeouts else reg.sema.tryAcquire(timeout, TimeUnit.MILLISECONDS); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "unblocked for {0} on {1}", interest.name(), reg.sema); // Typically the main processing thread will have registered the interest // which must be undone here, but no harm if never registered unregisterInterest(reg); return reg.popData(); } /** * We express interests to the ccnd and register them within the network manager * * @param caller must not be null * @param interest the interest * @param callbackListener listener to callback on receipt of data * @throws IOException on incorrect interest */ public void expressInterest( Object caller, Interest interest, CCNInterestListener callbackListener) throws IOException { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. if (null == callbackListener) { throw new NullPointerException("expressInterest: callbackListener cannot be null"); } if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "expressInterest: {0}", interest); InterestRegistration reg = new InterestRegistration(this, interest, callbackListener, caller); expressInterest(reg); } private void expressInterest(InterestRegistration reg) throws IOException { _stats.increment(StatsEnum.ExpressInterest); try { registerInterest(reg); write(reg.interest); } catch (ContentEncodingException e) { unregisterInterest(reg); throw e; } } /** * Cancel this query with all the repositories we sent * it to. * * @param caller must not be null * @param interest * @param callbackListener */ public void cancelInterest(Object caller, Interest interest, CCNInterestListener callbackListener) { if (null == callbackListener) { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. throw new NullPointerException("cancelInterest: callbackListener cannot be null"); } _stats.increment(StatsEnum.CancelInterest); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "cancelInterest: {0}", interest.name()); // Remove interest from repeated presentation to the network. unregisterInterest(caller, interest, callbackListener); } /** * Register a standing interest filter with callback to receive any * matching interests seen. Any interests whose prefix completely matches "filter" will * be delivered to the listener. Also if this filter matches no currently registered * prefixes, register its prefix with ccnd. * * @param caller must not be null * @param filter ContentName containing prefix of interests to match * @param callbackListener a CCNFilterListener * @throws IOException */ public void setInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener) throws IOException { setInterestFilter(caller, filter, callbackListener, null); } /** * Register a standing interest filter with callback to receive any * matching interests seen. Any interests whose prefix completely matches "filter" will * be delivered to the listener. Also if this filter matches no currently registered * prefixes, register its prefix with ccnd. * * @param caller must not be null * @param filter ContentName containing prefix of interests to match * @param callbackListener a CCNFilterListener * @param registrationFlags to use for this registration. * @throws IOException */ public void setInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener, Integer registrationFlags) throws IOException { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "setInterestFilter: {0}", filter); if ((null == _keyManager) || (!_keyManager.initialized() || (null == _keyManager.getDefaultKeyID()))) { Log.warning(Log.FAC_NETMANAGER, "Cannot set interest filter -- key manager not ready!"); throw new IOException("Cannot set interest filter -- key manager not ready!"); } // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. setupTimers(); if (_usePrefixReg) { try { if (null == _prefixMgr) { _prefixMgr = new PrefixRegistrationManager(this); } synchronized(_registeredPrefixes) { RegisteredPrefix oldPrefix = getRegisteredPrefix(filter); if (null != oldPrefix) { if (oldPrefix._closing) { synchronized (oldPrefix) { try { oldPrefix.wait(); } catch (InterruptedException e) {} // XXX do we need to worry about this? } _registeredPrefixes.remove(filter); // Just in case registerPrefix(filter, registrationFlags); } else oldPrefix._refCount++; } else { registerPrefix(filter, registrationFlags); } } } catch (CCNDaemonException e) { Log.warning(Log.FAC_NETMANAGER, "setInterestFilter: unexpected CCNDaemonException: " + e.getMessage()); throw new IOException(e.getMessage()); } } Filter newOne = new Filter(this, filter, callbackListener, caller); synchronized (_myFilters) { _myFilters.add(filter, newOne); } } /** * Must be called with _registeredPrefixes locked * * @param filter * @param registrationFlags * @throws CCNDaemonException */ private void registerPrefix(ContentName filter, Integer registrationFlags) throws CCNDaemonException { ForwardingEntry entry; if (null == registrationFlags) { entry = _prefixMgr.selfRegisterPrefix(filter); } else { entry = _prefixMgr.selfRegisterPrefix(filter, null, registrationFlags, Integer.MAX_VALUE); } RegisteredPrefix newPrefix = new RegisteredPrefix(entry); _registeredPrefixes.put(filter, newPrefix); // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds. The refresh code needs // to understand this. This isn't a problem for now because the lifetime we request when we register a // prefix we use Integer.MAX_VALUE as the requested lifetime. if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "setInterestFilter: entry.lifetime: " + entry.getLifetime() + " entry.faceID: " + entry.getFaceID()); } /** * Unregister a standing interest filter * * @param caller must not be null * @param filter currently registered filter * @param callbackListener the CCNFilterListener registered to it */ public void cancelInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener) { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "cancelInterestFilter: {0}", filter); Filter newOne = new Filter(this, filter, callbackListener, caller); Entry<Filter> found = null; synchronized (_myFilters) { found = _myFilters.remove(filter, newOne); } if (null != found) { Filter thisOne = found.value(); thisOne.invalidate(); if (_usePrefixReg) { // Deregister it with ccnd only if the refCount would go to 0 synchronized (_registeredPrefixes) { RegisteredPrefix prefix = getRegisteredPrefix(filter); if (null != prefix && prefix._refCount <= 1) { ForwardingEntry entry = prefix._forwarding; if (!entry.getPrefixName().equals(filter)) { Log.severe(Log.FAC_NETMANAGER, "cancelInterestFilter filter name {0} does not match recorded name {1}", filter, entry.getPrefixName()); } try { if (null == _prefixMgr) { _prefixMgr = new PrefixRegistrationManager(this); } prefix._closing = true; _prefixMgr.unRegisterPrefix(filter, prefix, entry.getFaceID()); } catch (CCNDaemonException e) { Log.warning(Log.FAC_NETMANAGER, "cancelInterestFilter failed with CCNDaemonException: " + e.getMessage()); } } else if (null != prefix) prefix._refCount } } } } /** * Merge prefixes so we only add a new one when it doesn't have a * common ancestor already registered. * * We decided that if we are registering a prefix that already has another prefix that * is an decedent of it registered, we won't bother to now deregister that prefix because * it would be complicated to do that and doesn't hurt anything. * * @param prefix * @return prefix that incorporates or matches this one or null if none found */ protected RegisteredPrefix getRegisteredPrefix(ContentName prefix) { synchronized(_registeredPrefixes) { // We want our map to include all ancestors of us SortedMap<ContentName, RegisteredPrefix> map = _registeredPrefixes.tailMap(new ContentName(1, prefix.components())); for (ContentName name : map.keySet()) { if (name.isPrefixOf(prefix)) return _registeredPrefixes.get(name); // If our prefix isn't a prefix of this name at all, we are past all ancestors and // can stop looking if (!prefix.isPrefixOf(name)) break; } } return null; } protected void write(ContentObject data) throws ContentEncodingException { _stats.increment(StatsEnum.WriteObject); WirePacket packet = new WirePacket(data); writeInner(packet); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "Wrote content object: {0}", data.name()); } /** * Don't do this unless you know what you are doing! * @param interest * @throws ContentEncodingException */ public void write(Interest interest) throws ContentEncodingException { _stats.increment(StatsEnum.WriteInterest); WirePacket packet = new WirePacket(interest); writeInner(packet); } // DKS TODO unthrown exception private void writeInner(WirePacket packet) throws ContentEncodingException { try { byte[] bytes = packet.encode(); ByteBuffer datagram = ByteBuffer.wrap(bytes); synchronized (_channel) { int result = _channel.write(datagram); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "Wrote datagram (" + datagram.position() + " bytes, result " + result + ")"); if( result < bytes.length ) { _stats.increment(StatsEnum.WriteUnderflows); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "Wrote datagram {0} bytes to channel, but packet was {1} bytes", result, bytes.length); } if (null != _tapStreamOut) { try { _tapStreamOut.write(bytes); } catch (IOException io) { Log.warning(Log.FAC_NETMANAGER, "Unable to write packet to tap stream for debugging"); } } } } catch (IOException io) { _stats.increment(StatsEnum.WriteErrors); // We do not see errors on send typically even if // agent is gone, so log each but do not track Log.warning(Log.FAC_NETMANAGER, "Error sending packet: " + io.toString()); } } /** * Pass things on to the network stack. * @throws IOException */ private InterestRegistration registerInterest(InterestRegistration reg) throws IOException { // Add to standing interests table setupTimers(); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "registerInterest for {0}, and obj is " + _myInterests.hashCode(), reg.interest.name()); synchronized (_myInterests) { _myInterests.add(reg.interest, reg); } return reg; } private void unregisterInterest(Object caller, Interest interest, CCNInterestListener callbackListener) { InterestRegistration reg = new InterestRegistration(this, interest, callbackListener, caller); unregisterInterest(reg); } /** * @param reg - registration to unregister * * Important Note: This can indirectly need to obtain the lock for "reg" with the lock on * "myInterests" held. Therefore it can't be called when holding the lock for "reg". */ private void unregisterInterest(InterestRegistration reg) { synchronized (_myInterests) { Entry<InterestRegistration> found = _myInterests.remove(reg.interest, reg); if (null != found) { found.value().invalidate(); } } } /** * Thread method: this thread will handle reading datagrams and * starts threads to dispatch data to handlers registered for it. */ public void run() { if (! _run) { Log.warning(Log.FAC_NETMANAGER, "CCNNetworkManager run() called after shutdown"); return; } //WirePacket packet = new WirePacket(); if( Log.isLoggable(Level.INFO) ) Log.info("CCNNetworkManager processing thread started for port: " + _localPort); while (_run) { try { XMLEncodable packet = _channel.getPacket(); if (null == packet) { continue; } if (packet instanceof ContentObject) { _stats.increment(StatsEnum.ReceiveObject); ContentObject co = (ContentObject)packet; if( Log.isLoggable(Level.FINER) ) Log.finer("Data from net for port: " + _localPort + " {0}", co.name()); // SystemConfiguration.logObject("Data from net:", co); deliverData(co); // External data never goes back to network, never held onto here // External data never has a thread waiting, so no need to release sema } else if (packet instanceof Interest) { _stats.increment(StatsEnum.ReceiveInterest); Interest interest = (Interest) packet; if( Log.isLoggable(Level.FINEST) ) Log.finest("Interest from net for port: " + _localPort + " {0}", interest); InterestRegistration oInterest = new InterestRegistration(this, interest, null, null); deliverInterest(oInterest); // External interests never go back to network } // for interests } catch (Exception ex) { _stats.increment(StatsEnum.ReceiveUnknown); Log.severe(Log.FAC_NETMANAGER, "Processing thread failure (UNKNOWN): " + ex.getMessage() + " for port: " + _localPort); Log.warningStackTrace(ex); } } _threadpool.shutdown(); Log.info(Log.FAC_NETMANAGER, "Shutdown complete for port: " + _localPort); } /** * Internal delivery of interests to pending filter listeners * @param ireg */ protected void deliverInterest(InterestRegistration ireg) { _stats.increment(StatsEnum.DeliverInterest); // Call any listeners with matching filters synchronized (_myFilters) { for (Filter filter : _myFilters.getValues(ireg.interest.name())) { if (filter.owner != ireg.owner) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Schedule delivery for interest: {0}", ireg.interest); if (filter.add(ireg.interest)) _threadpool.execute(filter); } } } } /** * Deliver data to blocked getters and registered interests * @param co */ protected void deliverData(ContentObject co) { _stats.increment(StatsEnum.DeliverContent); synchronized (_myInterests) { for (InterestRegistration ireg : _myInterests.getValues(co)) { if (ireg.add(co)) { // this is a copy of the data _stats.increment(StatsEnum.DeliverContentMatchingInterests); _threadpool.execute(ireg); } } } } protected PublisherPublicKeyDigest fetchCCNDId(CCNNetworkManager mgr, KeyManager keyManager) throws IOException { try { ContentName serviceKeyName = new ContentName(ServiceDiscoveryProfile.localServiceName(ServiceDiscoveryProfile.CCND_SERVICE_NAME), KeyProfile.KEY_NAME_COMPONENT); Interest i = new Interest(serviceKeyName); i.scope(1); ContentObject c = mgr.get(i, SystemConfiguration.CCNDID_DISCOVERY_TIMEOUT); if (null == c) { String msg = ("fetchCCNDId: ccndID discovery failed due to timeout."); Log.severe(Log.FAC_NETMANAGER, msg); throw new IOException(msg); } PublisherPublicKeyDigest sentID = c.signedInfo().getPublisherKeyID(); // TODO: This needs to be fixed once the KeyRepository is fixed to provide a KeyManager if (null != keyManager) { ContentVerifier v = new ContentObject.SimpleVerifier(sentID, keyManager); if (!v.verify(c)) { String msg = ("fetchCCNDId: ccndID discovery reply failed to verify."); Log.severe(Log.FAC_NETMANAGER, msg); throw new IOException(msg); } } else { Log.severe(Log.FAC_NETMANAGER, "fetchCCNDId: do not have a KeyManager. Cannot verify ccndID."); return null; } return sentID; } catch (InterruptedException e) { Log.warningStackTrace(e); throw new IOException(e.getMessage()); } catch (IOException e) { String reason = e.getMessage(); Log.warningStackTrace(e); String msg = ("fetchCCNDId: Unexpected IOException in ccndID discovery Interest reason: " + reason); Log.severe(Log.FAC_NETMANAGER, msg); throw new IOException(msg); } } /* PublisherPublicKeyDigest fetchCCNDId() */ /** * Reregister all current prefixes with ccnd after ccnd goes down and then comes back up * @throws IOException */ private void reregisterPrefixes() throws IOException { TreeMap<ContentName, RegisteredPrefix> newPrefixes = new TreeMap<ContentName, RegisteredPrefix>(); try { synchronized (_registeredPrefixes) { for (ContentName prefix : _registeredPrefixes.keySet()) { ForwardingEntry entry = _prefixMgr.selfRegisterPrefix(prefix); RegisteredPrefix newPrefixEntry = new RegisteredPrefix(entry); newPrefixEntry._refCount = _registeredPrefixes.get(prefix)._refCount; newPrefixes.put(prefix, newPrefixEntry); } _registeredPrefixes.clear(); _registeredPrefixes.putAll(newPrefixes); } } catch (CCNDaemonException cde) { _channel.close(); } } // Statistics protected CCNEnumStats<StatsEnum> _stats = new CCNEnumStats<StatsEnum>(StatsEnum.Puts); public CCNStats getStats() { return _stats; } public enum StatsEnum implements IStatsEnum { // Just edit this list, dont need to change anything else Puts ("ContentObjects", "The number of put calls"), Gets ("ContentObjects", "The number of get calls"), WriteInterest ("calls", "The number of calls to write(Interest)"), WriteObject ("calls", "The number of calls to write(ContentObject)"), WriteErrors ("count", "Error count for writeInner()"), WriteUnderflows ("count", "The count of times when the bytes written to the channel < buffer size"), ExpressInterest ("calls", "The number of calls to expressInterest"), CancelInterest ("calls", "The number of calls to cancelInterest"), DeliverInterest ("calls", "The number of calls to deliverInterest"), DeliverContent ("calls", "The number of calls to cancelInterest"), DeliverContentMatchingInterests ("calls", "Count of the calls to threadpool.execute in handleData()"), ReceiveObject ("objects", "Receive count of ContentObjects from channel"), ReceiveInterest ("interests", "Receive count of Interests from channel"), ReceiveUnknown ("calls", "Receive count of unknown type from channel"), ; // This is the same for every user of IStatsEnum protected final String _units; protected final String _description; protected final static String [] _names; static { _names = new String[StatsEnum.values().length]; for(StatsEnum stat : StatsEnum.values() ) _names[stat.ordinal()] = stat.toString(); } StatsEnum(String units, String description) { _units = units; _description = description; } public String getDescription(int index) { return StatsEnum.values()[index]._description; } public int getIndex(String name) { StatsEnum x = StatsEnum.valueOf(name); return x.ordinal(); } public String getName(int index) { return StatsEnum.values()[index].toString(); } public String getUnits(int index) { return StatsEnum.values()[index]._units; } public String [] getNames() { return _names; } } }
package org.semanticweb.yars.nx.cli; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Iterator; import java.util.logging.Logger; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.semanticweb.yars.nx.BNode; import org.semanticweb.yars.nx.Node; import org.semanticweb.yars.nx.Nodes; import org.semanticweb.yars.nx.parser.Callback; import org.semanticweb.yars.nx.parser.NxParser; import org.semanticweb.yars.util.CallbackNxBufferedWriter; /** * Reorder some statements * @author aidhog * */ public class Patch { static transient Logger _log = Logger.getLogger(Patch.class.getName()); /** * @param args * @throws IOException * @throws org.semanticweb.yars.nx.parser.ParseException */ public static void main(String[] args) throws IOException, org.semanticweb.yars.nx.parser.ParseException { Options options = Main.getStandardOptions(); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("***ERROR: " + e.getClass() + ": " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("parameters:", options ); return; } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("parameters:", options ); return; } InputStream is = Main.getMainInputStream(cmd); OutputStream os = Main.getMainOutputStream(cmd); Iterator<Node[]> it = new NxParser(is); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); Callback cb = new CallbackNxBufferedWriter(bw); int t = 0; int s = 0; int o = 0; boolean trip = false; int a = 0; while(it.hasNext()){ a++; Node[] next = it.next(); Node[] copy = new Node[next.length]; System.arraycopy(next, 0, copy, 0, next.length); trip = false; if(next[0].toN3().startsWith("<node")){ trip = true; s++; copy[0] = BNode.createBNode(next[0].toString(), next[3].toString()); // According to the naming of the variables, the next line would // have been correct, but it is used otherwise in other code. // copy[0] = BNode.createBNode(next[3].toString(), // next[0].toString()); // copy[2] = new BNode(next[2].toString()); // No bnode renaming } if (next[2].toN3().startsWith("<node")) { trip = true; o++; copy[2] = BNode.createBNode(next[2].toString(), next[3].toString()); // According to the naming of the variables, the next line would // have been correct, but it is used otherwise in other code. // copy[0] = BNode.createBNode(next[3].toString(), // next[0].toString()); // copy[2] = new BNode(next[2].toString()); // No bnode renaming } cb.processStatement(copy); if(trip){ _log.info("Rewriting "+Nodes.toN3(next)+" to "+Nodes.toN3(copy)); t++; } } _log.info("Finished patch. Read "+a+" statements. Rewrote "+s+" subjects, "+o+" objects, "+t+" statements."); is.close(); bw.close(); } }
package com.github.davidmoten.guavamini; public final class Optional<T> { private final T value; private final boolean present; private Optional(T value, boolean present) { this.value = value; this.present = present; } private Optional() { //no-arg constructor to enable kryo (a bit yukky but not a big deal) this(null, false); } public boolean isPresent() { return present; } public T get() { if (present) return value; else throw new NotPresentException(); } public T or(T alternative) { if (present) return value; else return alternative; } public static <T> Optional<T> fromNullable(T t) { if (t == null) return Optional.absent(); else return Optional.of(t); } public static <T> Optional<T> of(T t) { return new Optional<T>(t, true); } public static <T> Optional<T> absent() { return new Optional<T>(); } public static class NotPresentException extends RuntimeException { private static final long serialVersionUID = -4444814681271790328L; } @Override public String toString() { return present ? String.format("Optional.of(%s)", value) : "Optional.absent"; } }
package org.ccnx.ccn.impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.NotYetConnectedException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.xml.stream.XMLStreamException; import org.ccnx.ccn.CCNBase; import org.ccnx.ccn.CCNFilterListener; import org.ccnx.ccn.CCNInterestListener; import org.ccnx.ccn.KeyManager; import org.ccnx.ccn.impl.InterestTable.Entry; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.WirePacket; /** * The low level interface to ccnd. Connects to a ccnd and maintains the connection by sending * heartbeats to it. Other functions include reading and writing interests and content * to/from the ccnd, starting handler threads to feed interests and content to registered handlers, * and refreshing unsatisfied interests. * * This class attempts to notice when a ccnd has died and to reconnect to a ccnd when it is restarted. * * It also handles the low level output "tap" functionality - this allows inspection or logging of * all the communications with ccnd. * * Starts a separate thread to listen to, decode and handle incoming data from ccnd. */ public class CCNNetworkManager implements Runnable { public static final int DEFAULT_AGENT_PORT = 64206; public static final String DEFAULT_AGENT_HOST = "localhost"; public static final String PROP_AGENT_PORT = "ccn.agent.port"; public static final String PROP_AGENT_HOST = "ccn.agent.host"; public static final String PROP_TAP = "ccn.tap"; public static final String ENV_TAP = "CCN_TAP"; // match C library public static final int MAX_PAYLOAD = 8800; // number of bytes in UDP payload public static final int SOCKET_TIMEOUT = 1000; // period to wait in ms. public static final int PERIOD = 2000; // period for occasional ops in ms. public static final int HEARTBEAT_PERIOD = 3500; public static final int MAX_PERIOD = PERIOD * 8; public static final String KEEPALIVE_NAME = "/HereIAm"; public static final int THREAD_LIFE = 8; // in seconds /* * Static singleton. */ protected Thread _thread = null; // the main processing thread protected ThreadPoolExecutor _threadpool = null; // pool service for callback threads protected DatagramChannel _channel = null; // for use by run thread only! protected Selector _selector = null; protected Throwable _error = null; // Marks error state of socket protected boolean _run = true; protected KeyManager _keyManager; protected ContentObject _keepalive; protected FileOutputStream _tapStreamOut = null; protected FileOutputStream _tapStreamIn = null; protected long _lastHeartbeat = 0; protected int _port = DEFAULT_AGENT_PORT; protected String _host = DEFAULT_AGENT_HOST; // Tables of interests/filters: users must synchronize on collection protected InterestTable<InterestRegistration> _myInterests = new InterestTable<InterestRegistration>(); protected InterestTable<Filter> _myFilters = new InterestTable<Filter>(); private Timer _periodicTimer = null; private boolean _timersSetup = false; /** * Do scheduled writes of heartbeats and interest refreshes */ private class PeriodicWriter extends TimerTask { // TODO Interest refresh time is supposed to "decay" over time but there are currently // unresolved problems with this. public void run() { long ourTime = new Date().getTime(); if ((ourTime - _lastHeartbeat) > HEARTBEAT_PERIOD) { _lastHeartbeat = ourTime; heartbeat(); } // Library.finest("Refreshing interests (size " + _myInterests.size() + ")"); // Re-express interests that need to be re-expressed try { synchronized (_myInterests) { for (Entry<InterestRegistration> entry : _myInterests.values()) { InterestRegistration reg = entry.value(); if (ourTime > reg.nextRefresh) { Log.finer("Refresh interest: {0}", reg.interest); // Temporarily back out refresh period decay //reg.nextRefreshPeriod = (reg.nextRefreshPeriod * 2) > MAX_PERIOD ? MAX_PERIOD //: reg.nextRefreshPeriod * 2; reg.nextRefresh += reg.nextRefreshPeriod; try { write(reg.interest); } catch (NotYetConnectedException nyce) {} } } } } catch (XMLStreamException xmlex) { Log.severe("Processing thread failure (Malformed datagram): {0}", xmlex.getMessage()); Log.warningStackTrace(xmlex); } _periodicTimer.schedule(new PeriodicWriter(), PERIOD); } } /** * Send the heartbeat. Also attempt to detect ccnd going down. */ private void heartbeat() { try { ByteBuffer heartbeat = ByteBuffer.allocate(1); if (_channel.isConnected()) _channel.write(heartbeat); } catch (IOException io) { // We do not see errors on send typically even if // agent is gone, so log each but do not track Log.warning("Error sending heartbeat packet: {0}", io.getMessage()); try { if (_channel.isConnected()) _channel.disconnect(); } catch (IOException e) {} } } /** * First time startup of timing stuff after first registration * We don't bother to "unstartup" if everything is deregistered */ private void setupTimers() { if (!_timersSetup) { _timersSetup = true; heartbeat(); // Create timer for heartbeats and other periodic behavior _periodicTimer = new Timer(true); _periodicTimer.schedule(new PeriodicWriter(), PERIOD); } } /** Generic superclass for registration objects that may have a listener * Handles invalidation and pending delivery consistently to enable * subclass to call listener callback without holding any library locks, * yet avoid delivery to a cancelled listener. */ protected abstract class ListenerRegistration implements Runnable { protected Object listener; protected CCNNetworkManager manager; public Semaphore sema = null; //used to block thread waiting for data or null if none public Object owner = null; protected boolean deliveryPending = false; protected long id; public abstract void deliver(); /** * This is called when removing interest or content handlers. It's purpose * is to insure that once the remove call begins it completes atomically without more * handlers being triggered. */ public void invalidate() { // There may be a pending delivery in progress, and it doesn't // happen while holding this lock because that would give the // application callback code power to block library processing. // Instead, we use a flag that is checked and set under this lock // to be sure that on exit from invalidate() there will be // no future deliveries based on the now-invalid registration. while (true) { synchronized (this) { // Make invalid, this will prevent any new delivery that comes // along from doing anything. this.listener = null; this.sema = null; // Return only if no delivery is in progress now (or if we are // called out of our own handler) if (!deliveryPending || (Thread.currentThread().getId() == id)) { return; } } Thread.yield(); } } /** * Calls the client handler */ public void run() { id = Thread.currentThread().getId(); synchronized (this) { // Mark us pending delivery, so that any invalidate() that comes // along will not return until delivery has finished this.deliveryPending = true; } try { // Delivery may synchronize on this object to access data structures // but should hold no locks when calling the listener deliver(); } catch (Exception ex) { Log.warning("failed delivery: {0}", ex); } finally { synchronized(this) { this.deliveryPending = false; } } } /** Equality based on listener if present, so multiple objects can * have the same interest registered without colliding */ public boolean equals(Object obj) { if (obj instanceof ListenerRegistration) { ListenerRegistration other = (ListenerRegistration)obj; if (this.owner == other.owner) { if (null == this.listener && null == other.listener){ return super.equals(obj); } else if (null != this.listener && null != other.listener) { return this.listener.equals(other.listener); } } } return false; } public int hashCode() { if (null != this.listener) { if (null != owner) { return owner.hashCode() + this.listener.hashCode(); } else { return this.listener.hashCode(); } } else { return super.hashCode(); } } } /** * Record of Interest * listener must be set (non-null) for cases of standing Interest that holds * until canceled by the application. The listener should be null when a * thread is blocked waiting for data, in which case the thread will be * blocked on semaphore. */ protected class InterestRegistration extends ListenerRegistration { public final Interest interest; protected ArrayList<ContentObject> data = new ArrayList<ContentObject>(1); //data for waiting thread protected long nextRefresh; // next time to refresh the interest protected long nextRefreshPeriod = PERIOD * 2; // period to wait before refresh // All internal client interests must have an owner public InterestRegistration(CCNNetworkManager mgr, Interest i, CCNInterestListener l, Object owner) { manager = mgr; interest = i; listener = l; this.owner = owner; if (null == listener) { sema = new Semaphore(0); } nextRefresh = new Date().getTime() + nextRefreshPeriod; } /** * Return true if data was added */ public synchronized boolean add(ContentObject obj) { // Add a copy of data, not the original data object, so that // the recipient cannot disturb the buffers of the sender // We need this even when data comes from network, since receive // buffer will be reused while recipient thread may proceed to read // from buffer it is handed boolean hasData = (null == data); if (!hasData) this.data.add(obj.clone()); return !hasData; } /** * This used to be called just data, but its similarity * to a simple accessor made the fact that it cleared the data * really confusing and error-prone... * Pull the available data out for processing. * @return */ public synchronized ArrayList<ContentObject> popData() { ArrayList<ContentObject> result = this.data; this.data = new ArrayList<ContentObject>(1); return result; } /** * Deliver content to a registered handler */ public void deliver() { try { if (null != this.listener) { // Standing interest: call listener callback ArrayList<ContentObject> results = null; CCNInterestListener listener = null; synchronized (this) { if (this.data.size() > 0) { results = this.data; this.data = new ArrayList<ContentObject>(1); listener = (CCNInterestListener)this.listener; } } // Call into client code without holding any library locks if (null != results) { Log.finer("Interest callback (" + results.size() + " data) for: {0}", this.interest.name()); synchronized (this) { // DKS -- dynamic interests, unregister the interest here and express new one if we have one // previous interest is final, can't update it this.deliveryPending = false; } manager.unregisterInterest(this); // paul r. note - contract says interest will be gone after the call into user's code. // Eventually this may be modified for "pipelining". // DKS TODO tension here -- what object does client use to cancel? // Original implementation had expressInterest return a descriptor // used to cancel it, perhaps we should go back to that. Otherwise // we may need to remember at least the original interest for cancellation, // or a fingerprint representation that doesn't include the exclude filter. // DKS even more interesting -- how do we update our interest? Do we? // it's final now to avoid contention, but need to change it or change // the registration. Interest updatedInterest = listener.handleContent(results, interest); // Possibly we should optimize here for the case where the same interest is returned back // (now we would unregister it, then reregister it) but need to be careful that the timing // behavior is right if we do that if (null != updatedInterest) { Log.finer("Interest callback: updated interest to express: {0}", updatedInterest.name()); // luckily we saved the listener // if we want to cancel this one before we get any data, we need to remember the // updated interest in the listener manager.expressInterest(this.owner, updatedInterest, listener); } } else { Log.finer("Interest callback skipped (no data) for: {0}", this.interest.name()); } } else { synchronized (this) { if (null != this.sema) { Log.finer("Data consumes pending get: {0}", this.interest.name()); // Waiting thread will pickup data -- wake it up // If this interest came from net or waiting thread timed out, // then no thread will be waiting but no harm is done Log.finest("releasing {0}", this.sema); this.sema.release(); } } if (null == this.sema) { // this is no longer valid registration Log.finer("Interest callback skipped (not valid) for: {0}", this.interest.name()); } } } catch (Exception ex) { Log.warning("failed to deliver data: {0}", ex); Log.warningStackTrace(ex); } } /** * Start a thread to deliver data to a registered handler */ public void run() { synchronized (this) { // For now only one piece of data may be delivered per InterestRegistration // This might change when "pipelining" is implemented if (deliveryPending) return; } super.run(); } } /** * Record of a filter describing portion of namespace for which this * application can respond to interests. Used to deliver incoming interests * to registered interest handlers */ protected class Filter extends ListenerRegistration { public ContentName name; protected boolean deliveryPending = false; protected ArrayList<Interest> interests= new ArrayList<Interest>(1); public Filter(CCNNetworkManager mgr, ContentName n, CCNFilterListener l, Object o) { name = n; listener = l; owner = o; manager = mgr; } public synchronized void add(Interest i) { interests.add(i); } /** * Deliver interest to a registered handler */ public void deliver() { try { ArrayList<Interest> results = null; CCNFilterListener listener = null; synchronized (this) { if (this.interests.size() > 0) { results = interests; interests = new ArrayList<Interest>(1); listener = (CCNFilterListener)this.listener; } } if (null != results) { // Call into client code without holding any library locks Log.finer("Filter callback (" + results.size() + " interests) for: {0}", name); listener.handleInterests(results); } else { Log.finer("Filter callback skipped (no interests) for: {0}", name); } } catch (RuntimeException ex) { Log.warning("failed to deliver interest: {0}", ex); } } @Override public String toString() { return name.toString(); } } /** * The constructor. Attempts to connect to a ccnd at the currently specified port number * @throws IOException if the port is invalid */ public CCNNetworkManager() throws IOException { // Determine port at which to contact agent String portval = System.getProperty(PROP_AGENT_PORT); if (null != portval) { try { _port = new Integer(portval); } catch (Exception ex) { throw new IOException("Invalid port '" + portval + "' specified in " + PROP_AGENT_PORT); } Log.warning("Non-standard CCN agent port " + _port + " per property " + PROP_AGENT_PORT); } String hostval = System.getProperty(PROP_AGENT_HOST); if (null != hostval && hostval.length() > 0) { _host = hostval; Log.warning("Non-standard CCN agent host " + _host + " per property " + PROP_AGENT_HOST); } Log.info("Contacting CCN agent at " + _host + ":" + _port); String tapname = System.getProperty(PROP_TAP); if (null == tapname) { tapname = System.getenv(ENV_TAP); } if (null != tapname) { long msecs = new Date().getTime(); long secs = msecs/1000; msecs = msecs % 1000; String unique_tapname = tapname + "-T" + Thread.currentThread().getId() + "-" + secs + "-" + msecs; setTap(unique_tapname); } // Socket is to belong exclusively to run thread started here _channel = DatagramChannel.open(); _channel.connect(new InetSocketAddress(_host, _port)); _channel.configureBlocking(false); _selector = Selector.open(); _channel.register(_selector, SelectionKey.OP_READ); // Create callback threadpool and main processing thread _threadpool = (ThreadPoolExecutor)Executors.newCachedThreadPool(); _threadpool.setKeepAliveTime(THREAD_LIFE, TimeUnit.SECONDS); _thread = new Thread(this); _thread.start(); } /** * Shutdown the connection to ccnd and all threads associated with this network manager */ public void shutdown() { Log.info("Shutdown requested"); _run = false; if (_periodicTimer != null) _periodicTimer.cancel(); _selector.wakeup(); try { setTap(null); _channel.close(); } catch (IOException io) { // Ignore since we're shutting down } } /** * Turns on writing of all packets to a file for test/debug * Overrides any previous setTap or environment/property setting. * Pass null to turn off tap. * @param pathname name of tap file */ public void setTap(String pathname) throws IOException { // Turn off any active tap if (null != _tapStreamOut) { FileOutputStream closingStream = _tapStreamOut; _tapStreamOut = null; closingStream.close(); } if (null != _tapStreamIn) { FileOutputStream closingStream = _tapStreamIn; _tapStreamIn = null; closingStream.close(); } if (pathname != null && pathname.length() > 0) { _tapStreamOut = new FileOutputStream(new File(pathname + "_out")); _tapStreamIn = new FileOutputStream(new File(pathname + "_in")); Log.info("Tap writing to {0}", pathname); } } /** * Write content to ccnd * * @param co the content * @return the same content that was passed into the method * * TODO - code doesn't actually throw either of these exceptions but need to fix upper * level code to compensate when they are removed. * @throws IOException * @throws InterruptedException */ public ContentObject put(ContentObject co) throws IOException, InterruptedException { try { write(co); } catch (XMLStreamException e) { Log.warning("Exception in lowest-level put for object {1}! {1}", co.name(), e); } return co; } /** * get content matching an interest from ccnd. Expresses an interest, waits for ccnd to * return matching the data, then removes the interest and returns the data to the caller. * * TODO should probably handle InterruptedException at this level instead of throwing it to * higher levels * * @param interest the interest * @param timeout time to wait for return in ms * @return ContentObject or null on timeout * @throws IOException on incorrect interest data * @throws InterruptedException if process is interrupted during wait */ public ContentObject get(Interest interest, long timeout) throws IOException, InterruptedException { Log.fine("get: {0}", interest); InterestRegistration reg = new InterestRegistration(this, interest, null, null); expressInterest(reg); Log.finest("blocking for {0} on {1}", interest.name(), reg.sema); // Await data to consume the interest if (timeout == CCNBase.NO_TIMEOUT) reg.sema.acquire(); // currently no timeouts else reg.sema.tryAcquire(timeout, TimeUnit.MILLISECONDS); Log.finest("unblocked for {0} on {1}", interest.name(), reg.sema); // Typically the main processing thread will have registered the interest // which must be undone here, but no harm if never registered unregisterInterest(reg); ArrayList<ContentObject> result = reg.popData(); return result.size() > 0 ? result.get(0) : null; } /** * We express interests to the ccnd and register them within the network manager * * @param caller must not be null * @param interest the interest * @param callbackListener listener to callback on receipt of data * @throws IOException on incorrect interest */ public void expressInterest( Object caller, Interest interest, CCNInterestListener callbackListener) throws IOException { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. if (null == callbackListener) { throw new NullPointerException("expressInterest: callbackListener cannot be null"); } Log.fine("expressInterest: {0}", interest); InterestRegistration reg = new InterestRegistration(this, interest, callbackListener, caller); expressInterest(reg); } private void expressInterest(InterestRegistration reg) throws IOException { try { registerInterest(reg); write(reg.interest); } catch (XMLStreamException e) { unregisterInterest(reg); throw new IOException(e.getMessage()); } } /** * Cancel this query with all the repositories we sent * it to. * * @param caller must not be null * @param interest * @param callbackListener */ public void cancelInterest(Object caller, Interest interest, CCNInterestListener callbackListener) { if (null == callbackListener) { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. throw new NullPointerException("cancelInterest: callbackListener cannot be null"); } Log.fine("cancelInterest: {0}", interest.name()); // Remove interest from repeated presentation to the network. unregisterInterest(caller, interest, callbackListener); } /** * Register a standing interest filter with callback to receive any * matching interests seen. Any interests whose prefix completely matches "filter" will * be delivered to the listener * * @param caller must not be null * @param filter ContentName containing prefix of interests to match * @param callbackListener a CCNFilterListener */ public void setInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener) { Log.fine("setInterestFilter: {0}", filter); // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. setupTimers(); synchronized (_myFilters) { _myFilters.add(filter, new Filter(this, filter, callbackListener, caller)); } } /** * Unregister a standing interest filter * * @param caller must not be null * @param filter currently registered filter * @param callbackListener the CCNFilterListener registered to it */ public void cancelInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener) { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. Log.fine("cancelInterestFilter: {0}", filter); synchronized (_myFilters) { Entry<Filter> found = _myFilters.remove(filter, new Filter(this, filter, callbackListener, caller)); if (null != found) { found.value().invalidate(); } } } protected void write(ContentObject data) throws XMLStreamException { WirePacket packet = new WirePacket(data); writeInner(packet); Log.finest("Wrote content object: {0}", data.name()); } protected void write(Interest interest) throws XMLStreamException { WirePacket packet = new WirePacket(interest); writeInner(packet); } private void writeInner(WirePacket packet) throws XMLStreamException { try { byte[] bytes = packet.encode(); ByteBuffer datagram = ByteBuffer.wrap(bytes); synchronized (_channel) { int result = _channel.write(datagram); Log.finest("Wrote datagram (" + datagram.position() + " bytes, result " + result + ")"); if (null != _tapStreamOut) { try { _tapStreamOut.write(bytes); } catch (IOException io) { Log.warning("Unable to write packet to tap stream for debugging"); } } } } catch (IOException io) { // We do not see errors on send typically even if // agent is gone, so log each but do not track Log.warning("Error sending packet: " + io.toString()); } } /** * Pass things on to the network stack. */ private InterestRegistration registerInterest(InterestRegistration reg) { // Add to standing interests table setupTimers(); Log.finest("registerInterest for {0}, and obj is " + _myInterests.hashCode(), reg.interest.name()); synchronized (_myInterests) { _myInterests.add(reg.interest, reg); } return reg; } private void unregisterInterest(Object caller, Interest interest, CCNInterestListener callbackListener) { InterestRegistration reg = new InterestRegistration(this, interest, callbackListener, caller); unregisterInterest(reg); } /** * @param reg - registration to unregister * * Important Note: This can indirectly need to obtain the lock for "reg" with the lock on * "myInterests" held. Therefore it can't be called when holding the lock for "reg". */ private void unregisterInterest(InterestRegistration reg) { synchronized (_myInterests) { Entry<InterestRegistration> found = _myInterests.remove(reg.interest, reg); if (null != found) { found.value().invalidate(); } } } /** * Thread method: this thread will handle reading datagrams and * the periodic re-expressing of standing interests */ public void run() { if (! _run) { Log.warning("CCNSimpleNetworkManager run() called after shutdown"); return; } // Allocate datagram buffer: want to wrap array to ensure backed by // array to permit decoding byte[] buffer = new byte[MAX_PAYLOAD]; ByteBuffer datagram = ByteBuffer.wrap(buffer); WirePacket packet = new WirePacket(); Log.info("CCNSimpleNetworkManager processing thread started"); while (_run) { try { try { if (_selector.select(SOCKET_TIMEOUT) != 0) { // Note: we're selecting on only one channel to get // the ability to use wakeup, so there is no need to // inspect the selected-key set datagram.clear(); // make ready for new read synchronized (_channel) { _channel.read(datagram); // queue readers and writers } Log.finest("Read datagram (" + datagram.position() + " bytes)"); _selector.selectedKeys().clear(); if (null != _error) { Log.info("Receive error cleared"); _error = null; } datagram.flip(); // make ready to decode if (null != _tapStreamIn) { byte [] b = new byte[datagram.limit()]; datagram.get(b); _tapStreamIn.write(b); datagram.rewind(); } packet.clear(); packet.decode(datagram); } else { // This was a timeout or wakeup, no data packet.clear(); if (!_run) { // exit immediately if wakeup for shutdown break; } if (!_channel.isConnected()) { _channel.connect(new InetSocketAddress(_host, _port)); if (_channel.isConnected()) { _selector = Selector.open(); _channel.register(_selector, SelectionKey.OP_READ); } } } } catch (IOException io) { // We see IOException on receive every time if agent is gone // so track it to log only start and end of outages if (null == _error) { Log.info("Unable to receive from agent: is it still running?"); } _error = io; packet.clear(); } if (!_run) { // exit immediately if wakeup for shutdown break; } // If we got a data packet, hand it back to all the interested // parties (registered interests and getters). for (ContentObject co : packet.data()) { Log.fine("Data from net: {0}", co.name()); // SystemConfiguration.logObject("Data from net:", co); deliverData(co); // External data never goes back to network, never held onto here // External data never has a thread waiting, so no need to release sema } for (Interest interest : packet.interests()) { Log.fine("Interest from net: {0}", interest); InterestRegistration oInterest = new InterestRegistration(this, interest, null, null); deliverInterest(oInterest); // External interests never go back to network } // for interests } catch (Exception ex) { Log.severe("Processing thread failure (UNKNOWN): " + ex.getMessage()); Log.warningStackTrace(ex); } } _threadpool.shutdown(); Log.info("Shutdown complete"); } /** * Internal delivery of interests to pending filter listeners * @param ireg * @throws XMLStreamException */ protected void deliverInterest(InterestRegistration ireg) throws XMLStreamException { // Call any listeners with matching filters synchronized (_myFilters) { for (Filter filter : _myFilters.getValues(ireg.interest.name())) { if (filter.owner != ireg.owner) { Log.finer("Schedule delivery for interest: {0}", ireg.interest); filter.add(ireg.interest); _threadpool.execute(filter); } } } } /** * Deliver data to blocked getters and registered interests * @param co * @throws XMLStreamException */ protected void deliverData(ContentObject co) throws XMLStreamException { synchronized (_myInterests) { for (InterestRegistration ireg : _myInterests.getValues(co)) { if (ireg.add(co)) { // this is a copy of the data _threadpool.execute(ireg); } } } } }
package com.github.monee1988.mybatis.entity; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * ORM. * @author monee1988 * @param <T> Page. */ public class Page<T> implements Serializable{ public static final String ASC = "ASC"; public static final String DESC = "DESC"; public static final int DEFAULT_PAGESIZE =20; public static final int DEFAULT_PAGE_NO= 1; protected int pageNo = 1; protected int pageSize = -1; // protected String orderBy = null; // protected String order = null; // protected boolean autoCount = true; private int startPageIndex; private int endPageIndex; private int pageCount; /** * page */ private Map<String, Object> extend; private List<T> list = new ArrayList<>(); private long totalCount = 0; /** * sql */ private String sql; public Page() { } public Page<T> end() { pageCount = ((int) this.totalCount + pageSize - 1) / pageSize; // 2, startPageIndexendPageIndex // a, 10 if (pageCount <= 10) { startPageIndex = 1; endPageIndex = pageCount; } // b, 10 else { startPageIndex = pageNo - 4; endPageIndex = pageNo + 5; // 410 if (startPageIndex < 1) { startPageIndex = 1; endPageIndex = 10; } // 510 else if (endPageIndex > pageCount) { endPageIndex = pageCount; startPageIndex = pageCount - 10 + 1; } } return this; } public Page(int pageSize) { this.pageSize = pageSize; } public Page(int pageNo, int pageSize) { this.pageNo = pageNo; this.pageSize = pageSize; } public Page(int pageNo, int pageSize, int totalCount) { this.pageNo = pageNo; this.pageSize = pageSize; this.totalCount = totalCount; } /** * * @param request requset */ public Page(HttpServletRequest request) { request.getParameterMap(); String pageNo = request.getParameter("pageNo"); String pageSize = request.getParameter("pageSize"); if (!StringUtils.isBlank(pageNo)) { this.pageNo = Integer.valueOf(pageNo); }else{ this.pageNo = DEFAULT_PAGE_NO; } if (!StringUtils.isBlank(pageSize)) { this.pageSize = Integer.valueOf(pageSize); }else{ this.pageSize = DEFAULT_PAGESIZE; } } /** * PagesetPageNo, */ public Page<T> pageNo(int pageNo) { setPageNo(pageNo); return this; } /** * PagesetPageSize, */ public Page<T> pageSize(int pageSize) { setPageSize(pageSize); return this; } public int getPageNo() { if(pageNo > getTotalPages()){ setPageNo(Long.valueOf(getTotalPages()).intValue()); } if(pageNo <= 0){ setPageNo(DEFAULT_PAGE_NO); } return this.pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; if (pageNo < DEFAULT_PAGE_NO) { this.pageNo = DEFAULT_PAGE_NO; } if(pageNo > getTotalPages()){ this.pageNo = Long.valueOf(getTotalPages()).intValue(); } } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } /** * pageNopageSize1. */ public int getFirst() { return ((pageNo - 1) * pageSize) + 1; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } public long getTotalCount() { return totalCount; } public void setTotalCount(long totalCount) { this.totalCount = totalCount; } /** * pageSizetotalCount. */ public long getTotalPages() { if (totalCount < 0) { return -1; } long count = totalCount / pageSize; if (totalCount % pageSize > 0) { count++; } return count; } public boolean isHasNext() { return (pageNo + 1 <= getTotalPages()); } public int getNextPage() { if (isHasNext()) { return pageNo + 1; } else { return pageNo; } } public boolean isHasPre() { return (pageNo - 1 >= 1); } public int getPrePage() { if (isHasPre()) { return pageNo - 1; } else { return pageNo; } } /** * Mysql,Hibernate. */ public int getOffset() { return ((getPageNo() - 1) * pageSize); } /** * Oracle. */ public int getStartRow() { return getOffset() + 1; } /** * Oracle. */ public int getEndRow() { return pageSize * pageNo; } public int getStartPageIndex() { return startPageIndex; } public void setStartPageIndex(int startPageIndex) { this.startPageIndex = startPageIndex; } public int getEndPageIndex() { return endPageIndex; } public void setEndPageIndex(int endPageIndex) { this.endPageIndex = endPageIndex; } public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public Map<String, Object> getExtend() { return extend; } public void setExtend(Map<String, Object> extend) { this.extend = extend; } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } }
package com.github.niwaniwa.we.core; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import com.github.niwaniwa.we.core.api.WhiteEggAPI; import com.github.niwaniwa.we.core.command.WhiteEggCoreCommandHandler; import com.github.niwaniwa.we.core.command.WhiteEggHeadCommand; import com.github.niwaniwa.we.core.command.WhiteEggReplayCommand; import com.github.niwaniwa.we.core.command.WhiteEggScriptCommand; import com.github.niwaniwa.we.core.command.WhiteEggWhisperCommand; import com.github.niwaniwa.we.core.command.abstracts.AbstractWhiteEggCoreCommand; import com.github.niwaniwa.we.core.command.core.WhiteEggCoreCommand; import com.github.niwaniwa.we.core.command.toggle.WhiteEggToggleCommand; import com.github.niwaniwa.we.core.command.twitter.WhiteEggTwitterCommand; import com.github.niwaniwa.we.core.command.twitter.WhiteEggTwitterRegisterCommand; import com.github.niwaniwa.we.core.config.WhiteEggCoreConfig; import com.github.niwaniwa.we.core.listener.PlayerListener; import com.github.niwaniwa.we.core.listener.ScriptListener; import com.github.niwaniwa.we.core.player.WhitePlayerFactory; import com.github.niwaniwa.we.core.player.commad.WhiteCommandSender; import com.github.niwaniwa.we.core.player.commad.WhiteConsoleSender; import com.github.niwaniwa.we.core.player.rank.Rank; import com.github.niwaniwa.we.core.script.JavaScript; import com.github.niwaniwa.we.core.util.Util; import com.github.niwaniwa.we.core.util.Versioning; import com.github.niwaniwa.we.core.util.message.LanguageType; import com.github.niwaniwa.we.core.util.message.MessageManager; /** * * @author niwaniwa * @version 2.0.0 */ public class WhiteEggCore extends JavaPlugin { private static WhiteEggCore instance; private static WhiteEggAPI api = WhiteEggAPI.getAPI(); private static MessageManager msg; private static LanguageType type = LanguageType.en_US;; private static WhiteEggCoreConfig config; private PluginManager pm = Bukkit.getPluginManager(); private JavaScript script; public static final String logPrefix = "[WhiteEggCore]"; public static final String msgPrefix = "§7[§bWhiteEggCore§7]§r"; public static Logger logger; public static Versioning version; @Override public void onLoad() { logger = this.getLogger(); logger.info("Checking version...."); version = Versioning.getInstance(); } @Override public void onEnable(){ this.versionCheck(); if (!version.isSupport()) { return; } long time = System.nanoTime(); this.init(); long finish = (System.nanoTime() - time); logger.info(String.format("Done : %.3f s", new Object[] { Double.valueOf(finish / 1.0E9D) })); } @Override public void onDisable(){ if (!version.isSupport()) { return; } WhitePlayerFactory.saveAll(); Rank.saveAll(); } /** * instance * @return */ public static WhiteEggCore getInstance(){ return instance; } /** * API * @return API */ public static WhiteEggAPI getAPI(){ return api; } /** * * @return */ public static MessageManager getMessageManager(){ return msg; } /** * * @return */ public static LanguageType getType() { return type; } /** * * @return */ public static WhiteEggCoreConfig getConf(){ return config; } private void init(){ instance = this; msg = new MessageManager(this.getDataFolder() + File.pathSeparator +"lang" + File.pathSeparator); this.setting(); } private void setting(){ this.loadConfig(); this.register(); this.registerCommands(); this.registerListener(); this.settingLanguage(); this.load(); this.settingCheck(); this.runTask(); } private void loadConfig(){ saveDefaultConfig(); config = new WhiteEggCoreConfig(); config.load(); } private void settingCheck(){ if(config.getConfig().getString("setting.twitter.consumerKey", "").isEmpty() || config.getConfig().getString("setting.twitter.consumerSecret", "").isEmpty()){ logger.warning("Twitter Consumer key or Consumer Secret is empty"); logger.warning("Twitter command disable"); config.getConfig().set("setting.twitter.useTwitter", false); } } private void load(){ WhitePlayerFactory.load(); Rank.load(); } /** * command */ @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { WhiteCommandSender whiteCommandSender; if(sender instanceof Player){ whiteCommandSender = WhitePlayerFactory.newInstance((Player) sender); } else { whiteCommandSender = new WhiteConsoleSender(true); } return WhiteEggCoreCommandHandler.onCommand(whiteCommandSender, command, label, args); } private void registerListener(){ // pm.registerEvents(new Debug(), this); pm.registerEvents(new PlayerListener(), this); new ScriptListener(); } private void registerCommands(){ if(!config.getConfig().getBoolean("setting.enableCommands", true)){ return; } WhiteEggCoreCommandHandler handler = new WhiteEggCoreCommandHandler(); handler.registerCommand("whiteeggcore", new WhiteEggCoreCommand()); handler.registerCommand("toggle", new WhiteEggToggleCommand()); handler.registerCommand("head", new WhiteEggHeadCommand()); handler.registerCommand("register", new WhiteEggTwitterRegisterCommand()); handler.registerCommand("whisper", new WhiteEggWhisperCommand()); handler.registerCommand("replay", new WhiteEggReplayCommand()); handler.registerCommand("script", new WhiteEggScriptCommand()); if(config.getConfig().getBoolean("setting.twitter.useTwitter", false)){ handler.registerCommand("tweet", new WhiteEggTwitterCommand()); } } private void runTask(){ final int run = config.getConfig().getInt("setting.autoSave.time", 300000); new BukkitRunnable() { @Override public void run() { if(!config.getConfig().getBoolean("setting.autoSave.enable", false)){ this.cancel(); } WhitePlayerFactory.saveAll(); } }.runTaskTimerAsynchronously(instance, run, run); } private void settingLanguage(){ this.copyLangFiles(false); try { msg.loadLangFile(); } catch (IOException | InvalidConfigurationException e) {} msg.replaceDefaultLanguage(true); if(!msg.getLangs().isEmpty()){ return; } this.load(msg, LanguageType.ja_JP); } /** * * @param msg * @param type {@link LanguageType} */ private void load(MessageManager msg, LanguageType type){ BufferedReader buffer = null; try { InputStreamReader reader = new InputStreamReader( this.getClass().getClassLoader() .getResourceAsStream( "lang/" + type.getString() +".yml"), StandardCharsets.UTF_8); buffer = new BufferedReader(reader); msg.loadLangFile(type, buffer); } catch (InvalidConfigurationException | IOException e) { } finally { try{ if(buffer != null){ buffer.close(); } } catch (IOException e){} } } private void register(){ if(config.getConfig().getBoolean("setting.enablecCommands")) try { JavaScript.copyScript(); } catch (IOException e) { e.printStackTrace(); } script = JavaScript.loadScript(); } private void versionCheck(){ if(version.getJavaVersion() <= 1.7){ logger.warning("Unsupported Java Version >_< : " + version.getJavaVersion()); logger.warning("Please use 1.8"); pm.disablePlugin(instance); return; } if(!version.getCraftBukkitVersion().equalsIgnoreCase("v1_8_R3")){ logger.warning("Unsupported CraftBukkit Version >_< : " + version); logger.warning("Please use v1_8_R3"); pm.disablePlugin(instance); return; } return; } /** * * @param send */ private void copyLangFiles(boolean send){ for(LanguageType type : LanguageType.values()){ File path = new File(WhiteEggCore.getInstance().getDataFolder() + File.separator + "lang" + File.separator + type.getString() + ".yml"); if(path.exists()){ continue; } if(send){ logger.info(" " + type.getString() + " : loading now..."); } Util.copyFileFromJar(new File(WhiteEggCore.getInstance().getDataFolder() + "/lang/"), WhiteEggCore.getInstance().getFile(), "lang/" + type.getString() + ".yml"); if(send){ logger.info(" " + type.getString() + " : " + (path.exists() ? "complete" : "failure")); } } } /** * JarFile */ @Override public File getFile() { return super.getFile(); } /** * * @return Map */ public Map<String, AbstractWhiteEggCoreCommand> getCommands(){ return WhiteEggCoreCommandHandler.getCommans(); } public JavaScript getScript() { return script; } public void setScript(JavaScript s){ this.script = s; } }
/* * $Log$ * Revision 1.5 2000/09/01 16:34:53 apr * Accept "yes" as "true" response for getBoolean * * Revision 1.4 2000/03/01 14:44:38 apr * Changed package name to org.jpos * * Revision 1.3 1999/11/26 12:16:51 apr * CVS devel snapshot * * Revision 1.2 1999/11/11 10:18:49 apr * added get(name,name), getInt(name), getLong(name) and getDouble(name) * * Revision 1.1 1999/09/26 22:32:01 apr * CVS sync * */ package org.jpos.core; import java.io.*; import java.util.*; /** * @author apr@cs.com.uy * @version $Id$ * @since jPOS 1.1 */ public class SimpleConfiguration implements Configuration { private Properties props; public SimpleConfiguration () { props = new Properties(); } public SimpleConfiguration (Properties props) { this.props = props; } public SimpleConfiguration (String filename) throws FileNotFoundException, IOException { props = new Properties(); load (filename); } synchronized public String get (String name) { return props.getProperty (name, ""); } synchronized public String get (String name, String def) { return props.getProperty (name, def); } synchronized public int getInt (String name) { return Integer.parseInt(props.getProperty(name, "0").trim()); } synchronized public long getLong (String name) { return Long.parseLong(props.getProperty(name, "0").trim()); } synchronized public double getDouble(String name) { return Double.valueOf( props.getProperty(name,"0.00").trim()).doubleValue(); } public boolean getBoolean (String name) { String v = get (name, "false").trim(); return v.equalsIgnoreCase("true") || v.equalsIgnoreCase("yes"); } synchronized public void load(String filename) throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(filename); props.load(new BufferedInputStream(fis)); fis.close(); } }
package refinedstorage.tile.grid; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.*; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.wrapper.InvWrapper; import refinedstorage.RefinedStorage; import refinedstorage.RefinedStorageBlocks; import refinedstorage.RefinedStorageItems; import refinedstorage.RefinedStorageUtils; import refinedstorage.api.network.IGridHandler; import refinedstorage.block.BlockGrid; import refinedstorage.block.EnumGridType; import refinedstorage.container.ContainerGrid; import refinedstorage.inventory.BasicItemHandler; import refinedstorage.inventory.BasicItemValidator; import refinedstorage.item.ItemPattern; import refinedstorage.network.MessageGridSettingsUpdate; import refinedstorage.tile.TileSlave; import refinedstorage.tile.config.IRedstoneModeConfig; import java.util.ArrayList; import java.util.List; public class TileGrid extends TileSlave implements IGrid { public static final String NBT_SORTING_DIRECTION = "SortingDirection"; public static final String NBT_SORTING_TYPE = "SortingType"; public static final String NBT_SEARCH_BOX_MODE = "SearchBoxMode"; public static final int SORTING_DIRECTION_ASCENDING = 0; public static final int SORTING_DIRECTION_DESCENDING = 1; public static final int SORTING_TYPE_QUANTITY = 0; public static final int SORTING_TYPE_NAME = 1; public static final int SEARCH_BOX_MODE_NORMAL = 0; public static final int SEARCH_BOX_MODE_NORMAL_AUTOSELECTED = 1; public static final int SEARCH_BOX_MODE_JEI_SYNCHRONIZED = 2; public static final int SEARCH_BOX_MODE_JEI_SYNCHRONIZED_AUTOSELECTED = 3; private Container craftingContainer = new Container() { @Override public boolean canInteractWith(EntityPlayer player) { return false; } @Override public void onCraftMatrixChanged(IInventory inventory) { onCraftingMatrixChanged(); } }; private InventoryCrafting matrix = new InventoryCrafting(craftingContainer, 3, 3); private InventoryCraftResult result = new InventoryCraftResult(); private BasicItemHandler patterns = new BasicItemHandler(2, this, new BasicItemValidator(RefinedStorageItems.PATTERN)); private EnumGridType type; private int sortingDirection = SORTING_DIRECTION_DESCENDING; private int sortingType = SORTING_TYPE_NAME; private int searchBoxMode = SEARCH_BOX_MODE_NORMAL; // Used clientside only private List<ItemStack> items = new ArrayList<ItemStack>(); @Override public int getEnergyUsage() { switch (getType()) { case NORMAL: return 2; case CRAFTING: return 4; case PATTERN: return 3; default: return 0; } } @Override public void updateSlave() { } public EnumGridType getType() { if (type == null && worldObj.getBlockState(pos).getBlock() == RefinedStorageBlocks.GRID) { this.type = (EnumGridType) worldObj.getBlockState(pos).getValue(BlockGrid.TYPE); } return type == null ? EnumGridType.NORMAL : type; } @Override public List<ItemStack> getItems() { return items; } @Override public void setItems(List<ItemStack> items) { this.items = items; } @Override public BlockPos getNetworkPosition() { return network != null ? network.getPosition() : null; } public void onGridOpened(EntityPlayer player) { if (isConnected()) { network.updateItemsWithClient((EntityPlayerMP) player); } } @Override public IGridHandler getGridHandler() { return isConnected() ? network.getGridHandler() : null; } public InventoryCrafting getMatrix() { return matrix; } public InventoryCraftResult getResult() { return result; } public IItemHandler getPatterns() { return patterns; } public void onCraftingMatrixChanged() { markDirty(); result.setInventorySlotContents(0, CraftingManager.getInstance().findMatchingRecipe(matrix, worldObj)); } public void onCrafted() { ItemStack[] remainder = CraftingManager.getInstance().getRemainingItems(matrix, worldObj); for (int i = 0; i < matrix.getSizeInventory(); ++i) { if (i < remainder.length && remainder[i] != null) { matrix.setInventorySlotContents(i, remainder[i].copy()); } else { ItemStack slot = matrix.getStackInSlot(i); if (slot != null) { if (slot.stackSize == 1 && isConnected()) { matrix.setInventorySlotContents(i, RefinedStorageUtils.takeFromNetwork(network, slot, 1)); } else { matrix.decrStackSize(i, 1); } } } } onCraftingMatrixChanged(); } public void onCraftedShift(ContainerGrid container, EntityPlayer player) { List<ItemStack> craftedItemsList = new ArrayList<ItemStack>(); int craftedItems = 0; ItemStack crafted = result.getStackInSlot(0); while (true) { onCrafted(); craftedItemsList.add(crafted.copy()); craftedItems += crafted.stackSize; if (!RefinedStorageUtils.compareStack(crafted, result.getStackInSlot(0)) || craftedItems + crafted.stackSize > crafted.getMaxStackSize()) { break; } } for (ItemStack craftedItem : craftedItemsList) { if (!player.inventory.addItemStackToInventory(craftedItem.copy())) { InventoryHelper.spawnItemStack(player.worldObj, player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ(), craftedItem); } } container.sendCraftingSlots(); container.detectAndSendChanges(); } public void onCreatePattern() { if (canCreatePattern()) { patterns.extractItem(0, 1, false); ItemStack pattern = new ItemStack(RefinedStorageItems.PATTERN); for (ItemStack byproduct : CraftingManager.getInstance().getRemainingItems(matrix, worldObj)) { if (byproduct != null) { ItemPattern.addByproduct(pattern, byproduct); } } ItemPattern.addOutput(pattern, result.getStackInSlot(0)); ItemPattern.setProcessing(pattern, false); for (int i = 0; i < 9; ++i) { ItemStack ingredient = matrix.getStackInSlot(i); if (ingredient != null) { ItemPattern.addInput(pattern, ingredient); } } patterns.setStackInSlot(1, pattern); } } public boolean canCreatePattern() { return result.getStackInSlot(0) != null && patterns.getStackInSlot(1) == null && patterns.getStackInSlot(0) != null; } public void onRecipeTransfer(ItemStack[][] recipe) { if (isConnected()) { for (int i = 0; i < matrix.getSizeInventory(); ++i) { ItemStack slot = matrix.getStackInSlot(i); if (slot != null) { if (getType() == EnumGridType.CRAFTING) { if (network.push(slot, slot.stackSize, true) != null) { return; } else { network.push(slot, slot.stackSize, false); } } matrix.setInventorySlotContents(i, null); } } for (int i = 0; i < matrix.getSizeInventory(); ++i) { if (recipe[i] != null) { ItemStack[] possibilities = recipe[i]; if (getType() == EnumGridType.CRAFTING) { for (ItemStack possibility : possibilities) { ItemStack took = RefinedStorageUtils.takeFromNetwork(network, possibility, 1); if (took != null) { matrix.setInventorySlotContents(i, possibility); break; } } } else if (getType() == EnumGridType.PATTERN) { matrix.setInventorySlotContents(i, possibilities[0]); } } } } } public int getSortingDirection() { return sortingDirection; } public void setSortingDirection(int sortingDirection) { this.sortingDirection = sortingDirection; markDirty(); } public int getSortingType() { return sortingType; } public void setSortingType(int sortingType) { this.sortingType = sortingType; markDirty(); } public int getSearchBoxMode() { return searchBoxMode; } public void setSearchBoxMode(int searchBoxMode) { this.searchBoxMode = searchBoxMode; markDirty(); } @Override public void onSortingTypeChanged(int type) { RefinedStorage.NETWORK.sendToServer(new MessageGridSettingsUpdate(this, sortingDirection, type, searchBoxMode)); } @Override public void onSortingDirectionChanged(int direction) { RefinedStorage.NETWORK.sendToServer(new MessageGridSettingsUpdate(this, direction, sortingType, searchBoxMode)); } @Override public void onSearchBoxModeChanged(int searchBoxMode) { RefinedStorage.NETWORK.sendToServer(new MessageGridSettingsUpdate(this, sortingDirection, sortingType, searchBoxMode)); } @Override public IRedstoneModeConfig getRedstoneModeConfig() { return this; } @Override public void read(NBTTagCompound nbt) { super.read(nbt); RefinedStorageUtils.readItemsLegacy(matrix, 0, nbt); RefinedStorageUtils.readItems(patterns, 1, nbt); if (nbt.hasKey(NBT_SORTING_DIRECTION)) { sortingDirection = nbt.getInteger(NBT_SORTING_DIRECTION); } if (nbt.hasKey(NBT_SORTING_TYPE)) { sortingType = nbt.getInteger(NBT_SORTING_TYPE); } if (nbt.hasKey(NBT_SEARCH_BOX_MODE)) { searchBoxMode = nbt.getInteger(NBT_SEARCH_BOX_MODE); } } @Override public NBTTagCompound write(NBTTagCompound tag) { super.write(tag); RefinedStorageUtils.writeItemsLegacy(matrix, 0, tag); RefinedStorageUtils.writeItems(patterns, 1, tag); tag.setInteger(NBT_SORTING_DIRECTION, sortingDirection); tag.setInteger(NBT_SORTING_TYPE, sortingType); tag.setInteger(NBT_SEARCH_BOX_MODE, searchBoxMode); return tag; } @Override public void writeContainerData(ByteBuf buf) { super.writeContainerData(buf); buf.writeInt(sortingDirection); buf.writeInt(sortingType); buf.writeInt(searchBoxMode); } @Override public void readContainerData(ByteBuf buf) { super.readContainerData(buf); sortingDirection = buf.readInt(); sortingType = buf.readInt(); searchBoxMode = buf.readInt(); } @Override public Class<? extends Container> getContainer() { return ContainerGrid.class; } @Override public IItemHandler getDroppedItems() { switch (getType()) { case CRAFTING: return new InvWrapper(matrix); case PATTERN: return patterns; default: return null; } } public static boolean isValidSearchBoxMode(int mode) { return mode == SEARCH_BOX_MODE_NORMAL || mode == SEARCH_BOX_MODE_NORMAL_AUTOSELECTED || mode == SEARCH_BOX_MODE_JEI_SYNCHRONIZED || mode == SEARCH_BOX_MODE_JEI_SYNCHRONIZED_AUTOSELECTED; } public static boolean isSearchBoxModeWithAutoselection(int mode) { return mode == SEARCH_BOX_MODE_NORMAL_AUTOSELECTED || mode == TileGrid.SEARCH_BOX_MODE_JEI_SYNCHRONIZED_AUTOSELECTED; } public static boolean isValidSortingType(int type) { return type == SORTING_TYPE_QUANTITY || type == TileGrid.SORTING_TYPE_NAME; } public static boolean isValidSortingDirection(int direction) { return direction == SORTING_DIRECTION_ASCENDING || direction == SORTING_DIRECTION_DESCENDING; } }
package com.github.nkzawa.engineio.client; import com.github.nkzawa.emitter.Emitter; import com.github.nkzawa.engineio.client.transports.Polling; import com.github.nkzawa.engineio.client.transports.PollingXHR; import com.github.nkzawa.engineio.client.transports.WebSocket; import com.github.nkzawa.engineio.parser.Packet; import com.github.nkzawa.engineio.parser.Parser; import com.github.nkzawa.thread.EventThread; import org.json.JSONObject; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; public abstract class Socket extends Emitter { private static final Logger logger = Logger.getLogger(Socket.class.getName()); private enum ReadyState { OPENING, OPEN, CLOSING, CLOSED; @Override public String toString() { return super.toString().toLowerCase(); } } /** * Called on successful connection. */ public static final String EVENT_OPEN = "open"; /** * Called on disconnection. */ public static final String EVENT_CLOSE = "close"; /** * Called when data is received from the server. */ public static final String EVENT_MESSAGE = "message"; /** * Called when an error occurs. */ public static final String EVENT_ERROR = "error"; public static final String EVENT_UPGRADE_ERROR = "upgradeError"; /** * Called on completing a buffer flush. */ public static final String EVENT_FLUSH = "flush"; /** * Called after `drain` event of transport if writeBuffer is empty. */ public static final String EVENT_DRAIN = "drain"; public static final String EVENT_HANDSHAKE = "handshake"; public static final String EVENT_UPGRADING = "upgrading"; public static final String EVENT_UPGRADE = "upgrade"; public static final String EVENT_PACKET = "packet"; public static final String EVENT_PACKET_CREATE = "packetCreate"; public static final String EVENT_HEARTBEAT = "heartbeat"; public static final String EVENT_DATA = "data"; /** * Called on a new transport is created. */ public static final String EVENT_TRANSPORT = "transport"; private static final Runnable noop = new Runnable() { @Override public void run() {} }; /** * The protocol version. */ public static final int protocol = Parser.protocol; public static boolean priorWebsocketSuccess = false; private boolean secure; private boolean upgrade; private boolean timestampRequests; private boolean upgrading; private boolean rememberUpgrade; private int port; private int policyPort; private int prevBufferLen; private long pingInterval; private long pingTimeout; private String id; private String hostname; private String path; private String timestampParam; private List<String> transports; private List<String> upgrades; private Map<String, String> query; private LinkedList<Packet> writeBuffer = new LinkedList<Packet>(); private LinkedList<Runnable> callbackBuffer = new LinkedList<Runnable>(); /*package*/ Transport transport; private Future pingTimeoutTimer; private Future pingIntervalTimer; private ReadyState readyState; private ScheduledExecutorService heartbeatScheduler = Executors.newSingleThreadScheduledExecutor(); public Socket() { this(new Options()); } /** * Creates a socket. * * @param uri URI to connect. * @throws URISyntaxException */ public Socket(String uri) throws URISyntaxException { this(uri, null); } public Socket(URI uri) { this(uri, null); } /** * Creates a socket with options. * * @param uri URI to connect. * @param opts options for socket * @throws URISyntaxException */ public Socket(String uri, Options opts) throws URISyntaxException { this(uri == null ? null : new URI(uri), opts); } public Socket(URI uri, Options opts) { this(uri == null ? opts : Options.fromURI(uri, opts)); } public Socket(Options opts) { if (opts.host != null) { String[] pieces = opts.host.split(":"); opts.hostname = pieces[0]; if (pieces.length > 1) { opts.port = Integer.parseInt(pieces[pieces.length - 1]); } } this.secure = opts.secure; this.hostname = opts.hostname != null ? opts.hostname : "localhost"; this.port = opts.port != 0 ? opts.port : (this.secure ? 443 : 80); this.query = opts.query != null ? Util.qsParse(opts.query) : new HashMap<String, String>(); this.upgrade = opts.upgrade; this.path = (opts.path != null ? opts.path : "/engine.io").replaceAll("/$", "") + "/"; this.timestampParam = opts.timestampParam != null ? opts.timestampParam : "t"; this.timestampRequests = opts.timestampRequests; this.transports = new ArrayList<String>(Arrays.asList(opts.transports != null ? opts.transports : new String[]{Polling.NAME, WebSocket.NAME})); this.policyPort = opts.policyPort != 0 ? opts.policyPort : 843; this.rememberUpgrade = opts.rememberUpgrade; } /** * Connects the client. */ public void open() { EventThread.exec(new Runnable() { @Override public void run() { String transportName; if (Socket.this.rememberUpgrade && Socket.priorWebsocketSuccess && Socket.this.transports.contains(WebSocket.NAME)) { transportName = WebSocket.NAME; } else { transportName = Socket.this.transports.get(0); } Socket.this.readyState = ReadyState.OPENING; Transport transport = Socket.this.createTransport(transportName); Socket.this.setTransport(transport); transport.open(); } }); } private Transport createTransport(String name) { logger.fine(String.format("creating transport '%s'", name)); Map<String, String> query = new HashMap<String, String>(this.query); query.put("EIO", String.valueOf(Parser.protocol)); query.put("transport", name); if (this.id != null) { query.put("sid", this.id); } Transport.Options opts = new Transport.Options(); opts.hostname = this.hostname; opts.port = this.port; opts.secure = this.secure; opts.path = this.path; opts.query = query; opts.timestampRequests = this.timestampRequests; opts.timestampParam = this.timestampParam; opts.policyPort = this.policyPort; opts.socket = this; if (WebSocket.NAME.equals(name)) { return new WebSocket(opts); } else if (Polling.NAME.equals(name)) { return new PollingXHR(opts); } throw new RuntimeException(); } private void setTransport(Transport transport) { logger.fine(String.format("setting transport %s", transport.name)); final Socket self = this; if (this.transport != null) { logger.fine(String.format("clearing existing transport %s", this.transport.name)); this.transport.off(); } this.transport = transport; self.emit(EVENT_TRANSPORT, transport); transport.on(Transport.EVENT_DRAIN, new Listener() { @Override public void call(Object... args) { self.onDrain(); } }).on(Transport.EVENT_PACKET, new Listener() { @Override public void call(Object... args) { self.onPacket(args.length > 0 ? (Packet) args[0] : null); } }).on(Transport.EVENT_ERROR, new Listener() { @Override public void call(Object... args) { self.onError(args.length > 0 ? (Exception) args[0] : null); } }).on(Transport.EVENT_CLOSE, new Listener() { @Override public void call(Object... args) { self.onClose("transport close"); } }); } private void probe(final String name) { logger.fine(String.format("probing transport '%s'", name)); final Transport[] transport = new Transport[] {this.createTransport(name)}; final boolean[] failed = new boolean[] {false}; final Socket self = this; Socket.priorWebsocketSuccess = false; final Listener onerror = new Listener() { @Override public void call(Object... args) { if (failed[0]) return; failed[0] = true; // TODO: handle error Exception err = args.length > 0 ? (Exception)args[0] : null; EngineIOException error = new EngineIOException("probe error", err); //error.transport = transport[0].name; transport[0].close(); transport[0] = null; logger.fine(String.format("probing transport '%s' failed because of error: %s", name, err)); self.emit(EVENT_UPGRADE_ERROR, error); } }; transport[0].once(Transport.EVENT_OPEN, new Listener() { @Override public void call(Object... args) { if (failed[0]) return; logger.fine(String.format("probe transport '%s' opened", name)); Packet<String> packet = new Packet<String>(Packet.PING, "probe"); transport[0].send(new Packet[] {packet}); transport[0].once(Transport.EVENT_PACKET, new Listener() { @Override public void call(Object... args) { if (failed[0]) return; Packet msg = (Packet)args[0]; if (Packet.PONG.equals(msg.type) && "probe".equals(msg.data)) { logger.fine(String.format("probe transport '%s' pong", name)); self.upgrading = true; self.emit(EVENT_UPGRADING, transport[0]); Socket.priorWebsocketSuccess = WebSocket.NAME.equals(transport[0].name); logger.fine(String.format("pausing current transport '%s'", self.transport.name)); ((Polling)self.transport).pause(new Runnable() { @Override public void run() { if (failed[0]) return; if (self.readyState == ReadyState.CLOSED || self.readyState == ReadyState.CLOSING) { return; } logger.fine("changing transport and sending upgrade packet"); transport[0].off(Transport.EVENT_ERROR, onerror); self.setTransport(transport[0]); Packet packet = new Packet(Packet.UPGRADE); transport[0].send(new Packet[]{packet}); self.emit(EVENT_UPGRADE, transport[0]); transport[0] = null; self.upgrading = false; self.flush(); } }); } else { logger.fine(String.format("probe transport '%s' failed", name)); EngineIOException err = new EngineIOException("probe error"); //err.transport = transport[0].name; self.emit(EVENT_UPGRADE_ERROR, err); } } }); } }); transport[0].once(Transport.EVENT_ERROR, onerror); this.once(EVENT_CLOSE, new Listener() { @Override public void call(Object... args) { if (transport[0] != null) { logger.fine("socket closed prematurely - aborting probe"); failed[0] = true; transport[0].close(); transport[0] = null; } } }); this.once(EVENT_UPGRADING, new Listener() { @Override public void call(Object... args) { Transport to = (Transport)args[0]; if (transport[0] != null && !to.name.equals(transport[0].name)) { logger.fine(String.format("'%s' works - aborting '%s'", to.name, transport[0].name)); transport[0].close(); transport[0] = null; } } }); transport[0].open(); } private void onOpen() { logger.fine("socket open"); this.readyState = ReadyState.OPEN; Socket.priorWebsocketSuccess = WebSocket.NAME.equals(this.transport.name); this.emit(EVENT_OPEN); this.onopen(); this.flush(); if (this.readyState == ReadyState.OPEN && this.upgrade && this.transport instanceof Polling) { logger.fine("starting upgrade probes"); for (String upgrade: this.upgrades) { this.probe(upgrade); } } } private void onPacket(Packet packet) { if (this.readyState == ReadyState.OPENING || this.readyState == ReadyState.OPEN) { logger.fine(String.format("socket received: type '%s', data '%s'", packet.type, packet.data)); this.emit(EVENT_PACKET, packet); this.emit(EVENT_HEARTBEAT); if (Packet.OPEN.equals(packet.type)) { this.onHandshake(new HandshakeData(new JSONObject((String)packet.data))); } else if (Packet.PONG.equals(packet.type)) { this.setPing(); } else if (Packet.ERROR.equals(packet.type)) { // TODO: handle error EngineIOException err = new EngineIOException("server error"); //err.code = packet.data; this.emit(EVENT_ERROR, err); } else if (Packet.MESSAGE.equals(packet.type)) { this.emit(EVENT_DATA, packet.data); this.emit(EVENT_MESSAGE, packet.data); if (packet.data instanceof String) { this.onmessage((String)packet.data); } else if (packet.data instanceof byte[]) { this.onmessage((byte[])packet.data); } } } else { logger.fine(String.format("packet received with socket readyState '%s'", this.readyState)); } } private void onHandshake(HandshakeData data) { this.emit(EVENT_HANDSHAKE, data); this.id = data.sid; this.transport.query.put("sid", data.sid); this.upgrades = this.filterUpgrades(Arrays.asList(data.upgrades)); this.pingInterval = data.pingInterval; this.pingTimeout = data.pingTimeout; this.onOpen(); this.setPing(); this.off(EVENT_HEARTBEAT, this.onHeartbeatAsListener); this.on(EVENT_HEARTBEAT, this.onHeartbeatAsListener); } private final Listener onHeartbeatAsListener = new Listener() { @Override public void call(Object... args) { Socket.this.onHeartbeat(args.length > 0 ? (Long)args[0]: 0); } }; private void onHeartbeat(long timeout) { if (this.pingTimeoutTimer != null) { pingTimeoutTimer.cancel(true); } if (timeout <= 0) { timeout = this.pingInterval + this.pingTimeout; } final Socket self = this; this.pingTimeoutTimer = this.heartbeatScheduler.schedule(new Runnable() { @Override public void run() { EventThread.exec(new Runnable() { @Override public void run() { if (self.readyState == ReadyState.CLOSED) return; self.onClose("ping timeout"); } }); } }, timeout, TimeUnit.MILLISECONDS); } private void setPing() { if (this.pingIntervalTimer != null) { pingIntervalTimer.cancel(true); } final Socket self = this; this.pingIntervalTimer = this.heartbeatScheduler.schedule(new Runnable() { @Override public void run() { EventThread.exec(new Runnable() { @Override public void run() { logger.fine(String.format("writing ping packet - expecting pong within %sms", self.pingTimeout)); self.ping(); self.onHeartbeat(self.pingTimeout); } }); } }, this.pingInterval, TimeUnit.MILLISECONDS); } /** * Sends a ping packet. */ public void ping() { EventThread.exec(new Runnable() { @Override public void run() { Socket.this.sendPacket(Packet.PING); } }); } private void onDrain() { for (int i = 0; i < this.prevBufferLen; i++) { Runnable callback = this.callbackBuffer.get(i); if (callback != null) { callback.run(); } } for (int i = 0; i < this.prevBufferLen; i++) { this.writeBuffer.poll(); this.callbackBuffer.poll(); } this.prevBufferLen = 0; if (this.writeBuffer.size() == 0) { this.emit(EVENT_DRAIN); } else { this.flush(); } } private void flush() { if (this.readyState != ReadyState.CLOSED && this.transport.writable && !this.upgrading && this.writeBuffer.size() != 0) { logger.fine(String.format("flushing %d packets in socket", this.writeBuffer.size())); this.prevBufferLen = this.writeBuffer.size(); this.transport.send(this.writeBuffer.toArray(new Packet[this.writeBuffer.size()])); this.emit(EVENT_FLUSH); } } public void write(String msg) { this.write(msg, null); } public void write(String msg, Runnable fn) { this.send(msg, fn); } public void write(byte[] msg) { this.write(msg, null); } public void write(byte[] msg, Runnable fn) { this.send(msg, fn); } /** * Sends a message. * * @param msg */ public void send(String msg) { this.send(msg, null); } public void send(byte[] msg) { this.send(msg, null); } /** * Sends a message. * * @param msg * @param fn callback to be called on drain */ public void send(final String msg, final Runnable fn) { EventThread.exec(new Runnable() { @Override public void run() { Socket.this.sendPacket(Packet.MESSAGE, msg, fn); } }); } public void send(final byte[] msg, final Runnable fn) { EventThread.exec(new Runnable() { @Override public void run() { Socket.this.sendPacket(Packet.MESSAGE, msg, fn); } }); } private void sendPacket(String type) { this.sendPacket(new Packet(type), null); } private void sendPacket(String type, String data, Runnable fn) { Packet<String> packet = new Packet<String>(type, data); sendPacket(packet, fn); } private void sendPacket(String type, byte[] data, Runnable fn) { Packet<byte[]> packet = new Packet<byte[]>(type, data); sendPacket(packet, fn); } private void sendPacket(Packet packet, Runnable fn) { if (fn == null) { // ConcurrentLinkedList does not permit `null`. fn = noop; } this.emit(EVENT_PACKET_CREATE, packet); this.writeBuffer.offer(packet); this.callbackBuffer.offer(fn); this.flush(); } /** * Disconnects the client. * * @return a reference to to this object. */ public Socket close() { EventThread.exec(new Runnable() { @Override public void run() { if (Socket.this.readyState == ReadyState.OPENING || Socket.this.readyState == ReadyState.OPEN) { Socket.this.onClose("forced close"); logger.fine("socket closing - telling transport to close"); Socket.this.transport.close(); } } }); return this; } private void onError(Exception err) { logger.fine(String.format("socket error %s", err)); Socket.priorWebsocketSuccess = false; this.emit(EVENT_ERROR, err); this.onerror(err); this.onClose("transport error", err); } private void onClose(String reason) { this.onClose(reason, null); } private void onClose(String reason, Exception desc) { if (this.readyState == ReadyState.OPENING || this.readyState == ReadyState.OPEN) { logger.fine(String.format("socket close with reason: %s", reason)); final Socket self = this; // clear timers if (this.pingIntervalTimer != null) { this.pingIntervalTimer.cancel(true); } if (this.pingTimeoutTimer != null) { this.pingTimeoutTimer.cancel(true); } EventThread.nextTick(new Runnable() { @Override public void run() { self.writeBuffer.clear(); self.callbackBuffer.clear(); self.prevBufferLen = 0; } }); // ensure transport won't stay open this.transport.close(); // ignore further transport communication this.transport.off(); // set ready state this.readyState = ReadyState.CLOSED; // clear session id this.id = null; // emit close events this.emit(EVENT_CLOSE, reason, desc); this.onclose(); } } /*package*/ List<String > filterUpgrades(List<String> upgrades) { List<String> filteredUpgrades = new ArrayList<String>(); for (String upgrade : upgrades) { if (this.transports.contains(upgrade)) { filteredUpgrades.add(upgrade); } } return filteredUpgrades; } public void onmessage(byte[] data) {} public abstract void onopen(); public abstract void onmessage(String data); public abstract void onclose(); public abstract void onerror(Exception err); public static class Options extends Transport.Options { /** * List of transport names. */ public String[] transports; /** * Whether to upgrade the transport. Defaults to `true`. */ public boolean upgrade = true; public boolean rememberUpgrade; public String host; public String query; private static Options fromURI(URI uri, Options opts) { if (opts == null) { opts = new Options(); } opts.host = uri.getHost(); opts.secure = "https".equals(uri.getScheme()) || "wss".equals(uri.getScheme()); opts.port = uri.getPort(); String query = uri.getRawQuery(); if (query != null) { opts.query = query; } return opts; } } }
package sc.iview.commands.demo; import cleargl.GLVector; import graphics.scenery.Node; import graphics.scenery.PointLight; import graphics.scenery.volumes.bdv.BDVVolume; import java.io.FileNotFoundException; import net.imagej.mesh.Mesh; import net.imagej.ops.OpService; import net.imagej.ops.geom.geom3d.mesh.BitTypeVertexInterpolator; import net.imglib2.Cursor; import net.imglib2.IterableInterval; import net.imglib2.RandomAccessibleInterval; import net.imglib2.algorithm.labeling.ConnectedComponents; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImgs; import net.imglib2.roi.labeling.ImgLabeling; import net.imglib2.type.logic.BitType; import net.imglib2.type.numeric.integer.LongType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.view.IntervalView; import net.imglib2.view.Views; import org.apache.commons.io.FileUtils; import org.scijava.command.Command; import org.scijava.command.CommandService; import org.scijava.io.IOService; import org.scijava.log.LogService; import org.scijava.plugin.Menu; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.ui.UIService; import org.scijava.util.ColorRGB; import sc.iview.SciView; import sc.iview.Utils; import sc.iview.process.MeshConverter; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import static sc.iview.commands.MenuWeights.*; /** * A demo rendering an embryo volume with meshes for nuclei. * * @author Kyle Harrington */ @Plugin(type = Command.class, label = "Embryo Demo", menuRoot = "SciView", menu = { @Menu(label = "Demo", weight = DEMO), @Menu(label = "BDV Embryo Segmentation Demo", weight = DEMO_EMBRYO) }) public class EmbryoDemo implements Command { @Parameter private IOService io; @Parameter private LogService log; @Parameter private SciView sciView; @Parameter private CommandService commandService; @Parameter private OpService opService; @Parameter private UIService uiService; @Parameter private IOService ioService; private String localDirectory = System.getProperty("user.home") + File.separator + "Desktop"; private BDVVolume v; private final String xmlFilename = "drosophila.xml"; private final String h5Filename = "drosophila.h5"; private final String remoteLocation = "https://fly.mpi-cbg.de/~pietzsch/bdv-examples/"; @Override public void run() { fetchEmbryoImage(localDirectory); v = (BDVVolume) sciView.addBDVVolume(localDirectory + File.separator + xmlFilename); v.setName( "Embryo Demo" ); v.setPixelToWorldRatio(0.1f); v.setNeedsUpdate(true); v.setDirty(true); // Set the initial volume transfer function /* TODO: TransferFunction behaviour is not yet implemeneted for BDVVolumes AtomicReference<Float> rampMax = new AtomicReference<>(0.007f); float rampStep = 0.01f; AtomicReference<Double> dRampSign = new AtomicReference<>(1.); if( rampMax.get() < 0 ) { dRampSign.updateAndGet(v1 -> v1 * -1); } if( rampMax.get() > 0.3 ) { dRampSign.updateAndGet(v1 -> v1 * -1); } rampMax.updateAndGet(v1 -> (float) (v1 + dRampSign.get() * rampStep)); //System.out.println("RampMax: " + rampMax.get()); v.setTransferFunction(TransferFunction.ramp(0.0f, rampMax.get())); v.setNeedsUpdate(true); v.setDirty(true); */ // use ConverterSetups instead: v.getConverterSetups().forEach( s -> s.setDisplayRange( 500.0, 1500.0 ) ); sciView.centerOnNode( sciView.getActiveNode() ); System.out.println("Meshing nuclei"); Img<UnsignedByteType> filtered = null; try { filtered = (Img<UnsignedByteType> ) ioService.open("/home/kharrington/Data/Tobi/drosophila_filtered_8bit_v2.tif"); } catch (IOException e) { e.printStackTrace(); } // RandomAccessibleInterval<VolatileUnsignedShortType> volRAI = (RandomAccessibleInterval<VolatileUnsignedShortType>) v.getStack(0, 0, false).resolutions().get(0).getImage(); // IterableInterval<VolatileUnsignedShortType> volII = Views.iterable(volRAI); // int isoLevel = 6; // //Img<UnsignedByteType> volImg = opService.create().img(new long[]{volII.dimension(0), volII.dimension(1), volII.dimension(2)},new UnsignedByteType()); // Img<UnsignedByteType> volImg = opService.create().img(Intervals.createMinMax(0,0,0,volII.dimension(0), volII.dimension(1), volII.dimension(2)), new UnsignedByteType()); // System.out.println("Populating img: " + volImg); // Cursor<VolatileUnsignedShortType> c0 = volII.cursor(); // Cursor<UnsignedByteType> c1 = volImg.cursor(); // while(c0.hasNext()) { // c0.next(); // c1.next(); // c1.get().set(c0.get().get().get()); Img<UnsignedByteType> volImg = filtered; int isoLevel = 75; uiService.show(volImg); Img<BitType> bitImg = ( Img<BitType> ) opService.threshold().apply( volImg, new UnsignedByteType( isoLevel ) ); System.out.println("Thresholding done"); //ImgLabeling<Object, IntType> labels = opService.labeling().cca(bitImg, ConnectedComponents.StructuringElement.FOUR_CONNECTED); int start = 1; final Iterator< Integer > names = new Iterator< Integer >() { private int i = start; @Override public boolean hasNext() { return true; } @Override public Integer next() { return i++; } @Override public void remove() {} }; final long[] dimensions = new long[] { bitImg.dimension(0), bitImg.dimension(1), bitImg.dimension(2) }; final Img< LongType > indexImg = ArrayImgs.longs( dimensions ); final ImgLabeling< Integer, LongType > labeling = new ImgLabeling<>(indexImg); ConnectedComponents.labelAllConnectedComponents( bitImg, labeling, names, ConnectedComponents.StructuringElement.FOUR_CONNECTED ); uiService.show(bitImg); uiService.show(indexImg); Node[] lights = sciView.getSceneNodes(n -> n instanceof PointLight); float y = 0; GLVector c = new GLVector(0,0,0); float r = 500; for( int k = 0; k < lights.length; k++ ) { PointLight light = (PointLight) lights[k]; float x = (float) (c.x() + r * Math.cos( k == 0 ? 0 : Math.PI * 2 * ((float)k / (float)lights.length) )); float z = (float) (c.y() + r * Math.sin( k == 0 ? 0 : Math.PI * 2 * ((float)k / (float)lights.length) )); light.setLightRadius( 2 * r ); light.setPosition( new GLVector( x, y, z ) ); } showMeshes(labeling); // Mesh m = opService.geom().marchingCubes( bitImg, isoLevel, new BitTypeVertexInterpolator() ); // System.out.println("Marching cubes done"); // graphics.scenery.Mesh isoSurfaceMesh = MeshConverter.toScenery(m,true); // Node scMesh = sciView.addMesh(isoSurfaceMesh); // isoSurfaceMesh.setName( "Volume Render Demo Isosurface" ); // isoSurfaceMesh.setScale(new GLVector(v.getPixelToWorldRatio(), // v.getPixelToWorldRatio(), // v.getPixelToWorldRatio())); //sciView.addSphere(); } public void showMeshes( ImgLabeling<Integer, LongType> labeling ) { RandomAccessibleInterval<LongType> labelRAI = labeling.getIndexImg(); IterableInterval<LongType> labelII = Views.iterable(labelRAI); HashSet<Long> labelSet = new HashSet<>(); Cursor<LongType> cur = labelII.cursor(); while( cur.hasNext() ) { cur.next(); labelSet.add((long) cur.get().get()); } // Create label list and colors ArrayList<LongType> labelList = new ArrayList<>(); ArrayList<ColorRGB> labelColors = new ArrayList<>(); for( Long l : labelSet ) { labelList.add( new LongType(Math.toIntExact(l)) ); labelColors.add( new ColorRGB((int) (Math.random()*255), (int) (Math.random()*255), (int) (Math.random()*255) ) ); } int numRegions = labelList.size(); // GLVector vOffset = new GLVector(v.getSizeX() * v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.5f, // v.getSizeY() * v.getVoxelSizeY() * v.getPixelToWorldRatio() * 0.5f, // v.getSizeZ() * v.getVoxelSizeZ() * v.getPixelToWorldRatio() * 0.5f); float xscale = v.getVoxelSizeX() * v.getPixelToWorldRatio() * 0.36f; float yscale = v.getVoxelSizeY() * v.getPixelToWorldRatio() * 0.3f; float zscale = v.getVoxelSizeZ() * v.getPixelToWorldRatio() * 0.25f; GLVector vHalf = new GLVector(v.getSizeX() * xscale, v.getSizeY() * yscale, v.getSizeZ() * zscale); GLVector vOffset = new GLVector(0,0,0); System.out.println("Found " + numRegions + " regions"); System.out.println("Voxel size: " + v.getVoxelSizeX() + " , " + v.getVoxelSizeY() + " " + v.getVoxelSizeZ() + " voxtoworld: " + v.getPixelToWorldRatio()); Random rng = new Random(); // Create label images and segmentations //for( LabelRegion labelRegion : labelRegions ) { for( int k = 0; k < numRegions; k++ ) { System.out.println("Starting to process region " + k ); long id = labelList.get(k).getIntegerLong(); if( id > 1 ) { // Ignore background // get labelColor using ID //ColorRGB labelColor = labelColors.get(k); //ColorRGB labelColor = colorFromID(id); //ColorRGB labelColor = new ColorRGB(255,255,255); ColorRGB labelColor = new ColorRGB(rng.nextInt(255),rng.nextInt(255), rng.nextInt(255)); Img<BitType> labelRegion = opService.create().img(labelII, new BitType()); cur = labelII.cursor(); LongType thisLabel = labelList.get(k); Cursor<BitType> rCur = labelRegion.cursor(); long sum = 0; while (cur.hasNext()) { cur.next(); rCur.next(); if (cur.get().valueEquals(thisLabel)) { rCur.get().set(true); sum++; } else { rCur.get().set(false); } } System.out.println("Label " + k + " has sum voxels = " + sum); // FIXME: hack to skip large meshes if ( sum > 10 && sum < 10000) { // Find the smallest bounding box int xmin=Integer.MAX_VALUE, ymin=Integer.MAX_VALUE, zmin=Integer.MAX_VALUE; int xmax=Integer.MIN_VALUE, ymax=Integer.MIN_VALUE, zmax=Integer.MIN_VALUE; int x,y,z; rCur = labelRegion.cursor(); while(rCur.hasNext()) { rCur.next(); if( rCur.get().get() ) { x = rCur.getIntPosition(0); y = rCur.getIntPosition(1); z = rCur.getIntPosition(2); xmin = Math.min(xmin,x); ymin = Math.min(ymin,y); zmin = Math.min(zmin,z); xmax = Math.max(xmax,x); ymax = Math.max(ymax,y); zmax = Math.max(zmax,z); } } IntervalView<BitType> cropLabelRegion = Views.interval(labelRegion, new long[]{xmin, ymin, zmin}, new long[]{xmax, ymax, zmax}); Mesh m = opService.geom().marchingCubes(cropLabelRegion, 1, new BitTypeVertexInterpolator()); graphics.scenery.Mesh isoSurfaceMesh = MeshConverter.toScenery(m, false); isoSurfaceMesh.recalculateNormals(); Node scMesh = sciView.addMesh(isoSurfaceMesh); scMesh.setPosition(scMesh.getPosition().minus(vOffset).plus(new GLVector( -vHalf.x() + xmin* xscale, ymin* yscale, zmin* zscale))); scMesh.setScale(new GLVector(v.getPixelToWorldRatio(), v.getPixelToWorldRatio(), v.getPixelToWorldRatio())); scMesh.getMaterial().setAmbient(Utils.convertToGLVector(labelColor)); scMesh.getMaterial().setDiffuse(Utils.convertToGLVector(labelColor)); scMesh.setName("region_" + k); scMesh.setNeedsUpdate(true); scMesh.setDirty(true); scMesh.getMetadata().put("mesh_ID", id); } } //scMesh.setName( "region_" + labelRegion.getLabel() ); } sciView.takeScreenshot(); // Remove all other old meshes // for( Node n : previousMeshes ) { // sciView.deleteNode( n ); // Color code meshes and overlay in volume } public static ColorRGB colorFromID( Long id ) { // Hash to get label colors so they are unique by id Random rng = new Random(id); return new ColorRGB( rng.nextInt(256), rng.nextInt(256), rng.nextInt(256) ); } public void fetchEmbryoImage(String localDestination) { if( !(new File(localDirectory + File.separator + xmlFilename).exists()) ) { // File doesnt exist, so fetch System.out.println("Fetching data. This may take a moment..."); try { FileUtils.copyURLToFile(new URL(remoteLocation + "/" + xmlFilename), new File(localDestination + File.separator + xmlFilename)); FileUtils.copyURLToFile(new URL(remoteLocation + "/" + h5Filename), new File(localDestination + File.separator + h5Filename)); } catch (FileNotFoundException e) { System.out.println("Could not download file, " + xmlFilename + " not found on host."); } catch (IOException e) { e.printStackTrace(); } } } }