hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
3d02fe5a9a7c7fbfee8906db24a905447e3d2d32
15,513
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.editorActions.enter; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.highlighting.BraceMatcher; import com.intellij.codeInsight.highlighting.BraceMatchingUtil; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.HighlighterIterator; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.TokenType; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.IncorrectOperationException; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; public class EnterAfterUnmatchedBraceHandler extends EnterHandlerDelegateAdapter { private static final Logger LOG = Logger.getInstance(EnterAfterUnmatchedBraceHandler.class); @Override public Result preprocessEnter(@NotNull final PsiFile file, @NotNull final Editor editor, @NotNull final Ref<Integer> caretOffsetRef, @NotNull final Ref<Integer> caretAdvance, @NotNull final DataContext dataContext, final EditorActionHandler originalHandler) { int caretOffset = caretOffsetRef.get(); if (!isApplicable(file, caretOffset)) { return Result.Continue; } int maxRBraceCount = getMaxRBraceCount(file, editor, caretOffset); if (maxRBraceCount > 0) { insertRBraces(file, editor, caretOffset, getRBraceOffset(file, editor, caretOffset), generateStringToInsert(editor, caretOffset, maxRBraceCount)); return Result.DefaultForceIndent; } return Result.Continue; } /** * Checks that the text context is in responsibility of the handler. * * @param file target PSI file * @param caretOffset target caret offset * @return true, if handler is in charge */ public boolean isApplicable(@NotNull PsiFile file, int caretOffset) { return true; } /** * Calculates the maximum number of '}' that can be inserted by handler. * Can return {@code 0} or less in custom implementation to skip '}' insertion in the {@code preprocessEnter} call * and switch to default implementation. * * @param file target PSI file * @param editor target editor * @param caretOffset target caret offset * @return maximum number of '}' that can be inserted by handler, {@code 0} or less to switch to default implementation */ protected int getMaxRBraceCount(@NotNull final PsiFile file, @NotNull final Editor editor, int caretOffset) { if (!CodeInsightSettings.getInstance().INSERT_BRACE_ON_ENTER) { return 0; } return Math.max(0, getUnmatchedLBracesNumberBefore(editor, caretOffset, file.getFileType())); } /** * Calculates the string of '}' that have to be inserted by handler. * Some languages can expand the string by additional characters (i.e. '\', ';') * * @param editor target editor * @param caretOffset target caret offset * @param maxRBraceCount the maximum number of '}' for insert at position, it always positive * @return the string of '}' that has to be inserted by handler, it must have at least one '}' */ @NotNull protected String generateStringToInsert(@NotNull final Editor editor, int caretOffset, int maxRBraceCount) { assert maxRBraceCount > 0; CharSequence text = editor.getDocument().getCharsSequence(); int bracesToInsert = 0; for (int i = caretOffset - 1; i >= 0 && bracesToInsert < maxRBraceCount; --i) { final char c = text.charAt(i); if (c == '{') { ++bracesToInsert; } else if (isStopChar(c)) { break; } } return StringUtil.repeatSymbol('}', Math.max(bracesToInsert, 1)); } /** * Checks the character before the inserted '}' to reduce the count of inserted '}'. * The number of inserted '}' will increase for each found '{'. * * @param c character to check * @return true, to stop back iteration */ protected boolean isStopChar(char c) { return " \n\t".indexOf(c) < 0; } /** * Calculates the position for insertion of one or more '}'. * * @param file target PSI file * @param editor target editor * @param caretOffset target caret offset * @return the position between {@code caretOffset} and the end of file */ protected int getRBraceOffset(@NotNull final PsiFile file, @NotNull final Editor editor, int caretOffset) { CharSequence text = editor.getDocument().getCharsSequence(); int offset = CharArrayUtil.shiftForward(text, caretOffset, " \t"); final int fileLength = text.length(); if (offset < fileLength && ")];,%<?".indexOf(text.charAt(offset)) < 0) { offset = calculateOffsetToInsertClosingBrace(file, text, offset).second; //offset = CharArrayUtil.shiftForwardUntil(text, caretOffset, "\n"); } return Math.min(offset, fileLength); } /** * Inserts the {@code generatedRBraces} at the {@code rBracesInsertOffset} position and formats the code block. * @param file target PSI file * @param editor target editor * @param caretOffset target caret offset * @param rBracesInsertOffset target position to insert * @param generatedRBraces string of '}' to insert */ protected void insertRBraces(@NotNull PsiFile file, @NotNull Editor editor, int caretOffset, int rBracesInsertOffset, String generatedRBraces) { final Document document = editor.getDocument(); insertRBracesAtPosition(document, caretOffset, rBracesInsertOffset, generatedRBraces); formatCodeFragmentBetweenBraces(file, document, editor, caretOffset, rBracesInsertOffset, generatedRBraces); } /** * Inserts the {@code rBracesCount} of '}' at the {@code rBracesInsertOffset} position. * * @param document target document * @param caretOffset target caret offset * @param rBracesInsertOffset target position to insert * @param generatedRBraces string of '}' to insert */ protected void insertRBracesAtPosition(Document document, int caretOffset, int rBracesInsertOffset, String generatedRBraces) { document.insertString(rBracesInsertOffset, "\n" + generatedRBraces); // We need to adjust indents of the text that will be moved, hence, need to insert preliminary line feed. // Example: // if (test1()) { // } else {<caret> if (test2()) { // foo(); // } // We insert here '\n}' after 'foo();' and have the following: // if (test1()) { // } else { if (test2()) { // foo(); // } // } // That is formatted incorrectly because line feed between 'else' and 'if' is not inserted yet (whole 'if' block is indent anchor // to 'if' code block('{}')). So, we insert temporary line feed between 'if' and 'else', correct indent and remove that temporary // line feed. document.insertString(caretOffset, "\n"); } /** * Formats the code block between caret and inserted braces. * @param file target PSI file * @param document target document * @param editor target editor * @param caretOffset target caret offset * @param rBracesInsertOffset target position to insert * @param generatedRBraces string of '}' to insert */ protected void formatCodeFragmentBetweenBraces(@NotNull PsiFile file, @NotNull Document document, @NotNull Editor editor, int caretOffset, int rBracesInsertOffset, String generatedRBraces) { Project project = file.getProject(); long stamp = document.getModificationStamp(); boolean closingBraceIndentAdjusted; try { PsiDocumentManager.getInstance(project).commitDocument(document); CodeStyleManager.getInstance(project).adjustLineIndent(file, new TextRange(caretOffset, rBracesInsertOffset + 2)); } catch (IncorrectOperationException e) { LOG.error(e); } finally { closingBraceIndentAdjusted = stamp != document.getModificationStamp(); // do you remember that we insert the '\n'? here we take it back! document.deleteString(caretOffset, caretOffset + 1); } // There is a possible case that formatter was unable to adjust line indent for the closing brace (that is the case for plain text // document for example). Hence, we're trying to do the manually. if (!closingBraceIndentAdjusted) { int line = document.getLineNumber(rBracesInsertOffset); StringBuilder buffer = new StringBuilder(); int start = document.getLineStartOffset(line); int end = document.getLineEndOffset(line); final CharSequence text = document.getCharsSequence(); for (int i = start; i < end; i++) { char c = text.charAt(i); if (c != ' ' && c != '\t') { break; } else { buffer.append(c); } } if (buffer.length() > 0) { document.insertString(rBracesInsertOffset + 1, buffer); } } } /** * Current handler inserts closing curly brace (right brace) if necessary. There is a possible case that it should be located * more than one line forward. * <p/> * <b>Example</b> * <pre> * if (test1()) { * } else {<caret> if (test2()) { * foo(); * } * </pre> * <p/> * We want to get this after the processing: * <pre> * if (test1()) { * } else { * if (test2()) { * foo(); * } * } * </pre> * I.e. closing brace should be inserted two lines below current caret line. Hence, we need to calculate correct offset * to use for brace inserting. This method is responsible for that. * <p/> * In essence it inspects PSI structure and finds PSE elements with the max length that starts at caret offset. End offset * of that element is used as an insertion point. * * @param file target PSI file * @param text text from the given file * @param offset target offset where line feed will be inserted * @return pair of (element, offset). The element is the '}' owner, if applicable; the offset is the position for inserting closing brace */ protected Pair<PsiElement, Integer> calculateOffsetToInsertClosingBrace(@NotNull PsiFile file, @NotNull CharSequence text, final int offset) { PsiElement element = PsiUtilCore.getElementAtOffset(file, offset); ASTNode node = element.getNode(); if (node != null && node.getElementType() == TokenType.WHITE_SPACE) { return Pair.create(null, CharArrayUtil.shiftForwardUntil(text, offset, "\n")); } for (PsiElement parent = element.getParent(); parent != null; parent = parent.getParent()) { ASTNode parentNode = parent.getNode(); if (parentNode == null || parentNode.getStartOffset() != offset) { break; } element = parent; } if (element.getTextOffset() != offset) { return Pair.create(null, CharArrayUtil.shiftForwardUntil(text, offset, "\n")); } return Pair.create(element, calculateOffsetToInsertClosingBraceInsideElement(element)); } protected int calculateOffsetToInsertClosingBraceInsideElement(PsiElement element) { return element.getTextRange().getEndOffset(); } public static boolean isAfterUnmatchedLBrace(Editor editor, int offset, FileType fileType) { return getUnmatchedLBracesNumberBefore(editor, offset, fileType) > 0; } /** * Calculates number of unmatched left braces before the given offset. * * @param editor target editor * @param offset target offset * @param fileType target file type * @return number of unmatched braces before the given offset; * negative value if it's not possible to perform the calculation or if there are no unmatched left braces before * the given offset */ protected static int getUnmatchedLBracesNumberBefore(Editor editor, int offset, FileType fileType) { if (offset == 0) { return -1; } CharSequence chars = editor.getDocument().getCharsSequence(); if (chars.charAt(offset - 1) != '{') { return -1; } EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter(); HighlighterIterator iterator = highlighter.createIterator(offset - 1); BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator); if (!braceMatcher.isLBraceToken(iterator, chars, fileType) || !braceMatcher.isStructuralBrace(iterator, chars, fileType)) { return -1; } Language language = iterator.getTokenType().getLanguage(); iterator = highlighter.createIterator(0); int lBracesBeforeOffset = 0; int lBracesAfterOffset = 0; int rBracesBeforeOffset = 0; int rBracesAfterOffset = 0; for (; !iterator.atEnd(); iterator.advance()) { IElementType tokenType = iterator.getTokenType(); if (!tokenType.getLanguage().equals(language) || !braceMatcher.isStructuralBrace(iterator, chars, fileType)) { continue; } boolean beforeOffset = iterator.getStart() < offset; if (braceMatcher.isLBraceToken(iterator, chars, fileType)) { if (beforeOffset) { lBracesBeforeOffset++; } else { lBracesAfterOffset++; } } else if (braceMatcher.isRBraceToken(iterator, chars, fileType)) { if (beforeOffset) { rBracesBeforeOffset++; } else { rBracesAfterOffset++; } } } return lBracesBeforeOffset - rBracesBeforeOffset - (rBracesAfterOffset - lBracesAfterOffset); } }
40.503916
144
0.663637
dddce60cd522de8a9a0d3a30842b548e9d9fe64c
7,709
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id: FormatRed.java 1576437 2014-03-11 17:49:35Z vhennebert $ */ package org.apache.xmlgraphics.image.rendered; import java.awt.Point; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.ComponentColorModel; import java.awt.image.ComponentSampleModel; import java.awt.image.DataBuffer; import java.awt.image.DirectColorModel; import java.awt.image.Raster; import java.awt.image.SampleModel; import java.awt.image.SinglePixelPackedSampleModel; import java.awt.image.WritableRaster; import org.apache.xmlgraphics.image.GraphicsUtil; // CSOFF: NeedBraces // CSOFF: WhitespaceAfter // CSOFF: WhitespaceAround /** * This allows you to specify the ColorModel, Alpha premult and/or * SampleModel to be used for output. If the input image lacks * Alpha and alpha is included in output then it is filled with * alpha=1. In all other cases bands are simply copied. * * @version $Id: FormatRed.java 1576437 2014-03-11 17:49:35Z vhennebert $ * * Originally authored by Thomas DeWeese. */ public class FormatRed extends AbstractRed { public static CachableRed construct(CachableRed src, ColorModel cm) { ColorModel srcCM = src.getColorModel(); if ((cm.hasAlpha() != srcCM.hasAlpha()) || (cm.isAlphaPremultiplied() != srcCM.isAlphaPremultiplied())) { return new FormatRed(src, cm); } if (cm.getNumComponents() != srcCM.getNumComponents()) { throw new IllegalArgumentException( "Incompatible ColorModel given"); } if ((srcCM instanceof ComponentColorModel) && (cm instanceof ComponentColorModel)) { return src; } if ((srcCM instanceof DirectColorModel) && (cm instanceof DirectColorModel)) { return src; } return new FormatRed(src, cm); } /** * Construct an instance of CachableRed around a BufferedImage. */ public FormatRed(CachableRed cr, SampleModel sm) { super(cr, cr.getBounds(), makeColorModel(cr, sm), sm, cr.getTileGridXOffset(), cr.getTileGridYOffset(), null); } public FormatRed(CachableRed cr, ColorModel cm) { super(cr, cr.getBounds(), cm, makeSampleModel(cr, cm), cr.getTileGridXOffset(), cr.getTileGridYOffset(), null); } /** * fetch the source image for this node. */ public CachableRed getSource() { return (CachableRed)getSources().get(0); } public Object getProperty(String name) { return getSource().getProperty(name); } public String [] getPropertyNames() { return getSource().getPropertyNames(); } public WritableRaster copyData(WritableRaster wr) { ColorModel cm = getColorModel(); CachableRed cr = getSource(); ColorModel srcCM = cr.getColorModel(); SampleModel srcSM = cr.getSampleModel(); srcSM = srcSM.createCompatibleSampleModel(wr.getWidth(), wr.getHeight()); WritableRaster srcWR; srcWR = Raster.createWritableRaster(srcSM, new Point(wr.getMinX(), wr.getMinY())); getSource().copyData(srcWR); BufferedImage srcBI = new BufferedImage( srcCM, srcWR.createWritableTranslatedChild(0, 0), srcCM.isAlphaPremultiplied(), null); BufferedImage dstBI = new BufferedImage( cm, wr.createWritableTranslatedChild(0, 0), cm.isAlphaPremultiplied(), null); GraphicsUtil.copyData(srcBI, dstBI); return wr; } public static SampleModel makeSampleModel(CachableRed cr, ColorModel cm) { SampleModel srcSM = cr.getSampleModel(); return cm.createCompatibleSampleModel(srcSM.getWidth(), srcSM.getHeight()); } public static ColorModel makeColorModel(CachableRed cr, SampleModel sm) { ColorModel srcCM = cr.getColorModel(); ColorSpace cs = srcCM.getColorSpace(); int bands = sm.getNumBands(); int bits; int dt = sm.getDataType(); switch (dt) { case DataBuffer.TYPE_BYTE: bits = 8; break; case DataBuffer.TYPE_SHORT: bits = 16; break; case DataBuffer.TYPE_USHORT: bits = 16; break; case DataBuffer.TYPE_INT: bits = 32; break; default: throw new IllegalArgumentException( "Unsupported DataBuffer type: " + dt); } boolean hasAlpha = srcCM.hasAlpha(); if (hasAlpha) { // if Src has Alpha then our out bands must // either be one less than the source (no out alpha) // or equal (still has alpha) if (bands == srcCM.getNumComponents() - 1) { hasAlpha = false; } else if (bands != srcCM.getNumComponents()) { throw new IllegalArgumentException( "Incompatible number of bands in and out"); } } else { if (bands == srcCM.getNumComponents() + 1) { hasAlpha = true; } else if (bands != srcCM.getNumComponents()) { throw new IllegalArgumentException( "Incompatible number of bands in and out"); } } boolean preMult = srcCM.isAlphaPremultiplied(); if (!hasAlpha) { preMult = false; } if (sm instanceof ComponentSampleModel) { int [] bitsPer = new int[bands]; for (int i = 0; i < bands; i++) { bitsPer[i] = bits; } return new ComponentColorModel( cs, bitsPer, hasAlpha, preMult, hasAlpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE, dt); } else if (sm instanceof SinglePixelPackedSampleModel) { SinglePixelPackedSampleModel sppsm; sppsm = (SinglePixelPackedSampleModel)sm; int[] masks = sppsm.getBitMasks(); if (bands == 4) { return new DirectColorModel( cs, bits, masks[0], masks[1], masks[2], masks[3], preMult, dt); } else if (bands == 3) { return new DirectColorModel( cs, bits, masks[0], masks[1], masks[2], 0x0, preMult, dt); } else { throw new IllegalArgumentException( "Incompatible number of bands out for ColorModel"); } } throw new IllegalArgumentException( "Unsupported SampleModel Type"); } }
35.362385
78
0.600078
61d260cdc187c35285b3d5f1259a60d14c44f686
6,348
/******************************************************************************* * Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Tomas Kraus - Initial implementation ******************************************************************************/ package org.eclipse.persistence.logging; import java.util.HashMap; import java.util.Map; /** * EclipseLink categories used for logging name space. * The EclipseLink categories for the logging name space are:<br> * <table summary=""> * <tr><td>&nbsp;</td><td>ALL</td> <td>&nbsp;</td><td>= "all"</td></tr> * <tr><td>&nbsp;</td><td>CACHE</td> <td>&nbsp;</td><td>= "cache"</td></tr> * <tr><td>&nbsp;</td><td>CONNECTION</td> <td>&nbsp;</td><td>= "connection"</td></tr> * <tr><td>&nbsp;</td><td>DDL</td> <td>&nbsp;</td><td>= "ddl"</td></tr> * <tr><td>&nbsp;</td><td>DMS</td> <td>&nbsp;</td><td>= "dms"</td></tr> * <tr><td>&nbsp;</td><td>EJB</td> <td>&nbsp;</td><td>= "ejb"</td></tr> * <tr><td>&nbsp;</td><td>EJB_OR_METADATA</td><td>&nbsp;</td><td>= "ejb_or_metadata"</td></tr> * <tr><td>&nbsp;</td><td>EVENT</td> <td>&nbsp;</td><td>= "event"</td></tr> * <tr><td>&nbsp;</td><td>JPA</td> <td>&nbsp;</td><td>= "jpa"</td></tr> * <tr><td>&nbsp;</td><td>JPARS</td> <td>&nbsp;</td><td>= "jpars"</td></tr> * <tr><td>&nbsp;</td><td>METADATA</td> <td>&nbsp;</td><td>= "metadata"</td></tr> * <tr><td>&nbsp;</td><td>METAMODEL</td> <td>&nbsp;</td><td>= "metamodel"</td></tr> * <tr><td>&nbsp;</td><td>MONITORING</td> <td>&nbsp;</td><td>= "monitoring"</td></tr> * <tr><td>&nbsp;</td><td>PROPAGATION</td> <td>&nbsp;</td><td>= "propagation"</td></tr> * <tr><td>&nbsp;</td><td>PROPERTIES</td> <td>&nbsp;</td><td>= "properties"</td></tr> * <tr><td>&nbsp;</td><td>QUERY</td> <td>&nbsp;</td><td>= "query"</td></tr> * <tr><td>&nbsp;</td><td>SEQUENCING</td> <td>&nbsp;</td><td>= "sequencing"</td></tr> * <tr><td>&nbsp;</td><td>SERVER</td> <td>&nbsp;</td><td>= "server"</td></tr> * <tr><td>&nbsp;</td><td>SQL</td> <td>&nbsp;</td><td>= "sql"</td></tr> * <tr><td>&nbsp;</td><td>TRANSACTION</td> <td>&nbsp;</td><td>= "transaction"</td></tr> * <tr><td>&nbsp;</td><td>WEAVER</td> <td>&nbsp;</td><td>= "weaver"</td></tr> * </table> */ public enum LogCategory { ALL( (byte)0x00, "all"), CACHE( (byte)0x01, SessionLog.CACHE), CONNECTION( (byte)0x02, SessionLog.CONNECTION), DDL( (byte)0x03, SessionLog.DDL), DMS( (byte)0x04, SessionLog.DMS), EJB( (byte)0x05, SessionLog.EJB), EVENT( (byte)0x06, SessionLog.EVENT), JPA( (byte)0x07, SessionLog.JPA), JPARS( (byte)0x08, SessionLog.JPARS), METADATA( (byte)0x09, SessionLog.METADATA), METAMODEL( (byte)0x0A, SessionLog.METAMODEL), MISC( (byte)0x0B, SessionLog.MISC), MONITORING( (byte)0x0C, SessionLog.MONITORING), PROPAGATION((byte)0x0D, SessionLog.PROPAGATION), PROPERTIES( (byte)0x0E, SessionLog.PROPERTIES), QUERY( (byte)0x0F, SessionLog.QUERY), SEQUENCING( (byte)0x10, SessionLog.SEQUENCING), SERVER( (byte)0x11, SessionLog.SERVER), SQL( (byte)0x12, SessionLog.SQL), TRANSACTION((byte)0x13, SessionLog.TRANSACTION), WEAVER( (byte)0x14, SessionLog.WEAVER); /** Logging categories enumeration length. */ public static final int length = LogCategory.values().length; /** Logger name spaces prefix. */ private static final String NAMESPACE_PREFIX = "eclipselink.logging."; /** {@link Map} for {@link String} to {@link LogCategory} case insensitive conversion. */ private static final Map<String, LogCategory> stringValuesMap = new HashMap<String, LogCategory>(2 * length); /** Logger name spaces lookup table. */ private static final String[] nameSpaces = new String[length]; static { // Initialize String to LogCategory case insensitive lookup Map. for (LogCategory category : LogCategory.values()) { stringValuesMap.put(category.name.toLowerCase(), category); } // Initialize logger name spaces lookup table. for (LogCategory category : LogCategory.values()) { nameSpaces[category.id] = NAMESPACE_PREFIX + category.name; } } /** * Returns {@link LogCategory} object holding the value of the specified {@link String}. * @param name The {@link String} to be parsed. * @return {@link LogCategory} object holding the value represented by the string argument or {@code null} when * there exists no corresponding {@link LogCategory} object to provided argument value. {@code null} value * of the string argument is converted to {@code ALL}. */ public static final LogCategory toValue(final String name) { return name != null && name.length() > 0 ? stringValuesMap.get(name.toLowerCase()) : ALL; } /** Logging category ID. Continuous integer sequence starting from 0. */ private final byte id; /** Logging category name. */ private final String name; /** * Creates an instance of logging category. * @param id Logging category ID. * @param name Logging category name. */ private LogCategory(final byte id, final String name) { this.id = id; this.name = name; } /** * Get logging category ID. * @return Logging category ID. */ public byte getId() { return id; } /** * Get logging category name. * @return Logging category name. */ public String getName() { return name; } /** * Get logger name space for this logging category. * @return Logger name space for this logging category. */ public String getNameSpace() { return nameSpaces[id]; } }
44.391608
118
0.587902
42dbff5a4cc708419a02bced7c5f7db243a405ea
2,665
/* * Copyright (c) 2007-2014 Concurrent, Inc. All Rights Reserved. * * Project and contact information: http://www.cascading.org/ * * This file is part of the Cascading project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cascading.flow; import java.util.TreeMap; import cascading.pipe.Pipe; import cascading.pipe.SubAssembly; import cascading.tap.Tap; /** * */ public class FlowElements { public static String id( FlowElement flowElement ) { if( flowElement instanceof Pipe ) return Pipe.id( (Pipe) flowElement ); if( flowElement instanceof Tap ) return Tap.id( (Tap) flowElement ); throw new IllegalArgumentException( "id not supported for: " + flowElement.getClass().getCanonicalName() ); } public static int isPrevious( Pipe pipe, Pipe previous ) { if( pipe == previous ) return 0; if( pipe instanceof SubAssembly ) { Pipe[] unwind = SubAssembly.unwind( pipe ); for( Pipe unwound : unwind ) { int result = collectPipes( unwound, 0, previous ); if( result != -1 ) return result; } return -1; } return collectPipes( pipe, 0, previous ); } private static int collectPipes( Pipe pipe, int depth, Pipe... allPrevious ) { depth++; for( Pipe previous : allPrevious ) { if( pipe == previous ) return depth; int result; if( previous instanceof SubAssembly ) result = collectPipes( pipe, depth, SubAssembly.unwind( previous ) ); else result = collectPipes( pipe, depth, previous.getPrevious() ); if( result != -1 ) return result; } return -1; } public static Integer findOrdinal( Pipe pipe, Pipe previous ) { Pipe[] previousPipes = pipe.getPrevious(); TreeMap<Integer, Integer> sorted = new TreeMap<>(); for( int i = 0; i < previousPipes.length; i++ ) { int result = isPrevious( previousPipes[ i ], (Pipe) previous ); if( result == -1 ) continue; sorted.put( result, i ); } return sorted.firstEntry().getValue(); } }
24.449541
111
0.636398
839cfbe1fe5a699175d7b73c17060411db7a5df7
2,517
/* * Copyright (c) 2020. www.hoprxi.com All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package crm.hoprxi.core.domain.model.balance; import javax.money.MonetaryAmount; import java.util.StringJoiner; /*** * @author <a href="www.hoprxi.com/authors/guan xiangHuan">guan xiangHuang</a> * @since JDK8.0 * @version 0.0.2 2020-04-02 */ public class Rounded { private MonetaryAmount integer; private MonetaryAmount remainder; public Rounded(MonetaryAmount integer, MonetaryAmount remainder) { setInteger(integer); setRemainder(remainder); } private void setRemainder(MonetaryAmount remainder) { this.remainder = remainder; } private void setInteger(MonetaryAmount integer) { if (integer.isNegative()) throw new IllegalArgumentException("Positive integer expected"); this.integer = integer; } public MonetaryAmount integer() { return integer; } public MonetaryAmount remainder() { return remainder; } public boolean isOverflow() { return remainder.isPositive(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Rounded rounded = (Rounded) o; if (integer != null ? !integer.equals(rounded.integer) : rounded.integer != null) return false; return remainder != null ? remainder.equals(rounded.remainder) : rounded.remainder == null; } @Override public int hashCode() { int result = integer != null ? integer.hashCode() : 0; result = 31 * result + (remainder != null ? remainder.hashCode() : 0); return result; } @Override public String toString() { return new StringJoiner(", ", Rounded.class.getSimpleName() + "[", "]") .add("integer=" + integer) .add("remainder=" + remainder) .toString(); } }
29.964286
103
0.647199
9e21b982fd106551931c668af9f928f8387e68c1
2,095
package net.teamfruit.bnnwidget.component; import javax.annotation.Nonnull; import net.teamfruit.bnnwidget.OverridablePoint; import net.teamfruit.bnnwidget.WEvent; import net.teamfruit.bnnwidget.compat.OpenGL; import net.teamfruit.bnnwidget.position.Area; import net.teamfruit.bnnwidget.position.Coord; import net.teamfruit.bnnwidget.position.Point; import net.teamfruit.bnnwidget.position.R; import net.teamfruit.bnnwidget.render.RenderOption; import net.teamfruit.bnnwidget.render.WRenderer; /** * テキストラベル選択肢コンポーネントです * @author TeamFruit */ public class MSelectLabel extends MSelect<String> { /** * テキストラベル */ protected final @Nonnull MLabel field; private @Nonnull StringSelector selector = new StringSelector(); /** * 文字列セレクターを設定 * @param selector ボタンセレクター */ public void setSelector(final @Nonnull StringSelector selector) { this.selector = selector; } /** * 文字列セレクター */ @Override protected @Nonnull Selector<String> getSelector() { return this.selector; } public MSelectLabel(final @Nonnull R position, final float buttonwidth) { super(position, buttonwidth); add(this.field = new MLabel(new R(Coord.left(this.buttonwidth), Coord.right(this.buttonwidth), Coord.top(0), Coord.bottom(0))) { @Override public void draw(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final float frame, final float popacity, final @Nonnull RenderOption opt) { final Area a = getGuiPosition(pgp); WRenderer.startShape(); OpenGL.glColor4f(0f, 0f, 0f, .4f); draw(a); super.draw(ev, pgp, p, frame, popacity, opt); } @Override protected void onTextChanged(final @Nonnull String oldText) { onChanged(oldText, getText()); } }); } /** * 選択が変更された際に呼ばれます * @param widget ボタン */ @OverridablePoint protected void onChanged(final @Nonnull String oldText, final @Nonnull String newText) { } @Override protected void initWidget() { setText(getSelector().get()); } @Override public @Nonnull MSelectLabel setText(final @Nonnull String text) { this.field.setText(text); return this; } }
26.1875
170
0.734606
428df72d6aebb9a57dac90954eed0baf77e4c4c4
91
package org.albianj.security; public enum MACStyle { MD5, SHA1, SHA256, SHA384, SHA512 }
15.166667
34
0.747253
e4daf1acc680c66c45956f334f23b4482aa270f1
448
package com.ceiba.itemreserva.servicio; import com.ceiba.itemreserva.puerto.repositorio.RepositorioItemReserva; public class ServicioEliminarItemReserva { private final RepositorioItemReserva repositorioItemReserva; public ServicioEliminarItemReserva(RepositorioItemReserva repositorioItemReserva) { this.repositorioItemReserva = repositorioItemReserva; } public void ejecutar(Long id) { this.repositorioItemReserva.eliminar(id); } }
26.352941
84
0.841518
8d6d8816b929223c1da287e56ce59f6768ee83d3
565
public class Henkilo { private String nimi; private Lemmikki lemmikki; public Henkilo(String nimi, Lemmikki lemmikki) { this.nimi = nimi; this.lemmikki = lemmikki; } public Henkilo(String nimi) { this(nimi, new Lemmikki("Karvinen", "kissa")); } public Henkilo() { this("Caliban", new Lemmikki("Tuntematon", "mielikuvituskaveri")); } @Override public String toString() { return this.nimi + ", kaverina" + this.lemmikki.getNimi() + ", joka on " + this.lemmikki.getRotu(); } }
21.730769
107
0.60354
d17d9a3cdf064946be7777134ca992a84cb69461
23,696
/* * Copyright (C) 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.gmaven.runtime.support.stubgen.model; import org.codehaus.gmaven.runtime.support.stubgen.UnexpectedNodeException; import org.codehaus.gmaven.runtime.support.stubgen.parser.Node; import org.codehaus.gmaven.runtime.support.stubgen.parser.Parser; import org.codehaus.gmaven.runtime.support.stubgen.parser.ParserFactory; import org.codehaus.gmaven.runtime.support.stubgen.parser.SourceType; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.nio.charset.Charset; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; /** * Provides support for {@link ModelFactory} implementations. * * @version $Id$ * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> */ public abstract class ModelFactorySupport implements ModelFactory { protected final ParserFactory factory; protected Parser parser; protected Node lastNode; protected SourceDef source; protected ClassDef clazz; protected ModelFactorySupport(final ParserFactory factory) { assert factory != null; this.factory = factory; } public SourceDef create(final URL input) throws Exception { return create(input, Charset.defaultCharset().name()); } public SourceDef create(final URL input, final SourceType type) throws Exception { return create(input, Charset.defaultCharset().name(), type); } public SourceDef create(final URL input, final String encoding) throws Exception { assert input != null; return create(input, encoding, SourceType.forURL(input)); } public SourceDef create(final URL input, final String encoding, final SourceType type) throws Exception { assert input != null; assert type != null; // Setup the root model element source = createRoot(input, type); // Reset internal state lastNode = null; clazz = null; // Create a new parser for the source type parser = factory.create(source.getType()); // Parse the source Reader reader; if (encoding != null) { reader = new BufferedReader(new InputStreamReader(input.openStream(), encoding)); } else { reader = new BufferedReader(new InputStreamReader(input.openStream())); } Node node; try { node = parser.parse(reader, input.toExternalForm()); } finally { reader.close(); } // Process the tree process(node); return source; } protected SourceDef createRoot(final URL input, final SourceType type) { assert input != null; assert type != null; SourceDef def = new SourceDef(); def.setUrl(input); def.setType(type); addDefaultImports(def); return def; } protected abstract void addDefaultImports(final SourceDef model); // // Processing // protected void process(Node node) { assert node != null; while (node != null) { if (node.is("PACKAGE_DEF")) { packageDef(node); } else if (node.is(new String[] { "STATIC_IMPORT", "IMPORT" })) { importDef(node); } else if (node.is("CLASS_DEF")) { classDef(node); } else if (node.is("INTERFACE_DEF")) { interfaceDef(node); } else if (node.is("METHOD_DEF")) { methodDef(node); } else if (node.is("ENUM_DEF")) { enumDef(node); } else if (node.is("ANNOTATION_DEF")) { annotationDef(node); } else { // everything else should be some sort of statement source.addStatement(node); } node = node.nextSibling(); } } protected void packageDef(final Node parent) { assert parent != null; PackageDef def = new PackageDef(); Node node = parent.firstChild(); node = node.skip("ANNOTATIONS"); String name = qualifiedName(node); def.setName(name); source.setPackage(def); } protected void importDef(final Node parent) { assert parent != null; ImportDef def = new ImportDef(); if (parent.is("STATIC_IMPORT")) { // import is like "import static foo" def.setStatic(true); } Node node = parent.firstChild(); if (node.is("LITERAL_as")) { // import is like "import foo as bar" node = node.firstChild(); Node aliasNode = node.nextSibling(); def.setAlias(identifier(aliasNode)); } if (node.isLeaf()) { // import is like "import Foo" def.setType(identifier(node)); } else { Node packageNode = node.firstChild(); String packageName = qualifiedName(packageNode); def.setPackage(packageName); Node nameNode = packageNode.nextSibling(); if (nameNode.is("STAR")) { // import is like "import foo.*" def.setWildcard(true); } else { String name = identifier(nameNode); // import is like "import foo.Bar" def.setType(name); } } source.addImport(def); } protected void interfaceDef(final Node parent) { assert parent != null; InterfaceDef def = new InterfaceDef(); clazz = def; Node node = parent.firstChild(); node = modifiers(def, node); node = name(def, node); if (node.is("EXTENDS_CLAUSE")) { def.getImplements().addAll(interfaces(node)); node = node.nextSibling(); } javadocs(def, parent); objectBlock(node); source.addClass(def); } protected void classDef(final Node parent) { assert parent != null; ClassDef def = new ClassDef(); def.addImplements("groovy.lang.GroovyObject"); clazz = def; Node node = parent.firstChild(); node = modifiers(def, node); node = name(def, node); if (node.is("TYPE_PARAMETERS")) { // // FIXME: Support generics // node = node.nextSibling(); } if (node.is("EXTENDS_CLAUSE")) { def.setSuperClass(type(node)); node = node.nextSibling(); } if (node.is("IMPLEMENTS_CLAUSE")) { def.getImplements().addAll(interfaces(node)); node = node.nextSibling(); } javadocs(def, parent); objectBlock(node); source.addClass(def); } protected void enumDef(final Node parent) { assert parent != null; parent.ensure("ENUM_DEF"); EnumDef def = new EnumDef(); clazz = def; Node node = parent.firstChild(); node = modifiers(def, node); node = name(def, node); if (node.is("TYPE_PARAMETERS")) { // // FIXME: Support generics // node = node.nextSibling(); } if (node.is("EXTENDS_CLAUSE")) { def.setSuperClass(type(node)); node = node.nextSibling(); } if (node.is("IMPLEMENTS_CLAUSE")) { def.getImplements().addAll(interfaces(node)); node = node.nextSibling(); } javadocs(def, parent); objectBlock(node); source.addClass(def); } protected void annotationDef(final Node parent) { assert parent != null; parent.ensure("ANNOTATION_DEF"); AnnotationDef def = new AnnotationDef(); clazz = def; Node node = parent.firstChild(); node = modifiers(def, node); node = name(def, node); if (node.is("TYPE_PARAMETERS")) { // // FIXME: Support generics // node = node.nextSibling(); } if (node.is("EXTENDS_CLAUSE")) { def.getImplements().addAll(interfaces(node)); node = node.nextSibling(); } javadocs(def, parent); objectBlock(node); source.addClass(def); } protected void objectBlock(final Node parent) { assert parent != null; parent.ensure("OBJBLOCK"); for (Node node = parent.firstChild(); node != null; node = node.nextSibling()) { if (node.is("OBJBLOCK")) { objectBlock(node); } else if (node.is("METHOD_DEF")) { methodDef(node); } else if (node.is("ANNOTATION_FIELD_DEF")) { annotationFieldDef(node); } else if (node.is("CTOR_IDENT")) { constructorDef(node); } else if (node.is("VARIABLE_DEF")) { fieldDef(node); } else if (node.is("ENUM_DEF")) { enumDef(node); } else if (node.is("ENUM_CONSTANT_DEF")) { enumConstantDef(node); } else if (node.is(new String[] { "STATIC_INIT", "INSTANCE_INIT" })) { // Ignore } else { throw new UnexpectedNodeException(node); } } } protected void constructorDef(final Node parent) { assert parent != null; ConstructorDef def = new ConstructorDef(); Node node = parent.firstChild(); node = modifiers(def, node); node = parameters(def, node); node = throwz(def, node); superParameters(def, node); javadocs(def, parent); clazz.addConstructor(def); } protected void superParameters(final ConstructorDef target, final Node parent) { assert target != null; assert parent != null; Node node = parent; if (node.is("SLIST")) { node = node.firstChild(); if (node != null) { if (node.is(new String[] { "SUPER_CTOR_CALL", "CTOR_CALL" })) { if (node.is("SUPER_CTOR_CALL")) { target.setSuperType(ConstructorDef.SUPER); } else { target.setSuperType(ConstructorDef.THIS); } node = node.firstChild(); node.ensure("ELIST"); if (!node.isLeaf()) { node = node.firstChild(); // Pull off EXPR siblings do { superParameter(target, node); node = node.nextSibling(); } while (node != null); } // else we have a super() with-out/params } } } } protected void superParameter(final ConstructorDef target, final Node parent) { assert parent != null; parent.ensure("EXPR"); Node node = parent.firstChild(); SuperParameterDef def = new SuperParameterDef(); if (node.is("TYPECAST")) { node = node.firstChild(); assert node != null; node.ensure("TYPE"); def.setType(type(node)); } else if (node.is("LITERAL_as")) { node = node.firstChild(); assert node != null; node = node.nextSibling(); assert node != null; node.ensure("TYPE"); def.setType(type(node)); } else if (node.is("LITERAL_new")) { node = node.firstChild(); assert node != null; def.setType(type(node)); } else if (node.is(new String[] { "LITERAL_true", "LITERAL_false" })) { def.setType(TypeDef.BOOLEAN); } else if (node.is("STRING_LITERAL")) { def.setType(TypeDef.STRING); } else if (node.is("NUM_INT")) { def.setType(TypeDef.INT); } else if (node.is("NUM_LONG")) { def.setType(TypeDef.LONG); } else if (node.is("NUM_FLOAT")) { def.setType(TypeDef.FLOAT); } else if (node.is("NUM_DOUBLE")) { def.setType(TypeDef.DOUBLE); } else if (node.is("NUM_BIG_INT")) { def.setType(TypeDef.BIG_INT); } else if (node.is("NUM_BIG_DECIMAL")) { def.setType(TypeDef.BIG_DECIMAL); } else if (node.is("STRING_CONSTRUCTOR")) { def.setType(TypeDef.STRING); } else if (node.is("IDENT")) { // Could be a reference to parameters String ident = node.text(); Set parameters = target.getParameters(); if (!parameters.isEmpty()) { Iterator iter = parameters.iterator(); while (iter.hasNext()) { ParameterDef param = (ParameterDef)iter.next(); String name = param.getName(); if (name != null && name.equals(ident)) { def.setType(param.getType()); break; } } } } else { // Lets just assume the parser has done its job, but we don't have type information // so all we can do is use a null value w/o any cast // throw new UnexpectedNodeException(node); } target.addSuperParameter(def); } protected void methodDef(final Node parent) { assert parent != null; MethodDef def = new MethodDef(); Node node = parent.firstChild(); if (node.is("TYPE_PARAMETERS")) { // // FIXME: Support generics // node = node.nextSibling(); } node = modifiers(def, node); if (node.is("TYPE")) { def.setReturns(type(node)); node = node.nextSibling(); } else { def.setReturns(new TypeDef()); } node = name(def, node); node = parameters(def, node); node = throwz(def, node); // Don't care about the body if (node != null) { node.skip("SLIST"); } javadocs(def, parent); clazz.addMethod(def); } protected void annotationFieldDef(final Node parent) { assert parent != null; // methodDef(parent); MethodDef def = new MethodDef(); Node node = parent.firstChild(); if (node.is("TYPE_PARAMETERS")) { // // FIXME: Support generics // node = node.nextSibling(); } node = modifiers(def, node); if (node.is("TYPE")) { def.setReturns(type(node)); node = node.nextSibling(); } else { def.setReturns(new TypeDef()); } // // TODO: Support "default" // node = name(def, node); javadocs(def, parent); clazz.addMethod(def); } protected void fieldDef(final Node parent) { assert parent != null; FieldDef def = new FieldDef(); Node node = parent.firstChild(); node = modifiers(def, node); if (node.is("TYPE")) { def.setType(type(node)); node = node.nextSibling(); } else { def.setType(new TypeDef()); } name(def, node); javadocs(def, parent); clazz.addField(def); } protected void enumConstantDef(final Node parent) { assert parent != null; parent.ensure("ENUM_CONSTANT_DEF"); assert clazz instanceof EnumDef; EnumDef def = (EnumDef)clazz; Node node = parent.firstChild(); if (node.is("ANNOTATIONS")) { node = node.nextSibling(); } String name = identifier(node); // // TODO: Determine initialization expression // /* Expression init = null; element = element.getNextSibling(); if (element!=null) { init = expression(element); if (isType(ELIST,element)) { if(init instanceof ListExpression && !((ListExpression)init).isWrapped()) { ListExpression le = new ListExpression(); le.addExpression(init); init = le; } } } */ def.addConstant(name); } // // Helpers // protected Node name(final NameAware target, final Node node) { assert target != null; assert node != null; target.setName(identifier(node)); return node.nextSibling(); } protected Node modifiers(final ModifiersAware target, final Node parent) { assert parent != null; // Skip unless this is a modifiers node if (!parent.is("MODIFIERS")) { return parent; } ModifiersDef def = new ModifiersDef(); for (Node node = parent.firstChild(); node != null; node = node.nextSibling()) { if (node.is(new String[] { "STRICTFP", "STATIC_IMPORT" })) { // ignore } if (node.is("ANNOTATION")) { // // FIXME: Add annotation support // } else if (node.is("LITERAL_private")) { def.add(ModifiersDef.PRIVATE); } else if (node.is("LITERAL_protected")) { def.add(ModifiersDef.PROTECTED); } else if (node.is("LITERAL_public")) { def.add(ModifiersDef.PUBLIC); } else if (node.is("ABSTRACT")) { def.add(ModifiersDef.ABSTRACT); } else if (node.is("FINAL")) { def.add(ModifiersDef.FINAL); } else if (node.is("LITERAL_native")) { def.add(ModifiersDef.NATIVE); } else if (node.is("LITERAL_static")) { def.add(ModifiersDef.STATIC); } else if (node.is("LITERAL_synchronized")) { def.add(ModifiersDef.SYNCHRONIZED); } else if (node.is("LITERAL_transient")) { def.add(ModifiersDef.TRANSIENT); } else if (node.is("LITERAL_volatile")) { def.add(ModifiersDef.VOLATILE); } else { throw new UnexpectedNodeException(node); } } target.getModifiers().merge(def); return parent.nextSibling(); } protected Set interfaces(final Node parent) { assert parent != null; Set set = new LinkedHashSet(); for (Node node = parent.firstChild(); node != null; node = node.nextSibling()) { set.add(type(node)); } return set; } protected Node throwz(final ThrowsAware target, final Node parent) { assert target != null; // assert parent != null; if (parent == null) { return null; } // The throw statement is optional, so skip if not present if (!parent.is("LITERAL_throws")) { return parent; } Node node = parent.firstChild(); if (node != null) { do { target.getThrows().add(type(node)); node = node.nextSibling(); } while (node != null); } return parent.nextSibling(); } protected Node parameters(final ParametersAware target, final Node parent) { assert target != null; assert parent != null; parent.ensure("PARAMETERS"); Node node = parent.firstChild(); if (node != null) { do { target.addParameter(parameter(node)); node = node.nextSibling(); } while (node != null); } return parent.nextSibling(); } protected ParameterDef parameter(final Node parent) { assert parent != null; ParameterDef def = new ParameterDef(); Node node = parent.firstChild(); node = modifiers(def, node); if (node.is("TYPE")) { def.setType(type(node)); node = node.nextSibling(); } else { def.setType(new TypeDef()); } def.setName(identifier(node)); return def; } protected TypeDef type(final Node parent) { assert parent != null; TypeDef def = new TypeDef(); Node node; if (parent.is(new String[] { "IDENT", "DOT" })) { node = parent; } else { node = parent.firstChild(); } if (node != null) { int dim = 0; // Determine array dimentions if there are any while (node.is("ARRAY_DECLARATOR")) { node = node.firstChild(); dim++; } def.setDimensions(dim); def.setName(qualifiedName(node)); } return def; } private static JavaDocParser javaDocParser = new JavaDocParser(); protected void javadocs(final JavaDocAware target, final Node node) { assert target != null; assert node != null; // Get the snippet between nodes String text = parser.snippet(lastNode, node); // Remember where we last looked lastNode = node; // Attempt to parse out the docs JavaDocDef def = javaDocParser.parse(text); if (def != null) { target.setJavaDoc(def); } } protected String qualifiedName(final Node parent) { assert parent != null; if (parent.is("IDENT")) { return parent.text(); } else if (parent.is("DOT")) { Node node = parent.firstChild(); StringBuffer buff = new StringBuffer(); boolean first = true; for (; node != null; node = node.nextSibling()) { if (first) { first = false; } else { buff.append("."); } buff.append(qualifiedName(node)); } return buff.toString(); } else { return parent.text(); } } protected String identifier(final Node node) { assert node != null; node.ensure("IDENT"); return node.text(); } }
25.925602
109
0.513715
e86b65479eff903f3c7aa7a034a66abbc9b6ebe4
7,657
import java.util.Random; import java.util.concurrent.ConcurrentHashMap; /** * Requests: * An object oriented request based networking protocol * suitable for almost all networking applications */ public class Requests { /** * An interface used for callbacks for when an `error` or `return` is received */ public interface OnResultCallback { /** * When a `return` is received, called from inside parseData() * * @param name the name of the request (the "function" name) * @param data the data received in the `return` */ void onReturn(String name, String data); /** * When an `error` is received, called from inside parseData() * * @param name the name of the request (the "function" name) * @param error the error received in the `error` */ void onError(String name, String error); } /** * An interface containing callbacks for when a request is received */ public interface OnRequestCallback { /** * Called (from inside parseData()) when a request is received * * @param requestID the ID of the request * @param name The name of the request (the "function" name) * @param data The data/parameters associated with the request */ void onRequest(String requestID, String name, String data); } /** * A member that specifies how long the requestID should be * 10 is recommended but can be changed to your choosing * Smaller numbers reduce the size of requests, but are less random and can cause issues */ private static final int requestIDLength = 10; /** * How many unfulfilled requests to save in memory * 100 is recommended for a client * 10-50 is recommended for a server (as more have the possibility to clog up memory) */ private static final int awaitingRequestsLimit = 100; /** * A member that holds unfulfilled requests in memory so callbacks can be later executed */ private ConcurrentHashMap<String, OnResultCallback> createdRequests = new ConcurrentHashMap<>(); /** * The callback to call when a request is received * Called from within parseData() */ private OnRequestCallback onRequestCallback; /** * A callback that is called when there is a requestID that is not in createdRequests * Called from within parseData() * This may be called when a request is returned but null was passed to generateRequest() */ private OnResultCallback onUnknownRequestID; /** * The constructor for Requests that initializes the necessary fields * * @param onRequestCallback The callback to call when a request is received (can be null) * @param onDataWithUnknownRequestID The callback to call from within parseData() when an * unknown requestID is in a received `return` or `error` * See the member's javadoc for more information */ public Requests(OnRequestCallback onRequestCallback, OnResultCallback onDataWithUnknownRequestID) { this.onRequestCallback = onRequestCallback; this.onUnknownRequestID = onDataWithUnknownRequestID; } /** * A simple and efficient method to find the nth index of a comma in a string * * @param str the string to search * @param n the nth occurrence of a comma to return the index of (starting at 1) * @return the index of the nth occurrence of a comma in the string */ private int findNthComma(String str, int n) { int counter = 0; for (int i = 0; i < str.length(); ++i) { if (str.charAt(i) == ',' && ++counter == n) return i; } return -1; } /** * This method is used to generate a `return` to send after receiving a `request` * * @param requestID The requestID supplied by the OnRequestCallback * @param name The name provided by the OnRequestCallback * @param data The data to return * @return A string that is suitable to send following the Requests protocol */ public String generateReturn(String requestID, String name, String data) { return "return," + requestID + "," + name + "," + data; } /** * This method is used to generate an `error` to send after receiving a `request` * * @param requestID The requestID supplied by the OnRequestCallback * @param name The name provided by the OnRequestCallback * @param error The error encountered while trying to process the request, as a string * @return A string that is suitable to send following the Requests protocol */ public String generateError(String requestID, String name, String error) { return "error," + requestID + "," + name + "," + error; } /** * This method creates a `request` to send * It also loads a callback into memory for when (and if) the request is fulfilled * * @param name The name of the "function" the request is calling * @param data The data/parameters of the request * @param callback The callback to call when the request is fulfilled (can be null) * @return A string that is suitable to send following the Requests protocol */ public String generateRequest(String name, String data, OnResultCallback callback) { StringBuilder requestID = new StringBuilder(requestIDLength); Random random = new Random(); for (int i = 0; i < requestIDLength; ++i) { requestID.append((char) (random.nextInt(('z' - 'a') + 1) + 'a')); } if (callback != null && createdRequests.size() <= awaitingRequestsLimit) { createdRequests.putIfAbsent(requestID.toString(), callback); } return "request," + requestID.toString() + "," + name + "," + data; } /** * A method that parses received data and deals with it accordingly * Calls any necessary callbacks * * @param rawData A string of the data received from the other end * @return true if the data received was valid (follows Requests protocol), false otherwise */ public boolean parseData(String rawData) { int index1 = findNthComma(rawData, 1), index2 = findNthComma(rawData, 2), index3 = findNthComma(rawData, 3); String type, requestID, name, data; try { type = rawData.substring(0, index1); requestID = rawData.substring(index1 + 1, index2); name = rawData.substring(index2 + 1, index3); data = rawData.substring(index3 + 1); } catch (StringIndexOutOfBoundsException e) { return false; } switch (type) { case "request": if (onRequestCallback != null) onRequestCallback.onRequest(requestID, name, data); case "return": OnResultCallback returnCallback = createdRequests.remove(requestID); if (returnCallback != null) returnCallback.onReturn(name, data); else if (onUnknownRequestID != null) onUnknownRequestID.onReturn(name, data); case "error": OnResultCallback errorCallback = createdRequests.remove(requestID); if (errorCallback != null) errorCallback.onError(name, data); else if (onUnknownRequestID != null) onUnknownRequestID.onError(name, data); } return true; } }
41.84153
102
0.629881
1e213d2254b953a6a674a2d02405b9f35e4e0d7b
2,980
package br.com.zup.proposta.bloqueio; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import br.com.zup.proposta.cartao.CartaoClienteFeing; import br.com.zup.proposta.cartao.CartaoModel; import br.com.zup.proposta.cartao.CartaoRepository; import br.com.zup.proposta.compartilhado.ExecutorTransacao; import feign.FeignException; @RestController @RequestMapping("/bloqueio") public class BloqueioController { @Autowired private CartaoRepository cartaoRepository; @Autowired private ExecutorTransacao executorTransacao; @Autowired private CartaoClienteFeing cartaoClienteFeing; private final Logger logger = LoggerFactory.getLogger(BloqueioController.class); @PostMapping("/{idCartao}") public ResponseEntity<?> bloquearCartao(@PathVariable("idCartao") String id, HttpServletRequest servletRequest, @RequestBody @Valid BloqueioRequest request){ Optional<CartaoModel> cartao = cartaoRepository.findById(id); if(cartao.isEmpty()){ logger.warn("Cartão {} inexistente=", id); return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cartão inexistente"); } if(cartao.get().verificaBloqueado()) { logger.warn("Cartão {} já está bloqueado=", id); return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("Cartão já está bloqueado"); } BloqueioModel bloqueio = new BloqueioModel(servletRequest.getLocalAddr(), servletRequest.getHeader("User-Agent"), cartao.get()); bloquearCartao(bloqueio, cartao.get(), request); logger.info("Cartão bloqueado com sucesso"); return ResponseEntity.ok().build(); } /* -- Notificando o sistema legado do bloqueio do nosso cartão-- Quando o retorno do sistema bancário retornar sucesso (status code na faixa 200) = "BLOQUEADO". Quando o retorno do sistema bancário retornar erro (status code na faixa 400 ou 500) = não alterar o estado do cartão. */ private void bloquearCartao(BloqueioModel bloqueio, CartaoModel cartao, BloqueioRequest request) { try { cartaoClienteFeing.bloqueioCartao(cartao.getId(), request); cartao.setBloqueio(bloqueio); executorTransacao.atualizaEComita(cartao); } catch (FeignException e) { throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY,"O bloqueio falhou!"); } } }
38.701299
119
0.766779
5eb481df5334b0acc54ed15c5877d151c2961d8f
524
package com.packege_new; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class test { WebDriver wd; @BeforeClass public void setUP() { wd = new ChromeDriver(); } @Test public void opengoogleTest() { wd.get("https://google.com/"); } @AfterClass public void tearDown() { wd.quit(); } }
16.375
47
0.662214
31d9e4ef9abb173f947a7a88a8b8870a597901cb
12,999
/* LinkingKeyEventProfile.java Copyright (c) 2016 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.deviceplugin.linking.linking.profile; import android.content.Intent; import android.os.Bundle; import android.util.Log; import org.deviceconnect.android.deviceplugin.linking.lib.BuildConfig; import org.deviceconnect.android.deviceplugin.linking.LinkingApplication; import org.deviceconnect.android.deviceplugin.linking.LinkingDestroy; import org.deviceconnect.android.deviceplugin.linking.LinkingDevicePluginService; import org.deviceconnect.android.deviceplugin.linking.linking.LinkingDevice; import org.deviceconnect.android.deviceplugin.linking.linking.LinkingDeviceManager; import org.deviceconnect.android.deviceplugin.linking.linking.service.LinkingDeviceService; import org.deviceconnect.android.event.Event; import org.deviceconnect.android.event.EventError; import org.deviceconnect.android.event.EventManager; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.profile.KeyEventProfile; import org.deviceconnect.android.profile.api.DConnectApi; import org.deviceconnect.android.profile.api.DeleteApi; import org.deviceconnect.android.profile.api.GetApi; import org.deviceconnect.android.profile.api.PutApi; import org.deviceconnect.message.DConnectMessage; import java.util.List; public class LinkingKeyEventProfile extends KeyEventProfile implements LinkingDestroy { private static final String TAG = "LinkingPlugIn"; /** * Attribute: {@value} . */ public static final String ATTRIBUTE_ON_KEY_CHANGE = "onKeyChange"; /** * Parameter: {@value} . */ public static final String PARAM_STATE = "state"; public LinkingKeyEventProfile() { addApi(mGetOnDown); addApi(mPutOnDown); addApi(mDeleteOnDown); addApi(mGetOnKeyChangeApi); addApi(mPutOnKeyChangeApi); addApi(mDeleteOnKeyChangeApi); } private final LinkingDeviceManager.OnButtonEventListener mListener = new LinkingDeviceManager.OnButtonEventListener() { @Override public void onButtonEvent(final LinkingDevice device, final int keyCode) { notifyKeyEvent(device, keyCode); } }; private final DConnectApi mGetOnDown = new GetApi() { @Override public String getAttribute() { return ATTRIBUTE_ON_DOWN; } @Override public boolean onRequest(final Intent request, final Intent response) { final LinkingDevice device = getDevice(response); if (device == null) { return true; } final LinkingDeviceManager deviceManager = getLinkingDeviceManager(); deviceManager.enableListenButtonEvent(device, new OnKeyEventListenerImpl(device) { @Override public void onCleanup() { deviceManager.disableListenButtonEvent(mDevice, this); } @Override public void onTimeout() { if (mCleanupFlag) { return; } MessageUtils.setTimeoutError(response); sendResponse(response); } @Override public void onButtonEvent(final LinkingDevice device, final int keyCode) { if (mCleanupFlag || !mDevice.equals(device)) { return; } setKeyEvent(response, createKeyEvent(keyCode, System.currentTimeMillis())); sendResponse(response); cleanup(); } }); return false; } }; private final DConnectApi mPutOnDown = new PutApi() { @Override public String getAttribute() { return ATTRIBUTE_ON_DOWN; } @Override public boolean onRequest(final Intent request, final Intent response) { LinkingDevice device = getDevice(response); if (device == null) { return true; } EventError error = EventManager.INSTANCE.addEvent(request); if (error == EventError.NONE) { getLinkingDeviceManager().enableListenButtonEvent(device, mListener); setResult(response, DConnectMessage.RESULT_OK); } else if (error == EventError.INVALID_PARAMETER) { MessageUtils.setInvalidRequestParameterError(response); } else { MessageUtils.setUnknownError(response); } return true; } }; private DConnectApi mDeleteOnDown = new DeleteApi() { @Override public String getAttribute() { return ATTRIBUTE_ON_DOWN; } @Override public boolean onRequest(final Intent request, final Intent response) { LinkingDevice device = getDevice(response); if (device == null) { return true; } EventError error = EventManager.INSTANCE.removeEvent(request); if (error == EventError.NONE) { if (isEmptyEventList(device)) { getLinkingDeviceManager().disableListenButtonEvent(device, mListener); } setResult(response, DConnectMessage.RESULT_OK); } else if (error == EventError.INVALID_PARAMETER) { MessageUtils.setInvalidRequestParameterError(response); } else { MessageUtils.setUnknownError(response); } return true; } }; private final DConnectApi mGetOnKeyChangeApi = new GetApi() { @Override public String getAttribute() { return ATTRIBUTE_ON_KEY_CHANGE; } @Override public boolean onRequest(final Intent request, final Intent response) { final LinkingDevice device = getDevice(response); if (device == null) { return true; } final LinkingDeviceManager deviceManager = getLinkingDeviceManager(); deviceManager.enableListenButtonEvent(device, new OnKeyEventListenerImpl(device) { @Override public void onCleanup() { deviceManager.disableListenButtonEvent(mDevice, this); } @Override public void onTimeout() { if (mCleanupFlag) { return; } MessageUtils.setTimeoutError(response); sendResponse(response); } @Override public void onButtonEvent(final LinkingDevice device, final int keyCode) { if (mCleanupFlag || !mDevice.equals(device)) { return; } Bundle keyEvent = createKeyEvent(keyCode, System.currentTimeMillis()); keyEvent.putString(PARAM_STATE, "down"); setKeyEvent(response, keyEvent); sendResponse(response); cleanup(); } }); return false; } }; private final DConnectApi mPutOnKeyChangeApi = new PutApi() { @Override public String getAttribute() { return ATTRIBUTE_ON_KEY_CHANGE; } @Override public boolean onRequest(final Intent request, final Intent response) { LinkingDevice device = getDevice(response); if (device == null) { return true; } EventError error = EventManager.INSTANCE.addEvent(request); if (error == EventError.NONE) { getLinkingDeviceManager().enableListenButtonEvent(device, mListener); setResult(response, DConnectMessage.RESULT_OK); } else if (error == EventError.INVALID_PARAMETER) { MessageUtils.setInvalidRequestParameterError(response); } else { MessageUtils.setUnknownError(response); } return true; } }; private final DConnectApi mDeleteOnKeyChangeApi = new DeleteApi() { @Override public String getAttribute() { return ATTRIBUTE_ON_KEY_CHANGE; } @Override public boolean onRequest(final Intent request, final Intent response) { LinkingDevice device = getDevice(response); if (device == null) { return true; } EventError error = EventManager.INSTANCE.removeEvent(request); if (error == EventError.NONE) { if (isEmptyEventList(device)) { getLinkingDeviceManager().disableListenButtonEvent(device, mListener); } setResult(response, DConnectMessage.RESULT_OK); } else if (error == EventError.INVALID_PARAMETER) { MessageUtils.setInvalidRequestParameterError(response); } else { MessageUtils.setUnknownError(response); } return true; } }; @Override public void onDestroy() { if (BuildConfig.DEBUG) { Log.i(TAG, "LinkingKeyEventProfile#destroy: " + getService().getId()); } getLinkingDeviceManager().disableListenButtonEvent(getDevice(), mListener); } private boolean isEmptyEventList(final LinkingDevice device) { List<Event> keyDownEvents = EventManager.INSTANCE.getEventList( device.getBdAddress(), PROFILE_NAME, null, ATTRIBUTE_ON_DOWN); List<Event> keyChangeEvents = EventManager.INSTANCE.getEventList( device.getBdAddress(), PROFILE_NAME, null, ATTRIBUTE_ON_KEY_CHANGE); return keyDownEvents.isEmpty() && keyChangeEvents.isEmpty(); } private LinkingDevice getDevice() { return ((LinkingDeviceService) getService()).getLinkingDevice(); } private LinkingDevice getDevice(final Intent response) { LinkingDevice device = getDevice(); if (!device.isConnected()) { MessageUtils.setIllegalDeviceStateError(response, "device not connected"); return null; } return device; } private Bundle createKeyEvent(final int keyCode) { Bundle keyEvent = new Bundle(); keyEvent.putString(PARAM_ID, String.valueOf(KeyEventProfile.KEYTYPE_STD_KEY + keyCode)); return keyEvent; } private Bundle createKeyEvent(final int keyCode, final long timeStamp) { Bundle keyEvent = createKeyEvent(keyCode); keyEvent.putString(PARAM_CONFIG, "" + timeStamp); return keyEvent; } private void setKeyEvent(final Intent intent, final Bundle keyEvent) { intent.putExtra(PARAM_KEYEVENT, keyEvent); } private void notifyKeyEvent(final LinkingDevice device, final int keyCode) { if (BuildConfig.DEBUG) { Log.d(TAG, "notifyKeyEvent: " + device.getDisplayName() + "[" + keyCode + "]"); } String serviceId = device.getBdAddress(); List<Event> keyDownEvents = EventManager.INSTANCE.getEventList(serviceId, PROFILE_NAME, null, ATTRIBUTE_ON_DOWN); if (keyDownEvents != null && keyDownEvents.size() > 0) { for (Event event : keyDownEvents) { Intent intent = EventManager.createEventMessage(event); setKeyEvent(intent, createKeyEvent(keyCode)); sendEvent(intent, event.getAccessToken()); } } List<Event> keyChangeEvents = EventManager.INSTANCE.getEventList(serviceId, PROFILE_NAME, null, ATTRIBUTE_ON_KEY_CHANGE); if (keyChangeEvents != null) { for (Event event : keyChangeEvents) { Bundle keyEvent = createKeyEvent(keyCode); keyEvent.putString(PARAM_STATE, "down"); Intent intent = EventManager.createEventMessage(event); setKeyEvent(intent, keyEvent); sendEvent(intent, event.getAccessToken()); } } } private LinkingDeviceManager getLinkingDeviceManager() { LinkingApplication app = getLinkingApplication(); return app.getLinkingDeviceManager(); } private LinkingApplication getLinkingApplication() { LinkingDevicePluginService service = (LinkingDevicePluginService) getContext(); return (LinkingApplication) service.getApplication(); } private abstract class OnKeyEventListenerImpl extends TimeoutSchedule implements LinkingDeviceManager.OnButtonEventListener { OnKeyEventListenerImpl(final LinkingDevice device) { super(device); } } }
36.310056
129
0.612432
cc55a1b7cd7931196cc82a239dd27bcd7ccbb7e5
347
package io.sphere.sdk.annotations.processors.generators.examples; /** * */ import io.sphere.sdk.annotations.FactoryMethod; import io.sphere.sdk.annotations.ResourceDraftValue; @ResourceDraftValue(factoryMethods = {@FactoryMethod(parameterNames = {}) }, builderReturnsDslClass = false) public class ExampleWithBuilderReturnsInterfaceDraft { }
26.692308
108
0.806916
437e8de4460f00865d7f86659728c8bc36f96c21
2,274
package ru.bgbrakhi.carseller.models; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.Objects; @Entity @Table(name = "ref_carmodel") public class CarModel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "id_cartype") private CarType cartype; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "id_carmark") private CarMark carmark; @Column(name = "name", nullable = false) @NotNull private String name; public CarModel() { } public CarModel(String name) { this.name = name; } public CarModel(CarType cartype, CarMark carmark, @NotNull String name) { this.cartype = cartype; this.carmark = carmark; this.name = name; } public long getId() { return id; } public void setId(long id) { this.id = id; } public CarType getCartype() { return cartype; } public void setCartype(CarType cartype) { this.cartype = cartype; } public CarMark getCarmark() { return carmark; } public void setCarmark(CarMark carmark) { this.carmark = carmark; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "CarModel{" + "id=" + id + ", cartype=" + cartype + ", carmark=" + carmark + ", name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CarModel carModel = (CarModel) o; return id == carModel.id && Objects.equals(cartype, carModel.cartype) && Objects.equals(carmark, carModel.carmark) && Objects.equals(name, carModel.name); } @Override public int hashCode() { return Objects.hash(id, cartype, carmark, name); } }
22.07767
77
0.55277
2c00e35d1c00225ef23923251ab1dfc12de6fff7
211
package vetcilinic.Repositories; import org.springframework.data.jpa.repository.JpaRepository; import vetcilinic.Entities.Storage; public interface StorageRepository extends JpaRepository<Storage,Integer> { }
26.375
75
0.853081
2b5293278b78ee9aed55246ca089bcf63aaff98e
15,729
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.appium.uiautomator2.handler; import android.os.SystemClock; import android.util.Log; import android.util.LongSparseArray; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.MotionEvent.PointerCoords; import android.view.MotionEvent.PointerProperties; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import io.appium.uiautomator2.handler.request.SafeRequestHandler; import io.appium.uiautomator2.http.AppiumResponse; import io.appium.uiautomator2.http.IHttpRequest; import io.appium.uiautomator2.server.WDStatus; import io.appium.uiautomator2.utils.Logger; import io.appium.uiautomator2.utils.w3c.ActionsHelpers; import io.appium.uiautomator2.utils.w3c.ActionsHelpers.InputEventParams; import io.appium.uiautomator2.utils.w3c.ActionsHelpers.KeyInputEventParams; import io.appium.uiautomator2.utils.w3c.ActionsHelpers.MotionInputEventParams; import io.appium.uiautomator2.utils.w3c.ActionsParseException; import io.appium.uiautomator2.utils.w3c.W3CKeyCode; import static io.appium.uiautomator2.utils.InteractionUtils.injectEventSync; import static io.appium.uiautomator2.utils.w3c.ActionsHelpers.actionsToInputEventsMapping; import static io.appium.uiautomator2.utils.w3c.ActionsHelpers.getPointerAction; import static io.appium.uiautomator2.utils.w3c.ActionsHelpers.metaKeysToState; import static io.appium.uiautomator2.utils.w3c.ActionsHelpers.toolTypeToInputSource; public class W3CActions extends SafeRequestHandler { private static final String TAG = W3CActions.class.getSimpleName(); private static final KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD); private static final List<Integer> HOVERING_ACTIONS = Arrays.asList( MotionEvent.ACTION_HOVER_ENTER, MotionEvent.ACTION_HOVER_EXIT, MotionEvent.ACTION_HOVER_MOVE ); public W3CActions(String mappedUri) { super(mappedUri); } private static PointerProperties[] filterPointerProperties( final List<MotionInputEventParams> motionEventsParams, final boolean shouldHovering) { final List<PointerProperties> result = new ArrayList<>(); for (final MotionInputEventParams eventParams : motionEventsParams) { if (shouldHovering && HOVERING_ACTIONS.contains(eventParams.actionCode)) { result.add(eventParams.properties); } else if (!shouldHovering && !HOVERING_ACTIONS.contains(eventParams.actionCode)) { result.add(eventParams.properties); } } return result.toArray(new PointerProperties[result.size()]); } private static PointerCoords[] filterPointerCoordinates( final List<MotionInputEventParams> motionEventsParams, final boolean shouldHovering) { final List<PointerCoords> result = new ArrayList<>(); for (final MotionInputEventParams eventParams : motionEventsParams) { if (shouldHovering && HOVERING_ACTIONS.contains(eventParams.actionCode)) { result.add(eventParams.coordinates); } else if (!shouldHovering && !HOVERING_ACTIONS.contains(eventParams.actionCode)) { result.add(eventParams.coordinates); } } return result.toArray(new PointerCoords[result.size()]); } /** * Android handler for <a href="https://github.com/jlipps/simple-wd-spec#perform-actions">W3C actions endpoint</a> * <p> * All input source types are supported as well as multi-touch gestures. * <p> * The following additional item options are supported for <b>pointer</b> source: * <ul> * <li>pressure - A value in range [0.0, 1.0], which defines pointer pressure, * where 1.0 is the normal pressure (the default value) and 0.0 means no pressure.</li> * <li>size - A normalized value that describes the approximate size of the pointer touch area * in relation to the maximum detectable size of the device. * It represents some approximation of the area of the screen being * pressed; the actual value in pixels corresponding to the * touch is normalized with the device specific range of values * and scaled to a value between 0 and 1 (the default value). * The value of size can be used to determine fat touch events.</li> * </ul> * <p> * Applicable key and meta key codes for <b>key</b> input source can be found in * {@link KeyEvent} documentation. Value transformation to a numeric key code is * done via {@link String#charAt(int)} method call, which means, for example, * that the value <em>"\\u2000"</em> equals to meta key code 0x2000 * {@link KeyEvent#META_CTRL_LEFT_ON}. Meta key codes are also applied to pointer * events, which are happening at the same moment. * <p> * * @param request JSON request formatted according to W3C actions endpoint compilation rules. * @return The standard {@link AppiumResponse} instance with return value or error code inside. */ @Override protected AppiumResponse safeHandle(IHttpRequest request) throws JSONException { try { final JSONArray actions = ActionsHelpers.preprocessActions( (JSONArray) getPayload(request).get("actions") ); if (executeActions(actions)) { return new AppiumResponse(getSessionId(request), WDStatus.SUCCESS, "OK"); } return new AppiumResponse(getSessionId(request), WDStatus.UNKNOWN_ERROR, "Unable to perform W3C actions. Check the logcat output " + "for possible error reports and make sure your input actions chain is valid."); } catch (ActionsParseException e) { Logger.error("Exception while reading JSON: ", e); return new AppiumResponse(getSessionId(request), WDStatus.JSON_DECODER_ERROR, e); } } private boolean injectKeyEvent(KeyInputEventParams eventParam, long startTimestamp, Set<Integer> depressedMetaKeys) { final int keyCode = eventParam.keyCode; if (keyCode <= 0) { depressedMetaKeys.clear(); return true; } final int keyAction = eventParam.keyAction; final W3CKeyCode w3CKeyCode = W3CKeyCode.fromCodePoint(keyCode); if (w3CKeyCode == null) { final KeyEvent[] events = kcm.getEvents(Character.toChars(keyCode)); boolean result = true; for (KeyEvent event : events) { if (event.getAction() == keyAction) { Logger.debug(String.format("Generating KeyEvent for keyAction '%s', keyCode: '%s', metaState: '%s'", keyAction, keyCode, metaKeysToState(depressedMetaKeys))); result &= injectEventSync(new KeyEvent(startTimestamp + eventParam.startDelta, SystemClock.uptimeMillis(), keyAction, event.getKeyCode(), 0, event.getMetaState() | metaKeysToState(depressedMetaKeys), KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0)); } } return result; } final Integer metaCode = w3CKeyCode.toAndroidMetaKeyCode(); if (metaCode != null) { if (keyAction == KeyEvent.ACTION_DOWN) { depressedMetaKeys.add(metaCode); } else { depressedMetaKeys.remove(metaCode); } return true; } Logger.debug(String.format("Generating KeyEvent for keyAction '%s', keyCode: '%s', metaState: '%s'", keyAction, keyCode, metaKeysToState(depressedMetaKeys))); return injectEventSync(new KeyEvent(startTimestamp + eventParam.startDelta, SystemClock.uptimeMillis(), keyAction, w3CKeyCode.getAndroidCodePoint(), 0, metaKeysToState(depressedMetaKeys), KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0)); } private boolean executeActions(final JSONArray actions) throws JSONException { final LongSparseArray<List<InputEventParams>> inputEventsMapping = actionsToInputEventsMapping(actions); final List<Long> allDeltas = new ArrayList<>(); for (int i = 0; i < inputEventsMapping.size(); i++) { allDeltas.add(inputEventsMapping.keyAt(i)); } Collections.sort(allDeltas); long recentTimeDelta = 0; boolean result = true; final Set<Integer> depressedMetaKeys = new HashSet<>(); final long startTimestamp = SystemClock.uptimeMillis(); final LongSparseArray<Integer> motionEventsBalanceByInputSource = new LongSparseArray<>(); for (final Long currentTimeDelta : allDeltas) { final List<InputEventParams> eventParams = inputEventsMapping.get(currentTimeDelta); final LongSparseArray<List<MotionInputEventParams>> motionParamsByInputSource = new LongSparseArray<>(); for (final InputEventParams eventParam : eventParams) { if (eventParam instanceof KeyInputEventParams) { result &= injectKeyEvent((KeyInputEventParams) eventParam, startTimestamp, depressedMetaKeys); } else if (eventParam instanceof MotionInputEventParams) { final int inputSource = toolTypeToInputSource(((MotionInputEventParams) eventParam).properties.toolType); final List<MotionInputEventParams> events = (motionParamsByInputSource.get(inputSource) == null) ? new ArrayList<MotionInputEventParams>() : motionParamsByInputSource.get(inputSource); events.add((MotionInputEventParams) eventParam); motionParamsByInputSource.put(inputSource, events); } } for (int i = 0; i < motionParamsByInputSource.size(); i++) { final int inputSource = (int) motionParamsByInputSource.keyAt(i); final List<MotionInputEventParams> motionEventsParams = motionParamsByInputSource.valueAt(i); final PointerProperties[] nonHoveringProps = filterPointerProperties(motionEventsParams, false); final PointerProperties[] hoveringProps = filterPointerProperties(motionEventsParams, true); final PointerCoords[] nonHoveringCoords = filterPointerCoordinates(motionEventsParams, false); final PointerCoords[] hoveringCoords = filterPointerCoordinates(motionEventsParams, true); for (final MotionInputEventParams motionEventParams : motionEventsParams) { final int actionCode = motionEventParams.actionCode; Integer upDownBalance = motionEventsBalanceByInputSource.get(inputSource); if (upDownBalance == null) { upDownBalance = 0; } switch (actionCode) { case MotionEvent.ACTION_DOWN: { ++upDownBalance; motionEventsBalanceByInputSource.put(inputSource, upDownBalance); final int action = upDownBalance == 1 ? MotionEvent.ACTION_DOWN : getPointerAction(MotionEvent.ACTION_POINTER_DOWN, upDownBalance - 1); result &= injectEventSync(MotionEvent.obtain(startTimestamp + motionEventParams.startDelta, SystemClock.uptimeMillis(), action, action == MotionEvent.ACTION_DOWN ? 1 : upDownBalance, nonHoveringProps, nonHoveringCoords, metaKeysToState(depressedMetaKeys), motionEventParams.button, 1, 1, 0, 0, inputSource, 0)); Log.d(TAG, String.format("Generated MotionEvent for action '%s'", action)); } break; case MotionEvent.ACTION_UP: { if (upDownBalance <= 0) { // ignore unbalanced pointer up actions break; } motionEventsBalanceByInputSource.put(inputSource, upDownBalance); final int action = upDownBalance <= 1 ? MotionEvent.ACTION_UP : getPointerAction(MotionEvent.ACTION_POINTER_UP, upDownBalance - 1); result &= injectEventSync(MotionEvent.obtain(startTimestamp + motionEventParams.startDelta, SystemClock.uptimeMillis(), action, action == MotionEvent.ACTION_UP ? 1 : upDownBalance, nonHoveringProps, nonHoveringCoords, metaKeysToState(depressedMetaKeys), motionEventParams.button, 1, 1, 0, 0, inputSource, 0)); if (upDownBalance > 0) { --upDownBalance; } Log.d(TAG, String.format("Generated MotionEvent for action '%s'", action)); } break; case MotionEvent.ACTION_MOVE: { result &= injectEventSync(MotionEvent.obtain(startTimestamp + motionEventParams.startDelta, SystemClock.uptimeMillis(), actionCode, upDownBalance, nonHoveringProps, nonHoveringCoords, metaKeysToState(depressedMetaKeys), motionEventParams.button, 1, 1, 0, 0, inputSource, 0) ); } break; case MotionEvent.ACTION_HOVER_ENTER: case MotionEvent.ACTION_HOVER_EXIT: case MotionEvent.ACTION_HOVER_MOVE: { result &= injectEventSync(MotionEvent.obtain(startTimestamp + motionEventParams.startDelta, SystemClock.uptimeMillis(), actionCode, hoveringProps.length, hoveringProps, hoveringCoords, metaKeysToState(depressedMetaKeys), 0, 1, 1, 0, 0, inputSource, 0) ); } break; } // switch } // motionEventParams : motionEventsParams } // for i < motionParamsByInputSource.size() SystemClock.sleep(currentTimeDelta - recentTimeDelta); recentTimeDelta = currentTimeDelta; } // currentTimeDelta : allDeltas return result; } }
54.804878
134
0.632399
0ba83d547c5c84d8c6e1e1bb22cd827c5dbe4a45
5,943
/* MIT License Copyright (c) 2019 Michele Maione Permission is hereby granted, free of charge, toE any person obtaining a copy of this software and associated documentation files (the "Software"), toE deal in the Software without restriction, including without limitation the rights toE use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and toE permit persons toE whom the Software is furnished toE do so, subject toE the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package OhmOMatic.Global; import OhmOMatic.Chord.Link.NodeLink; import org.apache.commons.codec.digest.DigestUtils; import java.io.*; import java.math.BigInteger; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Random; import java.util.concurrent.Callable; import static org.apache.commons.codec.digest.MessageDigestAlgorithms.SHA3_512; public final class GB { public static final Integer numberOfFingers = 8; private static final int shaBits = 512; private static final BigInteger shaBitsB = BigInteger.valueOf(shaBits); private static final DigestUtils duSHA3_512 = new DigestUtils(SHA3_512); private static final HashMap<String, BigInteger> _shaStrings = new HashMap<>(); private static final HashMap<Integer, BigInteger> _powerOfTwo = new HashMap<>(); private static final int randomSeed = new Date().getSeconds(); private static final Random randomFN = new Random(randomSeed); public static BigInteger SHA(final String s) { if (_shaStrings.containsKey(s)) return _shaStrings.get(s); final var b = new BigInteger(duSHA3_512.digest(s)); _shaStrings.put(s, b); return b; } public static BigInteger getPowerOfTwo(final Integer k) { if (_powerOfTwo.size() == 0) { var curVal = BigInteger.ONE; // 2^0 for (Integer i = 0; i <= shaBits; i++) { _powerOfTwo.put(i, curVal); curVal = curVal.multiply(BigInteger.TWO); } } return _powerOfTwo.get(k); } public static boolean incluso(NodeLink id, NodeLink a, BigInteger b) { return incluso(id.ID, a.ID, b); } public static boolean incluso(NodeLink id, NodeLink a, NodeLink b) { return incluso(id.ID, a.ID, b.ID); } public static boolean incluso(BigInteger id, NodeLink a, NodeLink b) { return incluso(id, a.ID, b.ID); } private static boolean incluso(BigInteger i, BigInteger s, BigInteger e) { final BigInteger id = i.mod(shaBitsB); final BigInteger start = s.mod(shaBitsB); final BigInteger end = e.mod(shaBitsB); if (end.compareTo(start) <= 0) return start.compareTo(id) < 0 || id.compareTo(end) <= 0; else return start.compareTo(id) < 0 && id.compareTo(end) <= 0; } public static boolean finger_incluso(NodeLink key, NodeLink x, BigInteger y) { return finger_incluso(key.ID, x.ID, y); } private static boolean finger_incluso(BigInteger i, BigInteger s, BigInteger e) { final BigInteger key = i.mod(shaBitsB); final BigInteger start = s.mod(shaBitsB); final BigInteger end = e.mod(shaBitsB); if (start.equals(end)) return true; else if (end.compareTo(start) < 0) return start.compareTo(key) < 0 || key.compareTo(end) < 0; else return start.compareTo(key) < 0 && key.compareTo(end) < 0; } public static byte[] serialize(final Serializable obj) throws IOException { try ( var out = new ByteArrayOutputStream(); var os = new ObjectOutputStream(out) ) { os.writeObject(obj); return out.toByteArray(); } } public static <G extends Serializable> G deserializeT(final byte[] data) throws IOException, ClassNotFoundException { return (G) deserialize(data); } public static Serializable deserialize(final byte[] data) throws IOException, ClassNotFoundException { try ( var in = new ByteArrayInputStream(data); var is = new ObjectInputStream(in) ) { return (Serializable) is.readObject(); } } public static int stringToInt(String s, int default_) { var r = default_; try { r = Integer.parseUnsignedInt(s); } catch (Exception e) { //non integer } return r; } public static boolean stringIsBlank(final String s) { return (s == null || s.equals("") || s.equals(" ")); } public static int randomInt(final int da, final int a) { return randomFN.nextInt(a) + da; } public static String DateToString() { return DateToString(new Date()); } private static String DateToString(Date d) { final var sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS"); return sdf.format(d); } public static void loopUntil(Callable<Boolean> callback) { try { while (!callback.call()) ; } catch (Exception e) { e.printStackTrace(); } } public static void waitfor(Callable<Boolean> callback, int millisecondi) { try { _waitfor(callback, millisecondi); } catch (Exception e) { e.printStackTrace(); } } private static void _waitfor(Callable<Boolean> callback, int millisecondi) throws Exception { while (!callback.call()) GB.sleep(millisecondi); } public static void sleep(int millisecondi) { try { Thread.sleep(millisecondi); } catch (InterruptedException e) { e.printStackTrace(); } } public static Date Now() { final var n = new Date(); return new Date( n.getYear(), n.getMonth(), n.getDate(), n.getHours(), n.getMinutes(), n.getSeconds() ); } }
25.397436
566
0.712771
e89af1bf783bdcaa3cb088e4d0f9c227f9b9258d
1,067
package pl.edu.agh.cs.app.backend.status; import javafx.beans.property.BooleanProperty; import javafx.beans.property.IntegerProperty; import pl.edu.agh.cs.app.backend.status.states.PressedStatus; import pl.edu.agh.cs.app.ui.game.panes.status.GameTimer; public interface IGameStatus { // yep, I know, the methods are in a totally random order :D BooleanProperty getFullScreenProperty(); void toggleFullScreen(); boolean isPaused(); void togglePause(); int getPlayerPoints(); IntegerProperty getPlayerPointsProperty(); boolean isChoiceHandled(); void handleChoice(); void pressed(PressedStatus pressed); boolean isSuccess(); boolean isFailure(); IntegerProperty averageReactionProperty(); int getRoundTime(); void measureTime(); void startRound(); void endRound(); boolean isRoundFinished(); boolean isGameFinished(); void runGameTimer(); void stopGameTimer(); void disableGameTimer(); void setGameTimer(GameTimer timer); void writeStatistics(); }
18.719298
64
0.712277
2996498a60b15d066010074d0e8160e619e4e916
712
package com.github.dev_brutus.bagel_ui.impl.listener; import com.github.dev_brutus.bagel_ui.impl.DisplayWindow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.event.WindowEvent; import java.awt.event.WindowStateListener; /** * */ public class WindowStateListenerImpl implements WindowStateListener { private static final Logger LOGGER = LoggerFactory.getLogger(WindowStateListenerImpl.class); private final DisplayWindow displayWindow; public WindowStateListenerImpl(DisplayWindow displayWindow) { this.displayWindow = displayWindow; } @Override public void windowStateChanged(WindowEvent e) { LOGGER.debug("Change state {}", e); } }
26.37037
96
0.766854
1e575a4173862c874d3e2cf4483b575a4bc7867d
1,218
package de.javagl.flow.samples.weka; import javax.swing.SwingUtilities; import de.javagl.category.Categories; import de.javagl.category.CategoriesBuilder; import de.javagl.category.Category; import de.javagl.flow.Flow; import de.javagl.flow.gui.FlowEditorApplication; import de.javagl.flow.module.creation.ModuleCreator; import de.javagl.flow.plugin.ModuleCreatorServices; /** * An example showing how to create an instance of the visual-interactive * {@link Flow} editing application, with a certain set of * {@link ModuleCreator} instances that perform Weka operations. */ @SuppressWarnings("javadoc") public class FlowWekaSample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> createAndShowGui()); } private static Category<ModuleCreator> createModuleCreators() { CategoriesBuilder<ModuleCreator> categoriesBuilder = Categories.createBuilder("All modules"); ModuleCreatorServices.initialize(categoriesBuilder); return categoriesBuilder.get(); } public static void createAndShowGui() { new FlowEditorApplication(createModuleCreators()); } }
30.45
75
0.715107
d6019d0c7fbfc4ac86f7b7b66c3af7c987544379
9,150
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|cxf operator|. name|systest operator|. name|jaxrs package|; end_package begin_import import|import name|java operator|. name|util operator|. name|Collections import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|javax operator|. name|ws operator|. name|rs operator|. name|Consumes import|; end_import begin_import import|import name|javax operator|. name|ws operator|. name|rs operator|. name|GET import|; end_import begin_import import|import name|javax operator|. name|ws operator|. name|rs operator|. name|POST import|; end_import begin_import import|import name|javax operator|. name|ws operator|. name|rs operator|. name|Path import|; end_import begin_import import|import name|javax operator|. name|ws operator|. name|rs operator|. name|PathParam import|; end_import begin_import import|import name|javax operator|. name|ws operator|. name|rs operator|. name|Produces import|; end_import begin_import import|import name|javax operator|. name|ws operator|. name|rs operator|. name|core operator|. name|MediaType import|; end_import begin_import import|import name|javax operator|. name|ws operator|. name|rs operator|. name|core operator|. name|MultivaluedMap import|; end_import begin_import import|import name|javax operator|. name|ws operator|. name|rs operator|. name|core operator|. name|Response import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|bind operator|. name|annotation operator|. name|XmlRootElement import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|bind operator|. name|annotation operator|. name|XmlSeeAlso import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|bind operator|. name|annotation operator|. name|XmlType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|jaxrs operator|. name|ext operator|. name|xml operator|. name|XMLName import|; end_import begin_class annotation|@ name|Path argument_list|( literal|"/" argument_list|) specifier|public class|class name|PetStore block|{ specifier|public specifier|static specifier|final name|String name|CLOSED init|= literal|"The Pet Store is closed" decl_stmt|; specifier|public name|PetStore parameter_list|() block|{ } annotation|@ name|GET annotation|@ name|Produces argument_list|( literal|"text/plain" argument_list|) specifier|public name|Response name|getBaseStatus parameter_list|() throws|throws name|Exception block|{ return|return name|Response operator|. name|ok argument_list|( name|CLOSED argument_list|) operator|. name|build argument_list|() return|; block|} annotation|@ name|GET annotation|@ name|Path argument_list|( literal|"/petstore/pets/{petId}/" argument_list|) annotation|@ name|Produces argument_list|( literal|"text/xml" argument_list|) specifier|public name|Response name|getStatus parameter_list|( annotation|@ name|PathParam argument_list|( literal|"petId" argument_list|) name|String name|petId parameter_list|) throws|throws name|Exception block|{ return|return name|Response operator|. name|ok argument_list|( name|CLOSED argument_list|) operator|. name|build argument_list|() return|; block|} annotation|@ name|GET annotation|@ name|Path argument_list|( literal|"/petstore/jaxb/status/" argument_list|) annotation|@ name|Produces argument_list|( literal|"text/xml" argument_list|) specifier|public name|PetStoreStatus name|getJaxbStatus parameter_list|() block|{ return|return operator|new name|PetStoreStatus argument_list|() return|; block|} annotation|@ name|GET annotation|@ name|Path argument_list|( literal|"/petstore/jaxb/statusType/" argument_list|) annotation|@ name|Produces argument_list|( literal|"text/xml" argument_list|) specifier|public name|PetStoreStatusType name|getJaxbStatusTyoe parameter_list|() block|{ return|return operator|new name|PetStoreStatusImpl1 argument_list|() return|; block|} annotation|@ name|GET annotation|@ name|Path argument_list|( literal|"/petstore/jaxb/status/elements" argument_list|) annotation|@ name|Produces argument_list|( block|{ literal|"text/xml" block|, literal|"application/json" block|} argument_list|) annotation|@ name|XMLName argument_list|( literal|"{http://pets}statuses" argument_list|) specifier|public name|List argument_list|< name|PetStoreStatusElement argument_list|> name|getJaxbStatusElements parameter_list|() block|{ return|return name|Collections operator|. name|singletonList argument_list|( operator|new name|PetStoreStatusElement argument_list|() argument_list|) return|; block|} annotation|@ name|GET annotation|@ name|Path argument_list|( literal|"/petstore/jaxb/status/element" argument_list|) annotation|@ name|Produces argument_list|( literal|"text/xml" argument_list|) specifier|public name|PetStoreStatusElement name|getJaxbStatusElement parameter_list|() block|{ return|return operator|new name|PetStoreStatusElement argument_list|() return|; block|} annotation|@ name|POST annotation|@ name|Path argument_list|( literal|"/petstore/pets/" argument_list|) annotation|@ name|Consumes argument_list|( name|MediaType operator|. name|APPLICATION_FORM_URLENCODED argument_list|) annotation|@ name|Produces argument_list|( literal|"text/xml" argument_list|) specifier|public name|Response name|updateStatus parameter_list|( name|MultivaluedMap argument_list|< name|String argument_list|, name|String argument_list|> name|params parameter_list|) throws|throws name|Exception block|{ return|return name|Response operator|. name|ok argument_list|( name|params operator|. name|getFirst argument_list|( literal|"status" argument_list|) argument_list|) operator|. name|build argument_list|() return|; block|} annotation|@ name|XmlType argument_list|( name|name operator|= literal|"status" argument_list|, name|namespace operator|= literal|"http://pets" argument_list|) specifier|public specifier|static class|class name|PetStoreStatus block|{ specifier|private name|String name|status init|= name|PetStore operator|. name|CLOSED decl_stmt|; specifier|public name|String name|getStatus parameter_list|() block|{ return|return name|status return|; block|} specifier|public name|void name|setStatus parameter_list|( name|String name|status parameter_list|) block|{ name|this operator|. name|status operator|= name|status expr_stmt|; block|} block|} annotation|@ name|XmlRootElement argument_list|( name|name operator|= literal|"elstatus" argument_list|, name|namespace operator|= literal|"http://pets" argument_list|) specifier|public specifier|static class|class name|PetStoreStatusElement extends|extends name|PetStoreStatus block|{ } annotation|@ name|XmlType argument_list|( name|name operator|= literal|"statusType" argument_list|, name|namespace operator|= literal|"http://pets" argument_list|) annotation|@ name|XmlSeeAlso argument_list|( block|{ name|PetStoreStatusImpl1 operator|. name|class block|, name|PetStoreStatusImpl2 operator|. name|class block|} argument_list|) specifier|public specifier|static class|class name|PetStoreStatusType block|{ specifier|private name|String name|status init|= name|PetStore operator|. name|CLOSED decl_stmt|; specifier|public name|String name|getStatus parameter_list|() block|{ return|return name|status return|; block|} specifier|public name|void name|setStatus parameter_list|( name|String name|status parameter_list|) block|{ name|this operator|. name|status operator|= name|status expr_stmt|; block|} block|} annotation|@ name|XmlRootElement argument_list|( name|name operator|= literal|"statusImpl1" argument_list|, name|namespace operator|= literal|"http://pets" argument_list|) specifier|public specifier|static class|class name|PetStoreStatusImpl1 extends|extends name|PetStoreStatusType block|{ } annotation|@ name|XmlRootElement argument_list|( name|name operator|= literal|"statusImpl2" argument_list|, name|namespace operator|= literal|"http://pets" argument_list|) specifier|public specifier|static class|class name|PetStoreStatusImpl2 extends|extends name|PetStoreStatusType block|{ } block|} end_class end_unit
14.500792
810
0.799235
14cbfc4f57ade1dc414da5c7a1f9a26fe80788fd
526
/* * Copyright (C) 2017, Ulrich Wolffgang <ulrich.wolffgang@proleap.io> * All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package io.proleap.cobol.preprocessor.sub.document; import io.proleap.cobol.CobolPreprocessorListener; import io.proleap.cobol.preprocessor.sub.document.impl.CobolDocumentContext; public interface CobolDocumentParserListener extends CobolPreprocessorListener { CobolDocumentContext context(); }
29.222222
80
0.80038
c86bacc8fee2086db2691a351bd4dc0c8b366e39
1,689
package com.intentmedia.admm; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mrunit.MapDriver; import org.apache.hadoop.mrunit.ReduceDriver; import org.apache.hadoop.mrunit.types.Pair; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; public class TestHelper { public static <IK extends WritableComparable<?>, OK extends WritableComparable<?>> void assertMaps( Mapper<IK, Text, OK, Text> subject, IK inputKey, List<Text> inputValues, List<OK> outputKeys, List<Text> outputValues) { MapDriver<IK, Text, OK, Text> mapDriver = new MapDriver<IK, Text, OK, Text>(subject); for (Text inputValue : inputValues) { mapDriver.withInput(inputKey, inputValue); } for (int i = 0; i < outputValues.size(); i++) { mapDriver.withOutput(outputKeys.get(i), outputValues.get(i)); } mapDriver.runTest(); } public static <IK extends WritableComparable<?>, OK extends WritableComparable<?>> Text reduceToOneValue( Reducer<IK, Text, OK, Text> subject, IK inputKey, List<Text> inputValues) throws IOException { ReduceDriver<IK, Text, OK, Text> reduceDriver = new ReduceDriver<IK, Text, OK, Text>(subject) .withInput(inputKey, inputValues); List<Pair<OK, Text>> output = reduceDriver.run(); assertEquals(1, output.size()); return output.get(0).getSecond(); } }
33.78
109
0.648905
7a3883c474ffd5d2e4aff78512858e6930d3316f
1,758
package edu.fudan.stormcv.service.monitor; import edu.fudan.stormcv.service.db.DBManager; import edu.fudan.stormcv.service.process.ProcessManager; import edu.fudan.stormcv.service.process.TopologyManager; import edu.fudan.stormcv.topology.TopologyH264; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.lang.Thread.sleep; /** * Created by IntelliJ IDEA. * User: jkyan * Time: 4/28/17 - 9:53 AM * Description: */ public class ProcessMonitor implements Runnable { private MetricsCollector metricsCollector; private Logger logger = LoggerFactory.getLogger(ProcessMonitor.class); public ProcessMonitor() { metricsCollector = new MetricsCollector(); } @Override public void run() { while(true) { try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } checkProcess(); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } checkTopology(); } } private void checkProcess() { } private void checkTopology() { Map<String, TopologyH264> topologyH264Map = TopologyManager.getInstance().getTopologyH264Map(); for (String topoName : topologyH264Map.keySet()) { TopologyH264 topology = topologyH264Map.get(topoName); metricsCollector.setName(topoName, topology.getConfig()); metricsCollector.run(); // if (topology.isTopologyRunningAtLocal()) { // // } else { // // } } } private boolean updateTopologySql() { return true; } }
24.082192
104
0.615472
330ffcdb5a8d54ba45c962575d9dcdef489d2cc2
25,033
/* * ModelGrid2D.java * * Created on November 29, 2005, 3:47 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ /** *TODO: create/import variable Hz */ package wts.roms.model; import com.wtstockhausen.utils.MathFunctions; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import ucar.ma2.ArrayChar; import ucar.ma2.Index; import ucar.nc2.Variable; import ucar.nc2.dataset.NetcdfDataset; /** * * @author William Stockhausen */ public class ModelGrid2D { /** */ protected final CriticalGrid2DVariablesInfo cvi; /** map of all ModelData fields */ protected final HashMap<String,ModelData> mdMap = new HashMap<>(40); /** map of all MaskData fields */ protected final HashMap<String,MaskData> mkMap = new HashMap<>(7); NetcdfReader nr; boolean spherical; /* *Grid lengths in xi, eta directions */ double xl,el; /* *Max indices in xi, eta directions */ int L,M; /* *Grid fields */ ModelData h, pm, pn, dmde, dndx, angle; ModelData x_rho, x_psi, x_u, x_v; ModelData y_rho, y_psi, y_u, y_v; ModelData lat_rho, lat_psi, lat_u, lat_v; ModelData lon_rho, lon_psi, lon_u, lon_v; /** mask fields */ MaskData mask_rho, mask_psi, mask_u, mask_v; /** Creates a new instance of Grid */ public ModelGrid2D() { cvi = GlobalInfo.getInstance().getCriticalGrid2DVariablesInfo(); initialize(); } public ModelGrid2D(String fn) { cvi = GlobalInfo.getInstance().getCriticalGrid2DVariablesInfo(); initialize(); if (isGrid(fn)) { setDataset(fn); } } public ModelGrid2D(ucar.nc2.dataset.NetcdfDataset nds) { cvi = GlobalInfo.getInstance().getCriticalGrid2DVariablesInfo(); initialize(); if (isGrid(nds)) { setDataset(nds); } } private void initialize() { nr = null; spherical = false; xl=el=0.0; this.L=this.M=-1; h=pm=pn=dmde=dndx=angle=null; mask_rho=mask_psi=mask_u=mask_v=null; x_rho=x_psi=x_u=x_v=null; y_rho=y_psi=y_u=y_v=null; lat_rho=lat_psi=lat_u=lat_v=null; lon_rho=lon_psi=lon_u=lon_v=null; createFieldMaps(); } /** * Creates the initial maps of internal names to model fields. */ private void createFieldMaps(){ //create mdMap CriticalGrid2DVariablesInfo cvis = GlobalInfo.getInstance().getCriticalGrid2DVariablesInfo(); Iterator<String> keys = cvis.getNames().iterator(); while (keys.hasNext()){ String key = keys.next(); CriticalVariableInfo cvi = cvis.getVariableInfo(key); if (cvi.isSpatialField()) mdMap.put(key,null);//additional field } //create mkMap mkMap.put("mask_rho",null); mkMap.put("mask_psi",null); mkMap.put("mask_u",null); mkMap.put("mask_v",null); } /** * Adds name to map of fields to be extracted from the ROMS netcdf dataset. * * @param name * @return */ public boolean addFieldName(String name){ boolean b = mdMap.containsKey(name); if (b) mdMap.put(name,null); return !b; } /** * Returns a Set of the internal field names available. * * @return Set<String> */ public Set<String> getFieldNames() { return mdMap.keySet(); } public static boolean isGrid(String fn) { boolean b = false; try { NetcdfDataset dsp = NetcdfDataset.openDataset(fn); b = isGrid(dsp); } catch (IOException ex) { // ex.printStackTrace(); } return b; } public static boolean isGrid(ucar.nc2.dataset.NetcdfDataset nds) { if (nds==null) return false; boolean b = (nds.findVariable(GlobalInfo.getInstance().getCriticalGrid2DVariablesInfo().getNameInROMSDataset("h"))!=null); return b; } private double readScalarDouble(String name) throws IOException { double x = 0; Variable v = nr.findVariable(name); if (v!=null) x = v.readScalarDouble(); else throw new IOException(); return x; } private void extractVariables() throws IOException { Variable sph = nr.findVariable(cvi.getNameInROMSDataset("spherical")); if (sph!=null) { ArrayChar ac = (ArrayChar) sph.read(); Index ix = ac.getIndex(); char c = ac.getChar(0); // char c = ac.getChar(ix.set(0)); String str = String.valueOf(c); spherical = str.equalsIgnoreCase("T"); } else { spherical = false; } xl = readScalarDouble(cvi.getNameInROMSDataset("xl")); el = readScalarDouble(cvi.getNameInROMSDataset("el")); h = nr.getModelData(cvi.getNameInROMSDataset("h"),"h"); pm = nr.getModelData(cvi.getNameInROMSDataset("pm"),"pm"); pn = nr.getModelData(cvi.getNameInROMSDataset("pn"),"pn"); dmde = nr.getModelData(cvi.getNameInROMSDataset("dmde"),"dmde"); dndx = nr.getModelData(cvi.getNameInROMSDataset("dndx"),"dndx"); angle = nr.getModelData(cvi.getNameInROMSDataset("angle"),"angle"); int[] shp = h.getShape(); L = shp[1]-1; //max index in xi direction M = shp[0]-1; //max index in eta direction mask_rho = nr.getMaskData(cvi.getNameInROMSDataset("mask_rho"),"mask_rho"); mask_psi = nr.getMaskData(cvi.getNameInROMSDataset("mask_psi"),"mask_psi"); mask_u = nr.getMaskData(cvi.getNameInROMSDataset("mask_u"),"mask_u"); mask_v = nr.getMaskData(cvi.getNameInROMSDataset("mask_v"),"mask_v"); x_rho = nr.getModelData(cvi.getNameInROMSDataset("x_rho"),"x_rho"); x_psi = nr.getModelData(cvi.getNameInROMSDataset("x_psi"),"x_psi"); x_u = nr.getModelData(cvi.getNameInROMSDataset("x_u"),"x_u"); x_v = nr.getModelData(cvi.getNameInROMSDataset("x_v"),"x_v"); y_rho = nr.getModelData(cvi.getNameInROMSDataset("y_rho"),"y_rho"); y_psi = nr.getModelData(cvi.getNameInROMSDataset("y_psi"),"y_psi"); y_u = nr.getModelData(cvi.getNameInROMSDataset("y_u"),"y_u"); y_v = nr.getModelData(cvi.getNameInROMSDataset("y_v"),"y_v"); lat_rho = nr.getModelData(cvi.getNameInROMSDataset("lat_rho"),"lat_rho"); lat_psi = nr.getModelData(cvi.getNameInROMSDataset("lat_psi"),"lat_psi"); lat_u = nr.getModelData(cvi.getNameInROMSDataset("lat_u"),"lat_u"); lat_v = nr.getModelData(cvi.getNameInROMSDataset("lat_v"),"lat_v"); lon_rho = nr.getModelData(cvi.getNameInROMSDataset("lon_rho"),"lon_rho"); lon_psi = nr.getModelData(cvi.getNameInROMSDataset("lon_psi"),"lon_psi"); lon_u = nr.getModelData(cvi.getNameInROMSDataset("lon_u"),"lon_u"); lon_v = nr.getModelData(cvi.getNameInROMSDataset("lon_v"),"lon_v"); if (lat_rho!=null) spherical=true; Iterator<String> keys = mdMap.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); mdMap.put(key,getGridField1(key)); } } /** * Set the ROMS grid using a file name. * @param fn */ public void setDataset(String fn) { try { if (isGrid(fn)) { nr = new NetcdfReader(fn); extractVariables(); } else { System.out.println("Grid.setDataset(fn): File not valid ROMS grid."); System.out.println(fn); System.out.println(""); } } catch (IOException ex) { ex.printStackTrace(); } } /** * Set the ROMS grid using a netcdf dataset object. * @param nds */ public void setDataset(ucar.nc2.dataset.NetcdfDataset nds) { try { if (isGrid(nds)) { nr = new NetcdfReader(nds); extractVariables(); } } catch (IOException ex) { ex.printStackTrace(); } } /** * Returns a grid field based on the internal name (not the ROMS alias) provided. * @param name * @return - the field as a ModelData object. */ private ModelData getGridField1(String name) { if (name.equalsIgnoreCase("angle")) {return angle;} else if (name.equalsIgnoreCase("dmde")) {return dmde;} else if (name.equalsIgnoreCase("dndx")) {return dndx;} else if (name.equalsIgnoreCase("h")) {return h;} else if (name.equalsIgnoreCase("lat_psi")) {return lat_psi;} else if (name.equalsIgnoreCase("lat_rho")) {return lat_rho;} else if (name.equalsIgnoreCase("lat_u")) {return lat_u;} else if (name.equalsIgnoreCase("lat_v")) {return lat_v;} else if (name.equalsIgnoreCase("lon_psi")) {return lon_psi;} else if (name.equalsIgnoreCase("lon_rho")) {return lon_rho;} else if (name.equalsIgnoreCase("lon_u")) {return lon_u;} else if (name.equalsIgnoreCase("lon_v")) {return lon_v;} else if (name.equalsIgnoreCase("mask_psi")) {return mask_psi;} else if (name.equalsIgnoreCase("mask_rho")) {return mask_rho;} else if (name.equalsIgnoreCase("mask_u")) {return mask_u;} else if (name.equalsIgnoreCase("mask_v")) {return mask_v;} else if (name.equalsIgnoreCase("pm")) {return pm;} else if (name.equalsIgnoreCase("pn")) {return pn;} else if (name.equalsIgnoreCase("x_psi")) {return x_psi;} else if (name.equalsIgnoreCase("x_rho")) {return x_rho;} else if (name.equalsIgnoreCase("x_u")) {return x_u;} else if (name.equalsIgnoreCase("x_v")) {return x_v;} else if (name.equalsIgnoreCase("y_psi")) {return y_psi;} else if (name.equalsIgnoreCase("y_rho")) {return y_rho;} else if (name.equalsIgnoreCase("y_u")) {return y_u;} else if (name.equalsIgnoreCase("y_v")) {return y_v;} return null; } /** * Returns a grid field based on the internal name (not the ROMS alias) provided. * * @param name * @return - the field as a ModelData object. */ public ModelData getGridField(String name) { return mdMap.get(name); } /** * Returns a grid mask field based on the internal name (not the ROMS alias) provided. * * @param name * @return - the mask as a MaskData object (or null). */ public MaskData getGridMask(String name) { return mkMap.get(name); } public double getH(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return h.getValue(xi,eta); } public double getPM(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return pm.getValue(xi,eta); } public double getPN(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return pn.getValue(xi,eta); } public double getDMDE(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return dmde.getValue(xi,eta); } public double getDNDX(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return dndx.getValue(xi,eta); } public double getAngle(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return angle.getValue(xi,eta); } public double getX_RHO(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return x_rho.getValue(xi,eta); } public double getX_PSI(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return x_psi.getValue(xi,eta); } public double getX_U(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return x_u.getValue(xi,eta); } public double getX_V(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return x_v.getValue(xi,eta); } public double getY_RHO(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return y_rho.getValue(xi,eta); } public double getY_PSI(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return y_psi.getValue(xi,eta); } public double getY_U(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return y_u.getValue(xi,eta); } public double getY_V(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return y_v.getValue(xi,eta); } public double getLat_RHO(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return lat_rho.getValue(xi,eta); } public double getLat_PSI(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return lat_psi.getValue(xi,eta); } public double getLat_U(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return lat_u.getValue(xi,eta); } public double getLat_V(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return lat_v.getValue(xi,eta); } /** * Returns grid lon at xi,eta. * @param xi - grid coordinate value * @param eta - grid coordinate value * * @return lon ROMS grid longitude (range 0-360). (Note: NOT standard NAD83) * @throws java.lang.ArrayIndexOutOfBoundsException */ public double getLon_RHO(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return lon_rho.getValue(xi,eta); } /** * Returns grid lon at xi,eta. * @param xi - grid coordinate value * @param eta - grid coordinate value * * @return lon ROMS grid longitude (range 0-360). (Note: NOT standard NAD83) * @throws java.lang.ArrayIndexOutOfBoundsException */ public double getLon_PSI(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return lon_psi.getValue(xi,eta); } /** * Returns grid lon at xi,eta. * @param xi - grid coordinate value * @param eta - grid coordinate value * * @return lon ROMS grid longitude (range 0-360). (Note: NOT standard NAD83) * @throws java.lang.ArrayIndexOutOfBoundsException */ public double getLon_U(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return lon_u.getValue(xi,eta); } /** * Returns grid lon at xi,eta. * @param xi - grid coordinate value * @param eta - grid coordinate value * * @return lon ROMS grid longitude (range 0-360). (Note: NOT standard NAD83) * @throws java.lang.ArrayIndexOutOfBoundsException */ public double getLon_V(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return lon_v.getValue(xi,eta); } public int getMask_RHO(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return (int) mask_rho.getValue(xi,eta); } public int getMask_PSI(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return (int) mask_psi.getValue(xi,eta); } public int getMask_U(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return (int) mask_u.getValue(xi,eta); } public int getMask_V(int xi, int eta) throws java.lang.ArrayIndexOutOfBoundsException { return (int) mask_v.getValue(xi,eta); } public boolean isSpherical() { return spherical; } /** * Gets max ROMS index in xi direction. * @return - the value */ public int getL() { return L; } /** * Gets max ROMS index-1 in xi direction (max xi index internal to grid). * @return - the value */ public int getLm() { return L-1; } /** * Gets max ROMS index in eta direction. * @return - the value */ public int getM() { return M; } /** * Gets max ROMS index-1 in eta direction (max eta index internal to grid). * @return - the value */ public int getMm() { return M-1; } /** * Computes the grid xi,eta coordinates corresponding to the input * lat, lon coordinates. The input lat/lon coordinates should be * in NAD83 (Greenwich PM, lon range -180 to 180). * @param lat * @param lon * @return double[] - grid {I,J} corresponding to lat,lon * @throws java.lang.ArrayIndexOutOfBoundsException */ public double[] computeIJfromLL(double lat, double lon) throws java.lang.ArrayIndexOutOfBoundsException { if (!spherical) return new double[] {-1.0,-1.0}; //transform range to [0,360) double[] pos = new double[] {MathFunctions.mod(lon+360.0,360.0),lat}; double[] posIJ = Grid2DUtilities.computeHorizontalIndices(pos, lon_rho, lat_rho, angle, spherical); return posIJ; } /** * Computes the grid xi,eta coordinates corresponding to the input * x,y coordinates. * @param x * @param y * @return double[] - grid {I,J} corresponding to x,y * @throws java.lang.ArrayIndexOutOfBoundsException */ public double[] computeIJfromXY(double x, double y) throws java.lang.ArrayIndexOutOfBoundsException { if (spherical) return new double[] {-1.0,-1.0}; double[] pos = new double[] {x,y}; double[] posIJ = Grid2DUtilities.computeHorizontalIndices(pos, x_rho, y_rho, angle, spherical); return posIJ; } /** * Returns the physical location of the vertices of the xi,eta cell in the * psi grid. * @param xi - xi index of cell * @param eta - eta index of cell * @param spherical - flag to return lat,lon (true) or x,y (false) * @return double[4][2] - array of vertices */ public double[][] getVerticesPSIgrid(int xi, int eta, boolean spherical) { double[][] verts = new double[4][2]; if (spherical) { verts[0][0] = lon_rho.getValue(xi-1, eta-1); verts[0][1] = lat_rho.getValue(xi-1, eta-1); verts[1][0] = lon_rho.getValue(xi, eta-1); verts[1][1] = lat_rho.getValue(xi, eta-1); verts[2][0] = lon_rho.getValue(xi, eta); verts[2][1] = lat_rho.getValue(xi, eta); verts[3][0] = lon_rho.getValue(xi-1, eta); verts[3][1] = lat_rho.getValue(xi-1, eta); } else { verts[0][0] = x_rho.getValue(xi-1, eta-1); verts[0][1] = y_rho.getValue(xi-1, eta-1); verts[1][0] = x_rho.getValue(xi, eta-1); verts[1][1] = y_rho.getValue(xi, eta-1); verts[2][0] = x_rho.getValue(xi, eta); verts[2][1] = y_rho.getValue(xi, eta); verts[3][0] = x_rho.getValue(xi-1, eta); verts[3][1] = y_rho.getValue(xi-1, eta); } return verts; } /** * Returns the physical location of the vertices of the xi,eta cell in the * rho grid. * @param xi - xi index of cell * @param eta - eta index of cell * @param spherical - flag to return lat,lon (true) or x,y (false) * @return double[4][2] - array of vertices */ public double[][] getVerticesRHOgrid(int xi, int eta, boolean spherical) { double[][] verts = new double[4][2]; if (spherical) { verts[0][0] = lon_psi.getValue(xi, eta); verts[0][1] = lat_psi.getValue(xi, eta); verts[1][0] = lon_psi.getValue(xi+1, eta); verts[1][1] = lat_psi.getValue(xi+1, eta); verts[2][0] = lon_psi.getValue(xi+1, eta+1); verts[2][1] = lat_psi.getValue(xi+1, eta+1); verts[3][0] = lon_psi.getValue(xi, eta+1); verts[3][1] = lat_psi.getValue(xi, eta+1); } else { verts[0][0] = x_psi.getValue(xi, eta); verts[0][1] = y_psi.getValue(xi, eta); verts[1][0] = x_psi.getValue(xi+1, eta); verts[1][1] = y_psi.getValue(xi+1, eta); verts[2][0] = x_psi.getValue(xi+1, eta+1); verts[2][1] = y_psi.getValue(xi+1, eta+1); verts[3][0] = x_psi.getValue(xi, eta+1); verts[3][1] = y_psi.getValue(xi, eta+1); } return verts; } /** * Returns the physical location of the vertices of the xi,eta cell in the * v grid. * @param xi - xi index of cell * @param eta - eta index of cell * @param spherical - flag to return lat,lon (true) or x,y (false) * @return double[4][2] - array of vertices */ public double[][] getVerticesUgrid(int xi, int eta, boolean spherical) { double[][] verts = new double[4][2]; if (spherical) { verts[0][0] = lon_v.getValue(xi-1, eta); verts[0][1] = lat_v.getValue(xi-1, eta); verts[1][0] = lon_v.getValue(xi, eta); verts[1][1] = lat_v.getValue(xi, eta); verts[2][0] = lon_v.getValue(xi, eta+1); verts[2][1] = lat_v.getValue(xi, eta+1); verts[3][0] = lon_v.getValue(xi-1, eta+1); verts[3][1] = lat_v.getValue(xi-1, eta+1); } else { verts[0][0] = x_v.getValue(xi-1, eta); verts[0][1] = y_v.getValue(xi-1, eta); verts[1][0] = x_v.getValue(xi, eta); verts[1][1] = y_v.getValue(xi, eta); verts[2][0] = x_v.getValue(xi, eta+1); verts[2][1] = y_v.getValue(xi, eta+1); verts[3][0] = x_v.getValue(xi-1, eta+1); verts[3][1] = y_v.getValue(xi-1, eta+1); } return verts; } /** * Returns the physical location of the vertices of the xi,eta cell in the * v grid. * @param xi - xi index of cell * @param eta - eta index of cell * @param spherical - flag to return lat,lon (true) or x,y (false) * @return double[4][2] - array of vertices */ public double[][] getVerticesVgrid(int xi, int eta, boolean spherical) { double[][] verts = new double[4][2]; if (spherical) { verts[0][0] = lon_u.getValue(xi, eta-1); verts[0][1] = lat_u.getValue(xi, eta-1); verts[1][0] = lon_u.getValue(xi+1, eta-1); verts[1][1] = lat_u.getValue(xi+1, eta-1); verts[2][0] = lon_u.getValue(xi+1, eta); verts[2][1] = lat_u.getValue(xi+1, eta); verts[3][0] = lon_u.getValue(xi, eta); verts[3][1] = lat_u.getValue(xi, eta); } else { verts[0][0] = x_u.getValue(xi, eta-1); verts[0][1] = y_u.getValue(xi, eta-1); verts[1][0] = x_u.getValue(xi+1, eta-1); verts[1][1] = y_u.getValue(xi+1, eta-1); verts[2][0] = x_u.getValue(xi+1, eta); verts[2][1] = y_u.getValue(xi+1, eta); verts[3][0] = x_u.getValue(xi, eta); verts[3][1] = y_u.getValue(xi, eta); } return verts; } public boolean isOnLand(double[] pos){ int Ir = (int) Math.floor(pos[0])+1; int Jr = (int) Math.floor(pos[1])+1; int i1 = Math.min(Math.max(Ir,1),L); int j1 = Math.min(Math.max(Jr,1),M); return (mask_psi.getValue(i1,j1)<0.5); } }
36.544526
130
0.557065
7984d9a2ef250d8547e23f469a6b3aa79c21f96a
14,192
package kr.hs.entrydsm.application.usecase; import kr.hs.entrydsm.application.ApplicationFactory; import kr.hs.entrydsm.application.entity.*; import kr.hs.entrydsm.application.integrate.score.ScoreCalculator; import kr.hs.entrydsm.application.integrate.user.ApplicantDocsService; import kr.hs.entrydsm.application.integrate.user.ApplicantRepository; import kr.hs.entrydsm.application.integrate.user.ApplicantStatusService; import kr.hs.entrydsm.application.integrate.user.ApplicationApplicantRepository; import kr.hs.entrydsm.application.usecase.dto.application.request.Information; import kr.hs.entrydsm.application.usecase.dto.application.request.ApplicationRequest; import kr.hs.entrydsm.application.usecase.dto.application.request.GraduatedInformationRequest; import kr.hs.entrydsm.application.usecase.dto.application.response.ApplicationResponse; import kr.hs.entrydsm.application.usecase.dto.application.response.GraduatedInformationResponse; import kr.hs.entrydsm.application.usecase.dto.application.response.InformationResponse; import kr.hs.entrydsm.application.usecase.exception.*; import kr.hs.entrydsm.application.usecase.image.ImageService; import kr.hs.entrydsm.common.context.auth.manager.AuthenticationManager; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.net.MalformedURLException; import java.time.YearMonth; import java.time.ZoneId; import java.time.format.DateTimeFormatter; @RequiredArgsConstructor @Service public class ApplicationManager implements ApplicationService { private final ApplicationFactory applicationFactory; private final ApplicantRepository applicantRepository; private final ImageService imageService; private final ApplicantDocsService applicantDocsService; private final ApplicationApplicantRepository applicationApplicantRepository; private final SchoolRepository schoolRepository; private final GraduationApplicationRepository graduationApplicationRepository; private final QualificationExamApplicationRepository qualificationExamApplicationRepository; private final ScoreCalculator scoreCalculator; private final ApplicantStatusService applicantStatusService; @Override public void writeSelfIntroduce(String content) { long receiptCode = AuthenticationManager.getUserReceiptCode(); applicantDocsService.writeSelfIntroduce(receiptCode, content); } @Override public void writeStudyPlan(String content) { long receiptCode = AuthenticationManager.getUserReceiptCode(); applicantDocsService.writeStudyPlan(receiptCode, content); } @Override public String getSelfIntroduce() { long receiptCode = AuthenticationManager.getUserReceiptCode(); return applicantDocsService.getSelfIntroduce(receiptCode); } @Override public String getStudyPlan() { long receiptCode = AuthenticationManager.getUserReceiptCode(); return applicantDocsService.getStudyPlan(receiptCode); } @Override public Page<School> getSchoolsByInformation(String information, Pageable pageable) { return schoolRepository.findByInformationContains(information, pageable); } @Override public void writeApplicationType(ApplicationRequest applicationRequest) { long receiptCode = AuthenticationManager.getUserReceiptCode(); if (applicationRequest.getEducationalStatus().equals("QUALIFICATION_EXAM")) { QualificationExamApplication qualificationExamApplication = applicationFactory.createQualificationExamApplicationIfNotExists(receiptCode); qualificationExamApplication.setQualifiedAt( YearMonth.parse(applicationRequest.getGraduatedAt(), DateTimeFormatter.ofPattern("yyyyMM") .withZone(ZoneId.of("Asia/Seoul"))) .atDay(1)); qualificationExamApplicationRepository.save(qualificationExamApplication); } else { GraduationApplication graduationApplication = applicationFactory.createGraduationApplicationIfNotExists(receiptCode); if (applicationRequest.getGraduatedAt() != null) { graduationApplication.setGraduatedAt( YearMonth.parse(applicationRequest.getGraduatedAt(), DateTimeFormatter.ofPattern("yyyyMM") .withZone(ZoneId.of("Asia/Seoul"))) .atDay(1)); } graduationApplication.setIsGraduated( applicationRequest.getEducationalStatus().equals("GRADUATE") ); graduationApplicationRepository.save(graduationApplication); } applicationApplicantRepository.writeApplicationType(receiptCode, applicationRequest); } @Override public void writeGraduatedInformation(GraduatedInformationRequest information) { long receiptCode = AuthenticationManager.getUserReceiptCode(); String educationalStatus = applicationApplicantRepository.getEducationalStatus(receiptCode); if (educationalStatus == null) throw new EducationalStatusNotFoundException(); if (educationalStatus.equals("QUALIFICATION_EXAM")) throw new EducationalStatusUnmatchedException(); GraduationApplication graduationApplication = applicationFactory.createGraduationApplicationIfNotExists(receiptCode); graduationApplication.setSchoolTel(information.getSchoolTel()); graduationApplication.setSchool(schoolRepository.findByCode(information.getSchoolCode()) .orElseThrow(SchoolNotFoundException::new)); graduationApplication.setStudentNumber(information.getStudentNumber()); graduationApplicationRepository.save(graduationApplication); } @Override public void writeInformation(Information information) { long receiptCode = AuthenticationManager.getUserReceiptCode(); applicationApplicantRepository.writeInformation(receiptCode, information); } @Override public ApplicationResponse getApplicationType() { long receiptCode = AuthenticationManager.getUserReceiptCode(); String educationStatus = applicationApplicantRepository.getEducationalStatus(receiptCode); if (educationStatus != null && !educationStatus.equals("QUALIFICATION_EXAM")) { if (graduationApplicationRepository.findByReceiptCode(receiptCode).isPresent()) { GraduationApplication graduationApplication = graduationApplicationRepository.findByReceiptCode(receiptCode) .orElseThrow(ApplicationNotFoundException::new); if (graduationApplication.getGraduatedAt() != null) return applicationApplicantRepository.getApplicationType(receiptCode) .setGraduatedAt(DateTimeFormatter.ofPattern("yyyyMM") .withZone(ZoneId.of("Asia/Seoul")) .format(graduationApplication.getGraduatedAt())) .setIsGraduated(graduationApplication.getIsGraduated()); return applicationApplicantRepository.getApplicationType(receiptCode) .setIsGraduated(graduationApplication.getIsGraduated() != null && graduationApplication.getIsGraduated()); } } else { if (qualificationExamApplicationRepository.findByReceiptCode(receiptCode).isPresent()) { QualificationExamApplication qualificationExamApplication = qualificationExamApplicationRepository.findByReceiptCode(receiptCode) .orElseThrow(ApplicationNotFoundException::new); if (qualificationExamApplication.getQualifiedAt() != null) return applicationApplicantRepository.getApplicationType(receiptCode) .setGraduatedAt(DateTimeFormatter.ofPattern("yyyyMM") .withZone(ZoneId.of("Asia/Seoul")) .format(qualificationExamApplication.getQualifiedAt())); return applicationApplicantRepository.getApplicationType(receiptCode); } } return applicationApplicantRepository.getApplicationType(receiptCode); } @Override public GraduatedInformationResponse getGraduatedInformation() { long receiptCode = AuthenticationManager.getUserReceiptCode(); String educationalStatus = applicationApplicantRepository.getEducationalStatus(receiptCode); if (educationalStatus == null) throw new EducationalStatusNotFoundException(); if (educationalStatus.equals("QUALIFICATION_EXAM")) throw new EducationalStatusUnmatchedException(); GraduatedInformationResponse result = new GraduatedInformationResponse() .setInformation(applicationApplicantRepository.getInformation(receiptCode)); if (graduationApplicationRepository.findByReceiptCode(receiptCode).isPresent()) { GraduationApplication graduationApplication = graduationApplicationRepository.findByReceiptCode(receiptCode) .orElseThrow(ApplicationNotFoundException::new); result.setSchoolCode(graduationApplication.getSchoolCode()); if(graduationApplication.getSchoolCode() != null) result.setSchoolName( schoolRepository.findByCode(graduationApplication.getSchoolCode()) .orElseThrow(SchoolNotFoundException::new).getName() ); else result.setSchoolName(null); result.setSchoolTel(graduationApplication.getSchoolTel()); result.setIsGraduated(graduationApplication.getIsGraduated() != null && graduationApplication.getIsGraduated()); result.setStudentNumber(graduationApplication.getStudentNumber()); } result.setPhotoFileName(getImageUrl(result.getPhotoFileName())); return result; } @Override public InformationResponse getInformation() { long receiptCode = AuthenticationManager.getUserReceiptCode(); InformationResponse result = applicationApplicantRepository.getInformation(receiptCode); result.setPhotoFileName(getImageUrl(result.getPhotoFileName())); return result; } @Override public String uploadPhoto(MultipartFile multipartFile) { long receiptCode = AuthenticationManager.getUserReceiptCode(); InformationResponse result = applicationApplicantRepository.getInformation(receiptCode); if(result.getPhotoFileName() != null) imageService.delete(result.getPhotoFileName()); String fileName; try { fileName = imageService.upload(multipartFile, receiptCode); } catch (IOException e) { fileName = null; } applicationApplicantRepository.setPhotoFileName(receiptCode, fileName); return fileName; } @Override public void finalSubmit() { Applicant applicant = applicantRepository.findByReceiptCode(AuthenticationManager.getUserReceiptCode()); if (!checkType(applicant) || !checkInfo(applicant) || !checkScore(applicant) || !checkPhoto(applicant)) { throw new ProcessNotCompletedException(); } applicantStatusService.finalSubmit(applicant.getReceiptCode()); } private boolean checkType(Applicant applicant) { if (applicant.isQualificationExam()) { return qualificationExamApplicationRepository.findByReceiptCode(applicant.getReceiptCode()) .map(application -> (application.getQualifiedAt() != null) && isFilledType(applicant)) .orElse(false); } if (applicant.isGraduate()) { return graduationApplicationRepository.findByReceiptCode(applicant.getReceiptCode()) .map(application -> (application.getGraduatedAt() != null) && isFilledType(applicant)) .orElse(false); } return isFilledType(applicant); } private boolean isFilledType(Applicant applicant) { return !applicant.isEducationalStatusEmpty() && applicant.getApplicationType() != null && !isApplicationEmpty(applicant); } private boolean isApplicationEmpty(Applicant applicant) { if (applicant.isQualificationExam()) { return !qualificationExamApplicationRepository.existsByReceiptCode(applicant.getReceiptCode()); } else if (applicant.isProspectiveGraduate() || applicant.isGraduate()) { return !graduationApplicationRepository.existsByReceiptCode(applicant.getReceiptCode()); } return true; } private boolean checkInfo(Applicant applicant) { if (!checkType(applicant)) return false; if (applicant.isGraduate() || applicant.isProspectiveGraduate()) { GraduationApplication application = graduationApplicationRepository.findByReceiptCode(applicant.getReceiptCode()) .orElseThrow(ApplicationNotFoundException::new); return application.isFilledStudentInfo() && applicant.isFilledInfo(); } return applicant.isFilledInfo(); } private boolean checkScore(Applicant applicant) { if (!checkType(applicant)) return false; return scoreCalculator.isExists(applicant.getReceiptCode()); } private boolean checkPhoto(Applicant applicant) { return applicant.getPhotoFileName() != null; } private String getImageUrl(String photoFileName) { try { return (photoFileName != null) ? imageService.generateObjectUrl(photoFileName) : null; } catch (MalformedURLException e){ return null; } } }
47.624161
130
0.70885
0271a2b2189cfe281e6620ed397167b31b77ad34
1,117
package javaAdvanced.multidimensionalArrays.lab; import java.util.Arrays; import java.util.Scanner; public class Task6 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String separator = "\\s+"; int [][] matrix = createMatrix(separator, scanner); printDiagonals (matrix); } private static void printDiagonals(int[][] matrix) { for (int i = 0; i < matrix.length; i++) { System.out.print(matrix[i][i] + " "); } System.out.println(); for (int i = 0; i < matrix.length; i++) { System.out.print(matrix[matrix.length-1-i][i] + " "); } } private static int[][] createMatrix(String separator, Scanner scanner) { int rows = Integer.parseInt(scanner.nextLine()); int[][] matrix = new int[rows][]; for (int row = 0; row < rows; row++) { int[] currentRow = Arrays.stream(scanner.nextLine().split(separator)).mapToInt(Integer::parseInt).toArray(); matrix[row] = currentRow; } return matrix; } }
30.189189
120
0.573859
c807b084421157e96697542f1a452c4b6d44343c
2,930
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.oodt.cas.catalog.util; //JDK imports import java.io.InputStream; import java.io.OutputStream; //XStream imports import com.thoughtworks.xstream.XStream; /** * @author bfoster * @version $Revision$ * */ public class Serializer { protected ClassLoader classLoader; protected boolean usePluginUrls; public Serializer() { this(true); } public Serializer(boolean usePluginUrls) { this.usePluginUrls = usePluginUrls; this.refreshClassLoader(); } public void refreshClassLoader() { if (usePluginUrls) this.classLoader = new PluginClassLoader(); else this.classLoader = Serializer.class.getClassLoader(); } public void setUsePluginUrls(boolean usePluginUrls) { this.usePluginUrls = usePluginUrls; } public ClassLoader getClassLoader() { return classLoader; } /** * Serializes any java object into a java Serializable String * @param <T> Object type to be serialized * @param object The Object of type <T> to be serialized * @return A String for of the object arg */ public <T> String serializeObject(T object) { XStream xStream = new XStream(); return xStream.toXML(object); } public <T> void serializeObject(T object, OutputStream outStream) { XStream xStream = new XStream(); xStream.toXML(object, outStream); } /** * Deserializes any object that has been serialized by the serializedObject(T) method * @param <T> Type of Object that was originally serialized * @param clazz The class object representation of the object type * @param xmlObject The String for of the object to be deserialized * @return The deserialized object * @throws ClassNotFoundException * @throws InstantiationException * @throws IllegalAccessException */ public <T> T deserializeObject(Class<T> clazz, String xmlObject) { XStream xStream = new XStream(); xStream.setClassLoader(getClassLoader()); return (T) xStream.fromXML(xmlObject); } public <T> T deserializeObject(Class<T> clazz, InputStream inStream) { XStream xStream = new XStream(); xStream.setClassLoader(getClassLoader()); return (T) xStream.fromXML(inStream); } }
29.59596
86
0.741297
49687a1752eae4c392207eb28ca364fd082c8e35
1,366
package cn.edu.hbfu.server.controller; import cn.edu.hbfu.server.db.PersonDB; import cn.edu.hbfu.server.entity.Person; import cn.edu.hbfu.server.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping(value = "/table") public class TableController { @Autowired PersonService p; @GetMapping("/index/{talk}") public Map index(@PathVariable("talk") String talk) { Map<String, String> response = new HashMap<>(); System.out.println(talk); response.put("talk", talk); return response; } @GetMapping("/findall") public Map findall() { Map<String, List<Person>> res = new HashMap<>(); res.put("msg", p.findAll()); return res; } @PostMapping("/addperson") public Map add(@RequestBody Person person) { Map<String, String> res = new HashMap(); try { p.addPerson(person); res.put("msg", "成功"); } catch (Exception e) { res.put("msg", "失败"); e.printStackTrace(); } return res; } @DeleteMapping("/delete/{id}") public void delete(@PathVariable("id") Integer id) { p.delete(id); } }
26.269231
62
0.618594
5ea95a8bf4a7ee1a496ae40d48f63f3daf5d3ba6
2,059
/* Copyright 2014-2016 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cxx.tests; import org.moe.natj.processor.cxx.ITypeResolverPlugin; import org.moe.natj.processor.cxx.TypeResolverPluginConfiguration; public class TestTypeResolver implements ITypeResolverPlugin { private static final String CLASS_PREFIXES = "cxx/tests/binding/DynamicTypeTests$"; @Override public void setup(TypeResolverPluginConfiguration config) { config.registerType(1, CLASS_PREFIXES + "DynTypeA"); config.registerType(2, CLASS_PREFIXES + "DynTypeB"); config.registerType(3, CLASS_PREFIXES + "DynTypeC"); config.registerType(4, CLASS_PREFIXES + "DynTypeD"); config.registerType(11, CLASS_PREFIXES + "DynTypeX"); config.registerType(12, CLASS_PREFIXES + "DynTypeY"); config.registerType(13, CLASS_PREFIXES + "DynTypeZ"); config.registerType(14, CLASS_PREFIXES + "DynTypeW"); config.registerType(21, CLASS_PREFIXES + "DynTypeM"); config.registerType(22, CLASS_PREFIXES + "DynTypeN"); config.userHeaders.add("binding/DynamicTypes.hpp"); } @Override public boolean match(String internalName) { return internalName.startsWith(CLASS_PREFIXES); } @Override public String nativeTypeIDResolver(String nativeObject) { return "return reinterpret_cast<natj::cxx::tests::binding::DynTypeRoot*>(" + nativeObject + ")->getTID();"; } @Override public String getImplementingClass() { return CLASS_PREFIXES + "DynTypeA"; } }
37.436364
115
0.728995
c112c8c42fd9773f70832df4b42765ce10587796
605
package test.example2.car; import se.jbee.inject.binder.Installs; import se.jbee.inject.binder.LocalEnvModule; import se.jbee.inject.config.NamesBy; import se.jbee.inject.config.ProducesBy; import se.jbee.lang.Type; import test.example2.Car; import test.example2.car.pool.CarPoolEnvModule; @Installs(bundles = CarPoolEnvModule.class) public class CarEnvModule extends LocalEnvModule { @Override protected void declare() { bind(NamesBy.class).to(NamesBy.DECLARED_NAME); bind(ProducesBy.class) .to(ProducesBy.declaredMethods(false).returnTypeAssignableTo(Type.raw(Car.class))); } }
28.809524
91
0.781818
0c28ba0b978eafe1e4f3ce3ca50aa9aee7f1c86b
6,335
/* Part of the NETLab Hub, which is part of the NETLab Toolkit project - http://netlabtoolkit.org Copyright (c) 2006-2013 Ewan Branda NETLab Hub is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NETLab Hub is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with NETLab Hub. If not, see <http://www.gnu.org/licenses/>. */ package netlab.hub.core; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import netlab.hub.util.Logger; import netlab.hub.util.ThreadUtil; /** * Accepts messages from clients and dispatches them to the appropriate service. * Converts multithreaded socket client requests to a single thread thereby * guaranteeing services that they will only be called from one thread. * * @author * */ public class Dispatcher { List<ClientSession> expiredClients = new ArrayList<ClientSession>(); List<ClientSession> clients = new ArrayList<ClientSession>(); List<DispatcherPoller> pollers = new ArrayList<DispatcherPoller>(); boolean running = false; boolean processing = false; /** * */ public Dispatcher() { } /** * @param session * @throws ServiceException */ public synchronized void register(ClientSession session) { if (!clients.contains(session)) { clients.add(session); } } /** * @param client */ public synchronized void deregister(ClientSession client) { if (!expiredClients.contains(client)) { expiredClients.add(client); } } /** * */ public void start() { new Thread(new Runnable() { public void run() { // Start the maintenance thread. We process the clients as fast as possible // to avoid socket input stream overflow in case the client is sending // messages very quickly. running = true; processing = false; while (running) { processing = true; try { process(); } catch (Throwable t) { Logger.error("Error dispatching message", t); } processing = false; ThreadUtil.pause(10); // Tiny delay, so we don't hog the CPU. Is this needed? } } }, "Hub-Dispatcher").start(); } /** * This method is invoked by each iteration * of the main dispatcher maintenance loop. */ protected synchronized void process() { ClientSession client; // Remove any expired client sessions and give all services a chance // to take action when a client session has ended for (Iterator<ClientSession> it=expiredClients.iterator(); it.hasNext();) { client = it.next(); for (Iterator<Service> its=ServiceRegistry.getAll().iterator(); its.hasNext();) { its.next().sessionEnded(client); } // Remove all pollers that have been registered by this client for (Iterator<DispatcherPoller> itp=pollers.iterator(); itp.hasNext();) { if (itp.next().client == client) { itp.remove(); } } it.remove(); clients.remove(client); } // Process any available client messages for (Iterator<ClientSession> it=clients.iterator(); it.hasNext();) { client = it.next(); for (Iterator<ServiceMessage> it2=client.getMessages().iterator(); it2.hasNext();) { processMessage(it2.next(), client); } } // Process any currently registered pollers DispatcherPoller poller; boolean polled; for (Iterator<DispatcherPoller> it=pollers.iterator(); it.hasNext();) { poller = it.next(); polled = poller.tryPoll(this); if (polled) { // If this poller has been configured to run for a finite number // of times then remove it from the list of registered pollers // if it has completed its lifecycle if (poller.completed()) { Logger.debug("Removing registered poller for pattern ["+poller.getPattern()+"]"); it.remove(); } } } } /** * @param client */ public void processMessage(ServiceMessage message, ClientSession client) { try { DispatcherAction action = DispatcherAction.parse(message); action.perform(message, client, this); } catch (Exception e) { Logger.error("Error processing client message", e); } } /** * @param request * @throws ServiceException */ protected void dispatch(ServiceMessage request, ClientSession client) { if (!request.isValid()) { Logger.debug("Invalid request pattern ["+request+"]... ignoring."); return; } Service service = getService(request); if (service == null) { Logger.debug("No service exists for request ["+request+"]... ignoring."); return; } ServiceResponse response = new ServiceResponse(request, client); try { response.setFilters(service.getOutputFilters()); service.accept(request, response); } catch (Exception e) { Logger.debug("Error dispatching message ["+request+"]"); Logger.debug(e); return; } } /** * @param request * @return */ public Service getService(ServiceMessage request) { return ServiceRegistry.get(request.getServiceAddressString()); } /** * @param poller */ public synchronized void registerPoller(DispatcherPoller poller) { if (!pollers.contains(poller)) { pollers.add(poller); } } /** * @param poller * @return */ public synchronized boolean deregisterPoller(DispatcherPoller poller) { return pollers.remove(poller); } /** * @param client * @param pattern * @return */ public synchronized DispatcherPoller getRegisteredPoller(ClientSession client, ServiceMessage pattern) { for (Iterator<DispatcherPoller> it=pollers.iterator(); it.hasNext();) { DispatcherPoller poller = it.next(); if (poller.getClient() == client && poller.getPattern().equals(pattern)) { return poller; } } return null; } /** * */ public synchronized void dispose() { running = false; } /** * To support unit testing. * @return */ public List<ClientSession> getClients() { return this.clients; } /** * To support unit testing. * @return */ public List<DispatcherPoller> getPollers() { return this.pollers; } }
25.963115
105
0.685872
33b716dbaea25fe2ebc44b5c8eabaf62628a3a66
150
/** * Labelers set flags or characteristics of network links based on tags in the OSM data they are built from. */ package com.conveyal.r5.labeling;
37.5
108
0.76
c8b4512d3f6fc05d1666fd5bae4e927b53e8a25f
3,584
/* * Copyright (c) EngineHub * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.enginehub.jinglenote.bukkit; import org.bukkit.Sound; import org.bukkit.SoundCategory; import org.bukkit.entity.Player; import org.enginehub.jinglenote.Instrument; import org.enginehub.jinglenote.JingleNotePlayer; import org.enginehub.jinglenote.Note; import org.enginehub.jinglenote.sequencer.JingleSequencer; /** * A JingleNote player for Bukkit players */ public class BukkitJingleNotePlayer extends JingleNotePlayer { private final Player player; /** * Create a player for a given sequencer. * * @param sequencer The sequencer */ public BukkitJingleNotePlayer(Player player, JingleSequencer sequencer) { super(sequencer); this.player = player; } @Override public void playNote(Note note) { if(!isActive()) return; player.playSound(player.getLocation(), toSound(note.getInstrument()), SoundCategory.RECORDS, note.getVelocity(), note.getPitch()); } @Override public boolean isActive() { return super.isActive() && player.isValid() && player.isOnline(); } private static Sound toSound(Instrument instrument) { switch(instrument) { case BASS: return Sound.BLOCK_NOTE_BLOCK_BASS; case SNARE: return Sound.BLOCK_NOTE_BLOCK_SNARE; case HAT: return Sound.BLOCK_NOTE_BLOCK_HAT; case BANJO: return Sound.BLOCK_NOTE_BLOCK_BANJO; case BASEDRUM: return Sound.BLOCK_NOTE_BLOCK_BASEDRUM; case BELL: return Sound.BLOCK_NOTE_BLOCK_BELL; case BIT: return Sound.BLOCK_NOTE_BLOCK_BIT; case CHIME: return Sound.BLOCK_NOTE_BLOCK_CHIME; case COW_BELL: return Sound.BLOCK_NOTE_BLOCK_COW_BELL; case DIDGERIDOO: return Sound.BLOCK_NOTE_BLOCK_DIDGERIDOO; case FLUTE: return Sound.BLOCK_NOTE_BLOCK_FLUTE; case XYLOPHONE: return Sound.BLOCK_NOTE_BLOCK_XYLOPHONE; case IRON_XYLOPHONE: return Sound.BLOCK_NOTE_BLOCK_IRON_XYLOPHONE; case PLING: return Sound.BLOCK_NOTE_BLOCK_PLING; case GUITAR: return Sound.BLOCK_NOTE_BLOCK_GUITAR; case HARP: default: return Sound.BLOCK_NOTE_BLOCK_HARP; } } }
35.485149
138
0.666574
4d4890c847f4b6ca2ee471f5d73a210905255623
2,785
/***************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ****************************************************************/ package org.apache.cayenne.remote.service; import junit.framework.TestCase; import org.apache.cayenne.CayenneRuntimeException; import org.apache.cayenne.query.Query; import org.apache.cayenne.remote.QueryMessage; import org.apache.cayenne.remote.RemoteSession; import org.apache.cayenne.util.Util; public class BaseRemoteServiceTest extends TestCase { public void testProcessMessageExceptionSerializability() throws Throwable { BaseRemoteService handler = new BaseRemoteService() { @Override protected ServerSession createServerSession() { return new ServerSession(new RemoteSession("a"), null); } @Override protected ServerSession createServerSession(String name) { return createServerSession(); } @Override protected ServerSession getServerSession() { return createServerSession(); } }; try { handler.processMessage(new QueryMessage(null) { @Override public Query getQuery() { // serializable exception thrown throw new CayenneRuntimeException(); } }); fail("Expected to throw"); } catch (Exception ex) { Util.cloneViaSerialization(ex); } try { handler.processMessage(new QueryMessage(null) { @Override public Query getQuery() { // non-serializable exception thrown throw new MockUnserializableException(); } }); fail("Expected to throw"); } catch (Exception ex) { Util.cloneViaSerialization(ex); } } }
33.154762
79
0.592819
0c2f8dbf1d070a0810cb4c136179c347934d261a
14,863
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.pom.core.impl; import com.intellij.lang.ASTNode; import com.intellij.lang.FileASTNode; import com.intellij.model.ModelBranch; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.PomModel; import com.intellij.pom.PomModelAspect; import com.intellij.pom.PomTransaction; import com.intellij.pom.event.PomModelEvent; import com.intellij.pom.event.PomModelListener; import com.intellij.pom.impl.PomTransactionBase; import com.intellij.pom.tree.TreeAspect; import com.intellij.pom.wrappers.PsiEventWrapperAspect; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.impl.*; import com.intellij.psi.impl.smartPointers.SmartPointerManagerImpl; import com.intellij.psi.impl.source.DummyHolder; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.tree.FileElement; import com.intellij.psi.impl.source.tree.TreeUtil; import com.intellij.psi.text.BlockSupport; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ThrowableRunnable; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Stack; import com.intellij.util.lang.CompoundRuntimeException; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class PomModelImpl extends UserDataHolderBase implements PomModel { private final Project myProject; private final TreeAspect myTreeAspect; private final PsiEventWrapperAspect myPsiAspect; private final Collection<PomModelListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); public PomModelImpl(@NotNull Project project) { myProject = project; myTreeAspect = TreeAspect.getInstance(project); myPsiAspect = new PsiEventWrapperAspect(myTreeAspect); } @Override public <T extends PomModelAspect> T getModelAspect(@NotNull Class<T> aClass) { //noinspection unchecked return myTreeAspect.getClass().equals(aClass) ? (T)myTreeAspect : myPsiAspect.getClass().equals(aClass) ? (T)myPsiAspect : null; } @Override public void addModelListener(@NotNull PomModelListener listener) { myListeners.add(listener); } @Override public void addModelListener(@NotNull final PomModelListener listener, @NotNull Disposable parentDisposable) { addModelListener(listener); Disposer.register(parentDisposable, () -> removeModelListener(listener)); } @Override public void removeModelListener(@NotNull PomModelListener listener) { myListeners.remove(listener); } @SuppressWarnings("SSBasedInspection") private final ThreadLocal<Stack<PomTransaction>> myTransactionStack = ThreadLocal.withInitial(Stack::new); @Override public void runTransaction(@NotNull PomTransaction transaction) throws IncorrectOperationException{ if (!isAllowPsiModification()) { throw new IncorrectOperationException("Must not modify PSI inside save listener"); } ProgressManager.getInstance().executeNonCancelableSection(() -> { PsiElement changeScope = transaction.getChangeScope(); PsiFile containingFileByTree = getContainingFileByTree(changeScope); Document document = startTransaction(transaction, containingFileByTree); PomTransaction block = getBlockingTransaction(changeScope); if (block != null) { block.getAccumulatedEvent().beforeNestedTransaction(); } List<Throwable> throwables = new ArrayList<>(0); DebugUtil.performPsiModification(null, ()->{ try{ Stack<PomTransaction> blockedAspects = myTransactionStack.get(); blockedAspects.push(transaction); final PomModelEvent event; try{ transaction.run(); event = transaction.getAccumulatedEvent(); } catch (ProcessCanceledException e) { throw e; } catch(Exception e){ throwables.add(e); return; } finally{ blockedAspects.pop(); } if(block != null){ block.getAccumulatedEvent().merge(event); return; } if (event.getChangedAspects().contains(myTreeAspect)) { updateDependentAspects(event); } for (final PomModelListener listener : myListeners) { final Set<PomModelAspect> changedAspects = event.getChangedAspects(); for (PomModelAspect modelAspect : changedAspects) { if (listener.isAspectChangeInteresting(modelAspect)) { listener.modelChanged(event); break; } } } } catch (ProcessCanceledException e) { throw e; } catch (Throwable t) { throwables.add(t); } finally { try { if (containingFileByTree != null) { commitTransaction(containingFileByTree, document); } } catch (ProcessCanceledException e) { throw e; } catch (Throwable t) { throwables.add(t); } if (!throwables.isEmpty()) CompoundRuntimeException.throwIfNotEmpty(throwables); } }); }); } protected void updateDependentAspects(PomModelEvent event) { myPsiAspect.update(event); } @Nullable private PomTransaction getBlockingTransaction(PsiElement changeScope) { Stack<PomTransaction> blockedAspects = myTransactionStack.get(); ListIterator<PomTransaction> iterator = blockedAspects.listIterator(blockedAspects.size()); while (iterator.hasPrevious()) { PomTransaction transaction = iterator.previous(); if (PsiTreeUtil.isAncestor(getContainingFileByTree(transaction.getChangeScope()), changeScope, false)) { return transaction; } } return null; } private void commitTransaction(@NotNull PsiFile containingFileByTree, @Nullable Document document) { final PsiDocumentManagerBase manager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject); final PsiToDocumentSynchronizer synchronizer = manager.getSynchronizer(); boolean isFromCommit = manager.isCommitInProgress(); boolean isPhysicalPsiChange = !isFromCommit && !synchronizer.isIgnorePsiEvents(); if (isPhysicalPsiChange) { reparseParallelTrees(containingFileByTree, synchronizer); } boolean docSynced = false; if (document != null) { final int oldLength = containingFileByTree.getTextLength(); docSynced = synchronizer.commitTransaction(document); if (docSynced) { sendAfterChildrenChangedEvent(containingFileByTree, oldLength); } } if (isPhysicalPsiChange && docSynced) { containingFileByTree.getViewProvider().contentsSynchronized(); } } private void reparseParallelTrees(PsiFile changedFile, PsiToDocumentSynchronizer synchronizer) { List<PsiFile> allFiles = changedFile.getViewProvider().getAllFiles(); if (allFiles.size() <= 1) { return; } CharSequence newText = changedFile.getNode().getChars(); for (final PsiFile file : allFiles) { FileElement fileElement = file == changedFile ? null : ((PsiFileImpl)file).getTreeElement(); Runnable changeAction = fileElement == null ? null : reparseFile(file, fileElement, newText); if (changeAction == null) continue; synchronizer.setIgnorePsiEvents(true); try { CodeStyleManager.getInstance(file.getProject()).performActionWithFormatterDisabled(changeAction); } finally { synchronizer.setIgnorePsiEvents(false); } } } /** * Reparses the file and returns a runnable which actually changes the PSI structure to match the new text. */ @Nullable @ApiStatus.Internal public Runnable reparseFile(@NotNull PsiFile file, @NotNull FileElement treeElement, @NotNull CharSequence newText) { TextRange changedPsiRange = ChangedPsiRangeUtil.getChangedPsiRange(file, treeElement, newText); if (changedPsiRange == null) return null; ProgressIndicator indicator = EmptyProgressIndicator.notNullize(ProgressIndicatorProvider.getGlobalProgressIndicator()); DiffLog log = BlockSupport.getInstance(myProject).reparseRange(file, treeElement, changedPsiRange, newText, indicator, treeElement.getText()); return () -> runTransaction(new PomTransactionBase(file) { @Override public @NotNull PomModelEvent runInner() throws IncorrectOperationException { return new PomModelEvent(PomModelImpl.this, log.performActualPsiChange(file)); } }); } @Nullable @Contract("_,null -> null") private Document startTransaction(@NotNull PomTransaction transaction, @Nullable PsiFile psiFile) { final PsiDocumentManagerBase manager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject); final PsiToDocumentSynchronizer synchronizer = manager.getSynchronizer(); final PsiElement changeScope = transaction.getChangeScope(); if (psiFile != null && !(psiFile instanceof DummyHolder) && !manager.isCommitInProgress()) { PsiUtilCore.ensureValid(psiFile); } boolean physical = changeScope.isPhysical(); if (synchronizer.toProcessPsiEvent()) { // fail-fast to prevent any psi modifications that would cause psi/document text mismatch if (isDocumentUncommitted(psiFile)) { throw new IllegalStateException("Attempt to modify PSI for non-committed Document!"); } CommandProcessor commandProcessor = CommandProcessor.getInstance(); if (physical && !commandProcessor.isUndoTransparentActionInProgress() && commandProcessor.getCurrentCommand() == null) { throw new IncorrectOperationException("Must not change PSI outside command or undo-transparent action. See com.intellij.openapi.command.WriteCommandAction or com.intellij.openapi.command.CommandProcessor"); } } VirtualFile vFile = psiFile == null ? null : psiFile.getViewProvider().getVirtualFile(); if (psiFile != null) { ((SmartPointerManagerImpl) SmartPointerManager.getInstance(myProject)).fastenBelts(vFile); if (psiFile instanceof PsiFileImpl) { ((PsiFileImpl)psiFile).beforeAstChange(); } } sendBeforeChildrenChangeEvent(changeScope); Document document = psiFile == null || psiFile instanceof DummyHolder ? null : physical || ModelBranch.getPsiBranch(psiFile) != null ? FileDocumentManager.getInstance().getDocument(vFile) : FileDocumentManager.getInstance().getCachedDocument(vFile); if (document != null) { synchronizer.startTransaction(myProject, document, psiFile); } return document; } private boolean isDocumentUncommitted(@Nullable PsiFile file) { if (file == null) return false; PsiDocumentManager manager = PsiDocumentManager.getInstance(myProject); Document cachedDocument = manager.getCachedDocument(file); return cachedDocument != null && manager.isUncommited(cachedDocument); } @Nullable private static PsiFile getContainingFileByTree(@NotNull final PsiElement changeScope) { // there could be pseudo physical trees (JSPX/JSP/etc.) which must not translate // any changes to document and not to fire any PSI events final PsiFile psiFile; final ASTNode node = changeScope.getNode(); if (node == null) { psiFile = changeScope.getContainingFile(); } else { final FileASTNode fileElement = TreeUtil.getFileElement(node); // assert fileElement != null : "Can't find file element for node: " + node; // Hack. the containing tree can be invalidated if updating supplementary trees like HTML in JSP. if (fileElement == null) return null; psiFile = (PsiFile)fileElement.getPsi(); } return psiFile.getNode() != null ? psiFile : null; } private static volatile boolean allowPsiModification = true; public static <T extends Throwable> void guardPsiModificationsIn(@NotNull ThrowableRunnable<T> runnable) throws T { ApplicationManager.getApplication().assertWriteAccessAllowed(); boolean old = allowPsiModification; try { allowPsiModification = false; runnable.run(); } finally { allowPsiModification = old; } } public static boolean isAllowPsiModification() { return allowPsiModification; } private void sendBeforeChildrenChangeEvent(@NotNull PsiElement scope) { if (!shouldFirePhysicalPsiEvents(scope)) { getPsiManager().beforeChange(false); return; } PsiTreeChangeEventImpl event = new PsiTreeChangeEventImpl(getPsiManager()); event.setParent(scope); event.setFile(scope.getContainingFile()); TextRange range = scope.getTextRange(); event.setOffset(range == null ? 0 : range.getStartOffset()); event.setOldLength(scope.getTextLength()); // the "generic" event is being sent on every PSI change. It does not carry any specific info except the fact that "something has changed" event.setGenericChange(true); getPsiManager().beforeChildrenChange(event); } @ApiStatus.Internal public static boolean shouldFirePhysicalPsiEvents(@NotNull PsiElement scope) { return scope.isPhysical() && ModelBranch.getPsiBranch(scope) == null; // injections are physical even in non-physical PSI :( } private void sendAfterChildrenChangedEvent(@NotNull PsiFile scope, int oldLength) { if (!shouldFirePhysicalPsiEvents(scope)) { getPsiManager().afterChange(false); return; } PsiTreeChangeEventImpl event = new PsiTreeChangeEventImpl(getPsiManager()); event.setParent(scope); event.setFile(scope); event.setOffset(0); event.setOldLength(oldLength); event.setGenericChange(true); getPsiManager().childrenChanged(event); } @NotNull private PsiManagerImpl getPsiManager() { return (PsiManagerImpl)PsiManager.getInstance(myProject); } }
39.320106
214
0.717217
9f2ef59de2f37a0f7dc42b2fbc1ebc4ade6ebc6b
695
package top.guoziyang.springframework.factory; import top.guoziyang.springframework.entity.BeanDefinition; /** * Bean工厂接口 * * @author ziyang */ public interface BeanFactory { /** * 根据名称从容器中获取bean * @param name bean的名字 * @return bean实例对象 */ Object getBean(String name) throws Exception; /** * 根据类从容器中获取bean * @param clazz bean的类对象 * @return bean实例对象 */ Object getBean(Class clazz) throws Exception; /** * 向工厂中注册bean定义 * @param name bean的名字 * @param beanDefinition bean的定义对象 * @throws Exception 可能出现的异常 */ void registerBeanDefinition(String name, BeanDefinition beanDefinition) throws Exception; }
19.857143
93
0.664748
db3c0e691b0a3829dfe77faee5199d69ae05e3c8
15,789
/* FRODO: a FRamework for Open/Distributed Optimization Copyright (C) 2008-2013 Thomas Leaute, Brammert Ottens & Radoslaw Szymanek FRODO is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FRODO is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. How to contact the authors: <http://frodo2.sourceforge.net/> */ package frodo2.algorithms.odpop; import java.util.List; import org.jdom2.Element; import frodo2.algorithms.AgentInterface; import frodo2.algorithms.StatsReporter; import frodo2.algorithms.odpop.Good; import frodo2.algorithms.odpop.goodsTree.GoodsTree; import frodo2.algorithms.odpop.goodsTree.InnerNodeTree.InnerNodeTree; import frodo2.algorithms.odpop.goodsTree.InnerNodeTree.LeafNode; import frodo2.algorithms.odpop.goodsTree.leafNodeTree.LeafNodeTree; import frodo2.communication.Message; import frodo2.solutionSpaces.Addable; import frodo2.solutionSpaces.DCOPProblemInterface; import frodo2.solutionSpaces.UtilitySolutionSpace; /** The UTIL propagation phase for O-DPOP * @author brammert * @param <Val> type used for variable values * @param <U> type used for utility values * * @todo make it work for minimisation problems as well! * */ public class UTILpropagation < Val extends Addable<Val>, U extends Addable<U> > extends UTILpropagationFullDomain<Val, U, LeafNode<U>> { /** * Constructor for the statsreporter * * @param problem the overall problem * @param parameters the description of what statistics should be reported (currently unused) */ public UTILpropagation (Element parameters, DCOPProblemInterface<Val, U> problem) { super(parameters, problem); } /** * Constructor * * @param problem The problem description * @param parameters The parameters */ public UTILpropagation (DCOPProblemInterface<Val, U> problem, Element parameters) { super(problem, parameters); } /** * Alternative constructor not using XML * * @param problem The problem description */ public UTILpropagation (DCOPProblemInterface<Val, U> problem) { super(problem); } /** The algorithm * @see StatsReporter#notifyIn(Message) */ @SuppressWarnings("unchecked") public void notifyIn(Message msg) { String type = msg.getType(); if(this.agentFinished) return; // put the stats reporter stuff here if(type.equals(OPT_UTIL_MSG_TYPE)) { OptUtilMessage<U> msgCast = (OptUtilMessage<U>)msg; if (!silent) System.out.println("Optimal utility for component rooted at `" + msgCast.getVariable() + "\': " + msgCast.getUtility()); if (this.optTotalUtil == null) { this.optTotalUtil = msgCast.getUtility(); } else this.optTotalUtil = this.optTotalUtil.add(msgCast.getUtility()); Long time = queue.getCurrentMessageWrapper().getTime(); if(finalTime < time) finalTime = time; return; } else if (type.equals(UTIL_STATS_MSG_TYPE)) { // we are in stats gatherer mode this.maxMsgDim = Math.max(this.maxMsgDim, ((StatsMessage) msg).getMsgDim()); return; } else if (type.equals(AgentInterface.AGENT_FINISHED)) { this.reset(); this.agentFinished = true; return; } if(!started) init(); if (type.equals(UTIL_MSG)) { UTILmsg<Val, U> msgCast = (UTILmsg<Val, U>)msg; VariableInfo varInfo = infos[variablePointer.get(msgCast.getReceiver())]; String sender = msgCast.getSender(); processGOOD(varInfo, msgCast.getGood(varInfo.tree.getChildSeparatorReportingOrder(varInfo.childrenPointer.get(sender))), sender, null, null); } else if (type.equals(UTIL_MSG_VARS)) { UTILvarsMsg<Val, U> msgCast = (UTILvarsMsg<Val, U>)msg; VariableInfo varInfo = infos[variablePointer.get(msgCast.getReceiver())]; String sender = msgCast.getSender(); varInfo.tree.setChildrenSeparator(varInfo.childrenPointer.get(sender), msgCast.getVariables()); processGOOD(varInfo, msgCast.getGood(), sender, null, null); } else if (type.equals(UTIL_MSG_DOM)) { UTILdomMsg<Val, U> msgCast = (UTILdomMsg<Val, U>)msg; VariableInfo varInfo = infos[variablePointer.get(msgCast.getReceiver())]; String sender = msgCast.getSender(); String[] variables = varInfo.tree.getChildSeparatorReportingOrder(varInfo.childrenPointer.get(sender)); int[] domInfo = msgCast.getDomInfo(); processGOOD(varInfo, msgCast.getGood(variables), sender, domInfo, variables); } else if (type.equals(UTIL_MSG_DOM_VARS)) { UTILvarsMsgWithDom<Val, U> msgCast = (UTILvarsMsgWithDom<Val, U>)msg; VariableInfo varInfo = infos[variablePointer.get(msgCast.getReceiver())]; String[] variables = msgCast.getVariables(); int[] domInfo = msgCast.getDomInfo(); String sender = msgCast.getSender(); varInfo.tree.setChildrenSeparator(varInfo.childrenPointer.get(sender), variables); processGOOD(varInfo, msgCast.getGood(), sender, domInfo, variables); } else { super.notifyIn(msg); } } /** @see frodo2.algorithms.odpop.UTILpropagationFullDomain#newVariableInfoInstanceInnerNode(java.lang.String, java.util.List, java.lang.String, Val[], java.util.List, int, frodo2.solutionSpaces.Addable) */ public VariableInfo newVariableInfoInstanceInnerNode(String var, List<String> children, String parent, Val[] ownVariableDomain, List<UtilitySolutionSpace<Val, U>> usedSpaces, int numberOfChildren, U zeroUtility) { return new VariableInfo(var, parent, children.toArray(new String[0]), new InnerNodeTree<Val, U, LeafNode<U>>(var, ownVariableDomain, usedSpaces, numberOfChildren, problem.getZeroUtility(), leafNodeInstance(), infeasibleUtil, maximize, collectStats)); } /** @see frodo2.algorithms.odpop.UTILpropagationFullDomain#newVariableInfoInstanceLeafNode(java.lang.String, java.util.List, java.lang.String, Val[], java.util.List, int, frodo2.solutionSpaces.Addable) */ public VariableInfo newVariableInfoInstanceLeafNode(String var, List<String> children, String parent, Val[] ownVariableDomain, List<UtilitySolutionSpace<Val, U>> usedSpaces, int numberOfChildren, U zeroUtility) { return new VariableInfo(var, parent, children.toArray(new String[0]), new LeafNodeTree<Val, U, LeafNode<U>>(var, ownVariableDomain, usedSpaces, problem.getZeroUtility(), infeasibleUtil, maximize, collectStats)); } /** * @author Brammert Ottens, 10 feb. 2011 * @return a new instance of a leafnode */ protected LeafNode<U> leafNodeInstance() { return new LeafNode<U>(); } /** @see frodo2.algorithms.odpop.UTILpropagationFullDomain#utilPropagationFinished(java.lang.String, frodo2.algorithms.odpop.goodsTree.GoodsTree, frodo2.solutionSpaces.Addable, int) */ @Override protected void utilPropagationFinished(String variableID, GoodsTree<Val, U, LeafNode<U>> tree, U utility, int domainSize) { queue.sendMessage(AgentInterface.STATS_MONITOR, new OptUtilMessage<U>(utility, variableID)); queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsMessage(domainSize)); // start the VALUE propagation queue.sendMessageToSelf(new GoodsTreeMessage<Val, U, LeafNode<U>>(tree, variableID)); } /** * This method starts the algorithm for the specified variable, i.e. if the variable is the root an ASK message * is sent. If not an ASK message is sent if an ASK message has been received * * @param variable The variable info * @param varIndex The index of the variable */ public void startProcess(VariableInfo variable, int varIndex) { // if the variable is the root, it starts by sending an ASK message to all its children if(variable.root) { if(variable.children.length == 0) { // the variable is a singleton Good<Val, U> aMax = variable.tree.getAmax(); if(aMax == null) { if(LOG) log(variable.variableID, this.infeasibleUtil.toString()); // OptUtilMessage<U> output = new OptUtilMessage<U>(this.infeasibleUtil, variable.variableID); // queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsMessage(variable.tree.getFinalDomainSize().length)); // queue.sendMessage(AgentInterface.STATS_MONITOR, output); // queue.sendMessageToSelf(new GoodsTreeMessage<Val, U, LeafNode<U>>(null, variable.variableID)); utilPropagationFinished(variable.variableID, null, this.infeasibleUtil, variable.tree.getFinalDomainSize().length); } else { if(LOG) log(variable.variableID, aMax.toString()); variable.tree.removeAMax(); utilPropagationFinished(variable.variableID, variable.tree, aMax.getUtility(), variable.tree.getFinalDomainSize().length); } } else { for(int i = 0; i < variable.children.length; i++) { String child = variable.children[i]; variable.done[i] = true; sendMessageToVariable(child, variable.getAskMessage(i), variable.variableID); } } } else if(receivedASK[varIndex]) { // if we already received an ASK message, process it processASK(variable); } } /** * Method used to process the GOOD messages received by this agent * * @param variable The variable information * @param g The good received * @param sender The sender of the good * @param domInfo domain size info reported by the child * @param variables the variables for which domain size info is reported */ private void processGOOD(VariableInfo variable, Good<Val, U> g, String sender, int[] domInfo, String[] variables) { if(LOG) log(variable.variableID, "Received a GOOD from " + sender +": " + g ); int childIndex = variable.childrenPointer.get(sender); boolean newVariable = ((InnerNodeTree<Val, U, LeafNode<U>>)variable.tree).add(g, childIndex) || variable.getNewVariable(); if(LOG) log(variable.variableID, variable.tree.toString()); if(domInfo != null) variable.tree.setFinalDomainSize(variables, domInfo); variable.done[childIndex] = false; Good<Val, U> aMax = variable.tree.getAmax(); if(aMax != null) { if(variable.root) { variable.tree.removeAMax(); if(!variable.terminated) { variable.terminated = true; queue.sendMessage(AgentInterface.STATS_MONITOR, new OptUtilMessage<U>(aMax.getUtility(), variable.variableID)); queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsMessage(variable.tree.getFinalDomainSize().length)); // start the VALUE propagation queue.sendMessageToSelf(new GoodsTreeMessage<Val, U, LeafNode<U>>(variable.tree, variable.variableID)); } } else if (!variable.responded) { variable.tree.removeAMax(); if(newVariable) { variable.setNewVariable(false); if(variable.tree.stillToSend() && variable.tree.hasFullInfo()) sendMessageToVariable(variable.parent, new UTILvarsMsgWithDom<Val, U>(variable.variableID, variable.parent, aMax, variable.tree.getFinalDomainSize()), variable.variableID); else sendMessageToVariable(variable.parent, new UTILvarsMsg<Val, U>(variable.variableID, variable.parent, aMax), variable.variableID); } else { if(variable.tree.stillToSend() && variable.tree.hasFullInfo()) sendMessageToVariable(variable.parent, new UTILdomMsg<Val, U>(variable.variableID, variable.parent, aMax, variable.tree.getFinalDomainSize()), variable.variableID); else sendMessageToVariable(variable.parent, new UTILmsg<Val, U>(variable.variableID, variable.parent, aMax), variable.variableID); } variable.responded = true; } } else if (!variable.responded) { variable.done[childIndex] = true; sendMessageToVariable(sender, variable.getAskMessage(sender), variable.variableID); } } /** * Method to process the ASK messages received by this agent * @param variable The variable information */ @Override protected void processASK(VariableInfo variable) { if(LOG) log(variable.variableID, "Received an ASK message from " + variable.parent); Good<Val, U> aMax = variable.tree.getAmax(); if(aMax != null) { variable.tree.removeAMax(); if(variable.root) { queue.sendMessage(AgentInterface.STATS_MONITOR, new OptUtilMessage<U>(aMax.getUtility(), variable.variableID)); queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsMessage(variable.tree.getFinalDomainSize().length)); // start the VALUE propagation } else { if(variable.getNewVariable()) { variable.setNewVariable(false); if(variable.tree.stillToSend() && variable.tree.hasFullInfo()) sendMessageToVariable(variable.parent, new UTILvarsMsgWithDom<Val, U>(variable.variableID, variable.parent, aMax, variable.tree.getFinalDomainSize()), variable.variableID); else sendMessageToVariable(variable.parent, new UTILvarsMsg<Val, U>(variable.variableID, variable.parent, aMax), variable.variableID); } else { if(variable.tree.stillToSend() && variable.tree.hasFullInfo()) sendMessageToVariable(variable.parent, new UTILdomMsg<Val, U>(variable.variableID, variable.parent, aMax, variable.tree.getFinalDomainSize()), variable.variableID); else sendMessageToVariable(variable.parent, new UTILmsg<Val, U>(variable.variableID, variable.parent, aMax), variable.variableID); } variable.responded = true; } } else if(variable.tree.hasMore() && !variable.infeasible) { for(int i = 0; i < variable.children.length; i++) { if(LOG) log(variable.variableID, "" + variable.done[i]); if(!variable.done[i]) { variable.done[i] = true; String child = variable.children[i]; sendMessageToVariable(child, variable.getAskMessage(i), variable.variableID); } } variable.responded = false; } else { sendMessageToVariable(variable.parent, new DONEmsg(variable.variableID, variable.parent), variable.variableID); variable.responded = true; } if(LOG) log(variable.variableID, variable.toString()); } /** * Method sets the entry for the corresponding agent of the done array in variable to true * @param variable The variables to whom this message has been sent * @param sender The sender of the message */ @Override public void processDONE(VariableInfo variable, String sender) { if(LOG) log(variable.variableID, "Received a DONE message from " + sender); int pointer = variable.childrenPointer.get(sender); variable.done[pointer] = true; variable.infeasible = ((InnerNodeTree<Val, U, LeafNode<U>>)variable.tree).setChildDone(pointer); if(LOG) log(variable.variableID, variable.toString()); if(variable.root) { Good<Val, U> aMax = variable.tree.getAmax(); if(aMax != null) { variable.tree.removeAMax(); if(!variable.terminated) { variable.terminated = true; queue.sendMessage(AgentInterface.STATS_MONITOR, new OptUtilMessage<U>(aMax.getUtility(), variable.variableID)); queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsMessage(variable.tree.getFinalDomainSize().length)); // start the VALUE propagation queue.sendMessageToSelf(new GoodsTreeMessage<Val, U, LeafNode<U>>(variable.tree, variable.variableID)); } } else if(variable.infeasible && !variable.terminated) { variable.terminated = true; queue.sendMessage(AgentInterface.STATS_MONITOR, new OptUtilMessage<U>(this.infeasibleUtil, variable.variableID)); queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsMessage(variable.tree.getFinalDomainSize().length)); // start the VALUE propagation queue.sendMessageToSelf(new GoodsTreeMessage<Val, U, LeafNode<U>>(null, variable.variableID)); } } else if(!variable.responded) { this.processASK(variable); } } }
41.769841
252
0.737095
971d7d4b8c7979e99fd7e6ed477f44c659883058
1,179
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2020 - 2021 The JfrUnit authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.moditect.jfrunit.generator; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvFileSource; public class PascalToSnakeCaseTest { @ParameterizedTest @CsvFileSource(resources = "/pascalToSnakeCaseTest.csv", numLinesToSkip = 1) public void eventNameToSnakeCase(String input, String expected) { Assertions.assertEquals(expected, JfrUnitConstantsGenerator.pascalCaseToSnakeCase(input)); } }
35.727273
80
0.751484
b63c1138f063270c1613322a13c54f5a2bfba7c9
644
package com.springmvc.pojo; import java.io.Serializable; /** * Ȩ�� * ��id��ʶ���洢Ȩ�޵�ģ������ * * @author shhz */ public class Jurisdiction implements Serializable { private int j_id;// Ȩ��id private String j_name;// Ȩ��ģ���� public int getJ_id() { return j_id; } public void setJ_id(int j_id) { this.j_id = j_id; } public String getJ_name() { return j_name; } public void setJ_name(String j_name) { this.j_name = j_name; } public Jurisdiction(int j_id, String j_name) { super(); this.j_id = j_id; this.j_name = j_name; } public Jurisdiction() { super(); // TODO Auto-generated constructor stub } }
15.333333
51
0.642857
d40cd381dbc45dbe8634da84985049a62bcc0820
7,776
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.coders; import com.google.common.collect.ImmutableList; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.WeakHashMap; import javax.annotation.Nullable; import org.apache.beam.sdk.PipelineRunner; import org.apache.beam.sdk.values.TypeDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A {@link Coder} for Java classes that implement {@link Serializable}. * * <p>To use, specify the coder type on a PCollection: * * <pre>{@code * PCollection<MyRecord> records = * foo.apply(...).setCoder(SerializableCoder.of(MyRecord.class)); * }</pre> * * <p>{@link SerializableCoder} does not guarantee a deterministic encoding, as Java serialization * may produce different binary encodings for two equivalent objects. * * @param <T> the type of elements handled by this coder */ public class SerializableCoder<T extends Serializable> extends CustomCoder<T> { /* * A thread safe set containing classes which we have warned about. * Note that we specifically use a weak hash map to allow for classes to be unloaded. */ private static final Set<Class<?>> MISSING_EQUALS_METHOD = Collections.synchronizedSet(Collections.newSetFromMap(new WeakHashMap<>())); private static final Logger LOG = LoggerFactory.getLogger(SerializableCoder.class); /** * Returns a {@link SerializableCoder} instance for the provided element type. * * @param <T> the element type */ public static <T extends Serializable> SerializableCoder<T> of(TypeDescriptor<T> type) { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) type.getRawType(); return new SerializableCoder<>(clazz, type); } @Override public boolean consistentWithEquals() { return false; } /** * The structural value of the object is the object itself. The {@link SerializableCoder} should * be only used for objects with a proper {@link Object#equals} implementation. */ @Override public Object structuralValue(T value) { return value; } /** * Returns a {@link SerializableCoder} instance for the provided element class. * * @param <T> the element type */ public static <T extends Serializable> SerializableCoder<T> of(Class<T> clazz) { checkEqualsMethodDefined(clazz); return new SerializableCoder<>(clazz, TypeDescriptor.of(clazz)); } private static <T extends Serializable> void checkEqualsMethodDefined(Class<T> clazz) { boolean warn = true; if (!clazz.isInterface()) { Method method; try { method = clazz.getMethod("equals", Object.class); } catch (NoSuchMethodException e) { // All concrete classes have an equals method declared in their class hierarchy. throw new AssertionError(String.format("Concrete class %s has no equals method", clazz)); } // Check if not default Object#equals implementation. warn = Object.class.equals(method.getDeclaringClass()); } // Note that the order of these checks is important since we want the // "did we add the class to the set" check to happen last. if (warn && MISSING_EQUALS_METHOD.add(clazz)) { LOG.warn( "Can't verify serialized elements of type {} have well defined equals method. " + "This may produce incorrect results on some {}", clazz.getSimpleName(), PipelineRunner.class.getSimpleName()); } } /** * Returns a {@link CoderProvider} which uses the {@link SerializableCoder} if possible for all * types. * * <p>This method is invoked reflectively from {@link DefaultCoder}. */ @SuppressWarnings("unused") public static CoderProvider getCoderProvider() { return new SerializableCoderProvider(); } /** * A {@link CoderProviderRegistrar} which registers a {@link CoderProvider} which can handle * serializable types. */ public static class SerializableCoderProviderRegistrar implements CoderProviderRegistrar { @Override public List<CoderProvider> getCoderProviders() { return ImmutableList.of(getCoderProvider()); } } /** * A {@link CoderProvider} that constructs a {@link SerializableCoder} for any class that * implements serializable. */ static class SerializableCoderProvider extends CoderProvider { @Override public <T> Coder<T> coderFor( TypeDescriptor<T> typeDescriptor, List<? extends Coder<?>> componentCoders) throws CannotProvideCoderException { if (Serializable.class.isAssignableFrom(typeDescriptor.getRawType())) { return SerializableCoder.of((TypeDescriptor) typeDescriptor); } throw new CannotProvideCoderException( "Cannot provide SerializableCoder because " + typeDescriptor + " does not implement Serializable"); } } private final Class<T> type; /** Access via {@link #getEncodedTypeDescriptor()}. */ @Nullable private transient TypeDescriptor<T> typeDescriptor; protected SerializableCoder(Class<T> type, TypeDescriptor<T> typeDescriptor) { this.type = type; this.typeDescriptor = typeDescriptor; } public Class<T> getRecordType() { return type; } @Override public void encode(T value, OutputStream outStream) throws IOException { ObjectOutputStream oos = new ObjectOutputStream(outStream); oos.writeObject(value); oos.flush(); } @Override public T decode(InputStream inStream) throws IOException, CoderException { try { ObjectInputStream ois = new ObjectInputStream(inStream); return type.cast(ois.readObject()); } catch (ClassNotFoundException e) { throw new CoderException("unable to deserialize record", e); } } /** * {@inheritDoc} * * @throws NonDeterministicException always. Java serialization is not deterministic with respect * to {@link Object#equals} for all types. */ @Override public void verifyDeterministic() throws NonDeterministicException { throw new NonDeterministicException(this, "Java Serialization may be non-deterministic."); } @Override public boolean equals(Object other) { return !(other == null || getClass() != other.getClass()) && type == ((SerializableCoder<?>) other).type; } @Override public int hashCode() { return type.hashCode(); } @Override public TypeDescriptor<T> getEncodedTypeDescriptor() { if (typeDescriptor == null) { typeDescriptor = TypeDescriptor.of(type); } return typeDescriptor; } // This coder inherits isRegisterByteSizeObserverCheap, // getEncodedElementByteSize and registerByteSizeObserver // from StructuredCoder. Looks like we cannot do much better // in this case. }
33.517241
99
0.710391
9e022268d78a6097953b56971e62ec2acac4b46f
972
import java.util.Scanner; public class LeftRotationOfArray { static void ArrayRotate(int arr[], int n) { int temp = arr[0]; for (int i = 1; i < n; i++) { arr[i - 1] = arr[i]; } arr[n - 1] = temp; } public static void main(String[] args) { Scanner cin = new Scanner(System.in); System.out.print("Enter array size: "); int n = cin.nextInt(); int[] arr = new int[n]; System.out.print("Enter " + n + " element: "); for (int i = 0; i < n; i++) { arr[i] = cin.nextInt(); } System.out.print("Enter number of rotation: "); int shift = cin.nextInt(); for (int i = 0; i < shift; i++) { ArrayRotate(arr, n); } System.out.print("Array after " + shift + " rotation: "); for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println("\n"); } }
27
65
0.466049
3b384e4d651fd3d558d7b2d582419e3eb88f3228
889
package org.zalando.nakadi.service.subscription; import org.junit.Test; import org.zalando.nakadi.util.ThreadUtils; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class IdleStreamWatcherTest { @Test public void checkIdleStreamWatcher() throws InterruptedException { final IdleStreamWatcher idleStreamWatcher = new IdleStreamWatcher(100); assertThat(idleStreamWatcher.isIdleForToolLong(), is(false)); // not idle at all idleStreamWatcher.idleStart(); assertThat(idleStreamWatcher.isIdleForToolLong(), is(false)); // is idle not long enough ThreadUtils.sleep(120); assertThat(idleStreamWatcher.isIdleForToolLong(), is(true)); // is idle for too long idleStreamWatcher.idleEnd(); assertThat(idleStreamWatcher.isIdleForToolLong(), is(false)); // not idle at all } }
32.925926
96
0.734533
608e30ad2f2f1684954aecaccb18a841177924b0
1,421
package cz.nkp.differ.cmdline; import com.beust.jcommander.Parameter; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * User: stavel * Date: 1.1.13 * Time: 15:37 * To change this template use File | Settings | File Templates. */ public class CommandArgs { @Parameter(description = "Files to validate.") public List<String> files = new ArrayList<String>(); @Parameter(names = {"-s","--save-report"}, description = "Report will be stored in a file named the same as input file. With extension: *.drep") public boolean saveReport=false; @Parameter(names = {"-l","--load-report"}, description = "Report will loaded from a given file named the same as input file. With extension: *.drep") public boolean loadReport=false; @Parameter(names = {"--save-properties"}, description = "A review of used significant properties will be saved.") public boolean saveProperties=false; @Parameter(names = {"--load-properties"}, description = "A review of significant properties to be used is loaded from a file.") public boolean loadProperties=false; @Parameter(names = {"-r","--save-raw-outputs"}, description = "Raw outputs of extractors will be saved too.") public boolean saveOutputs=false; @Parameter(names = {"-w","--send-report-to-web"}, description = "Report will be sent to web.") public boolean sendReportToWeb=false; };
38.405405
153
0.701619
8f3d2820c709ecd80ce2208204660e8b365a35ec
741
package br.com.orangetalents.proposta.integracao.response; import br.com.orangetalents.proposta.domain.modelo.Bloqueio; import java.time.LocalDateTime; public class BloqueioResponseClient { private String id; private LocalDateTime bloqueadoEm; private String sistemaResponsavel; private boolean ativo; public BloqueioResponseClient(String id, LocalDateTime bloqueadoEm, String sistemaResponsavel, boolean ativo) { this.id = id; this.bloqueadoEm = bloqueadoEm; this.sistemaResponsavel = sistemaResponsavel; this.ativo = ativo; } public Bloqueio responseClientToDomain() { return new Bloqueio(this.id, this.bloqueadoEm, this.sistemaResponsavel, this.ativo); } }
26.464286
115
0.739541
8a3dfa1f7ab104684c4dc2b4a3184fae56d5f095
1,398
package com.dianwoda.test.bassy.common.enums; import lombok.AllArgsConstructor; import java.util.HashMap; import java.util.Map; /** * Program type enum * * @author lichengkai * 2018 - 04 - 28 : 20:23 * Copyright(c) for dianwoda */ @AllArgsConstructor public enum ProgramTypeEn { PROGRAM("program", "立项项目"), INTERNAL("inner", "内部项目"), PRESSING("urgent", "紧急项目"), NORMAL("normal", "常规项目"); private String code; private String name; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static Boolean contains(String typeCode) { ProgramTypeEn[] programTypeEns = ProgramTypeEn.values(); for (int i = 0; i < programTypeEns.length; i++) { if (programTypeEns[i].getCode().equals(typeCode)) { return true; } } return false; } public static Map<String, String> getAllProgramType() { Map<String, String> map = new HashMap<>(); ProgramTypeEn[] programTypeEns = ProgramTypeEn.values(); for (int i = 0; i < programTypeEns.length; i++) { map.put(programTypeEns[i].getCode(),programTypeEns[i].getName()); } return map; } }
23.3
77
0.595851
24d4d940db1bee18a7e5434b24fec6d58ca40e81
1,388
package com.musak.service.guest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import static springfox.documentation.builders.PathSelectors.any; @SpringBootApplication @EnableSwagger2 @EnableDiscoveryClient public class GuestServicesApplication { @Bean public Docket api(){ return new Docket(DocumentationType.SWAGGER_2).groupName("Guest").select() .apis(RequestHandlerSelectors.basePackage("com.musak.service.guest")) .paths(any()).build().apiInfo(new ApiInfo("Guest Services", "A set of services to provide data access to guests", "1.0.0", null, new Contact("Musak Istvan", "https://twitter.com/musakistvan", null),null, null)); } public static void main(String[] args) { SpringApplication.run(GuestServicesApplication.class, args); } }
40.823529
106
0.768012
f8310accca9923d04787ae0d97846154bbe486d3
911
package com.hehe.sharingilive.homepage; import com.hehe.sharingilive.BasePresenter; import com.hehe.sharingilive.BaseView; import com.hehe.sharingilive.model.entity.LiveList; import com.hehe.sharingilive.model.entity.User; import java.util.List; /** * 定义方法,用于数据交互 * 保存view presenter 的父接口 * 调用view中的方法,写抽象方法,然后在view中实现抽象方法,对UI进行更改 * Created by tarena on 2017/7/11. */ public class HomeContract { interface View extends BaseView<Presenter> { void onSaveDataEnd(LiveList liveList, int openOrWatch); /** * 正在直播的列表信息更新完毕 * * @param liveLists */ void onUpateDataEnd(List<LiveList> liveLists); } interface Presenter extends BasePresenter { /** * 开始直播 * @param openOrWatch */ void openLive(int openOrWatch); /** * 获取正在直播的信息 */ void updateLiveInfo(); } }
21.690476
63
0.636663
761202292e754e62c99e9ec81c02973bc8a8e97b
225
package jason.designpatterns.command; /** * 命令接口 * 抽象命令类,声明执行命令的接口,拥有执行命令的抽象方法 execute() * * @author Jason Hou */ public interface Command { /** * 执行命令 * * @return 结果 */ String execute(); }
12.5
40
0.577778
a72aa0f796e6f4db5ad1abd1a12d77d9f9d5be29
464
package com.etiir.mdm.mapper.symmetric; import com.etiir.mdm.entity.TableTrigger; import org.apache.ibatis.annotations.Mapper; /** * @author lmx * @packageName com.etiir.mdm.mapper.symmetric * @description * @data 2019/6/13 10:29 */ @Mapper public interface TableTriggerMapper { void insertSelective(TableTrigger trigger); void delete(String triggerId); void update(String triggerId); TableTrigger selectByTriggerId(String triggerId); }
20.173913
53
0.752155
38efa7f44a77ac6779ada906f17157ea916a5d0b
401
package com.davidlares.davidAPI.service; import java.util.List; import com.davidlares.davidAPI.model.Course; public interface CourseService { void saveCourse(Course course); void deleteCourseById(Long idCourse); void updateCourse(Course course); List<Course> findAllCourses(); Course findByID(Long idCourse); Course findByName(String name); List<Course> findByIDteacher(Long idTeacher); }
22.277778
46
0.795511
72ae5a6f9bcec4122e3f2177d80399ff6a0444ec
1,336
/* * Copyright 2017-2018 Valiantsin Kavalenka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package stincmale.ratmex.meter; import stincmale.ratmex.doc.ThreadSafe; import stincmale.ratmex.meter.config.ConcurrentRateMeterConfig; /** * Stats gathered by a thread-safe implementation of {@link RateMeter} which implements {@link RateMeter#tick(long, long)} in a relaxed way, * that allows come ticks to be registered at an incorrect instant for example. */ @ThreadSafe public interface ConcurrentRateMeterStats { /** * @return The number of situations in which * {@link RateMeter} might have {@linkplain RateMeter#tick(long, long) registered ticks} at an incorrect instant, or just lost ticks. * * @see ConcurrentRateMeterConfig.Mode#RELAXED_TICKS */ long incorrectlyRegisteredTickEventsCount(); }
38.171429
140
0.756737
a319fd214558e281bedde444c1efd4454823f251
1,994
package com.icommerce.product.core.product; import com.icommerce.product.core.shared.CreationValidationGroup; import com.icommerce.product.core.shared.SelfValidating; import com.icommerce.product.core.shared.UpdatingValidationGroup; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.math.BigDecimal; import java.util.List; public class Product extends SelfValidating<Product> { @NotEmpty(groups = {UpdatingValidationGroup.class}) private String id; @NotEmpty(groups = {CreationValidationGroup.class, UpdatingValidationGroup.class}) private String title; private String description; private String brand; @NotNull(groups = {CreationValidationGroup.class, UpdatingValidationGroup.class}) private BigDecimal price; @NotEmpty(groups = {CreationValidationGroup.class, UpdatingValidationGroup.class}) private String colour; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } @Override public String toString() { return new StringBuilder(id) .append(title).append(description) .append(brand).append(price).append(colour) .toString(); } }
24.617284
86
0.669007
69e1124910b3ebb2df25ef020edd344fc4386620
1,073
package io.github.htools.extract.modules; import io.github.htools.lib.Log; /** * A TokenSubProcessor can be assigned to a TokenProcessorWithSubs by calling * {@link TokenProcessorWithSubs#addSubProcessor(java.lang.Class)} or by * configuring +extractor.[token].process = [subprocessor] * <p> * When a TokenProcessorWithSubs has accepted a token, is will sequentially * call it's SubProcessor to operate on the identified token in the byte array. * A subprocessor may modify the token in place (e.g. lowercase) or contain * validation rules to reject the token (e.g. verify URL validity). To reject * a token it should return endpos equal to startpos. * * @author jer */ public abstract class TokenSubProcessor extends TokenProcessor { public static final Log log = new Log(TokenSubProcessor.class); public TokenSubProcessor(TokenizerRegex tokenizer, String name) { super(tokenizer, name); } public boolean[] acceptedFirstChars() { log.fatal("Cannot use a TokenSubProcessor as TokenProcessor"); return null; } }
34.612903
79
0.738117
3a478fbc55ca618656df88e828c3084643ef3b38
1,520
/** * Write a function to find the longest common prefix string amongst an array of strings. * <p> * If there is no common prefix, return an empty string "". * <p> * <b>Example 1:</b> * <pre> * Input: ["flower","flow","flight"] * Output: "fl" * </pre> * <b>Example 2:</b> * <pre> * Input: ["dog","racecar","car"] * Output: "" * Explanation: There is no common prefix among the input strings. * </pre> * <p> * <b>Note:</b><br> * All given inputs are in lowercase letters a-z. * * @author Oleg Cherednik * @since 22.01.2019 */ public class Solution { public static void main(String... args) { System.out.println(longestCommonPrefix(new String[] { "ca", "a" })); System.out.println(longestCommonPrefix(new String[] { "flower", "flow", "flight" })); System.out.println(longestCommonPrefix(new String[] { "dog", "rececar", "car" })); } public static String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) return ""; if (strs.length == 1) return strs[0]; String res = strs[0]; for (int i = 0; i < strs.length; i++) if (strs[i].length() < res.length()) res = strs[i]; for (int i = 0, j = 0; !res.isEmpty() && i < strs.length; i++, j = 0) { for (; j < res.length(); j++) if (res.charAt(j) != strs[i].charAt(j)) break; res = res.substring(0, j); } return res; } }
27.142857
93
0.531579
5c14f8738040968ea05026eea0a48c45e17525b4
521
package org.springframework.boot.devtools.remote.server; import org.springframework.http.server.ServerHttpRequest; /** * Interface to provide a mapping between a {@link ServerHttpRequest} and a * {@link Handler}. * * @author Phillip Webb * @since 1.3.0 */ @FunctionalInterface public interface HandlerMapper { /** * Return the handler for the given request or {@code null}. * @param request the request * @return a {@link Handler} or {@code null} */ Handler getHandler(ServerHttpRequest request); }
20.84
75
0.723608
aab8bf328a173a6833ec5caeca0b72a571e3cdfd
488
package EdgeCounter; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * Class tests the funcationality of the EdgeFile class * @author Lavanya Uppala * */ public class EdgeFileTestCases { @Test public void testBasicConstructor() { EdgeFile tester = new EdgeFile(); assertEquals(EdgeFile.arrayEdgeNumTimesFound.size(), 0); assertEquals(EdgeFile.arrayEdgeHold.size(), 0); } @Test public void testReadFile() { } }
17.428571
59
0.688525
0d2e0c7a467d2b7a6b75e48cfaa05c8e5f673e00
2,853
package org.noear.solon.boot.ssl; import org.noear.solon.Utils; import org.noear.solon.boot.ServerConstants; import javax.net.ssl.*; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.*; import java.security.cert.CertificateException; /** * @author noear * @since 1.6 */ public class SslContextFactory { public static SSLContext createSslContext() throws IOException { String keyStoreName = System.getProperty(ServerConstants.SSL_KEYSTORE); String keyStoreType = System.getProperty(ServerConstants.SSL_KEYSTORE_TYPE); String keyStorePassword = System.getProperty(ServerConstants.SSL_KEYSTORE_PASSWORD); if(Utils.isEmpty(keyStoreType)){ keyStoreType = "jks"; } KeyStore keyStore = loadKeyStore(keyStoreName, keyStoreType, keyStorePassword); KeyManager[] keyManagers = buildKeyManagers(keyStore, keyStorePassword.toCharArray()); SSLContext sslContext; try { sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, null, null); } catch (NoSuchAlgorithmException | KeyManagementException exc) { throw new IOException("Unable to create and initialise the SSLContext", exc); } return sslContext; } private static KeyStore loadKeyStore(final String location, String type, String storePassword) throws IOException { URL KeyStoreUrl = Utils.getResource(location); InputStream KeyStoreStream = null; if (KeyStoreUrl == null) { KeyStoreStream = new FileInputStream(location); } else { KeyStoreStream = KeyStoreUrl.openStream(); } try (InputStream stream = KeyStoreStream) { KeyStore loadedKeystore = KeyStore.getInstance(type); loadedKeystore.load(stream, storePassword.toCharArray()); return loadedKeystore; } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException exc) { throw new IOException(String.format("Unable to load KeyStore %s", location), exc); } } private static KeyManager[] buildKeyManagers(final KeyStore keyStore, char[] storePassword) throws IOException { KeyManager[] keyManagers; try { KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory .getDefaultAlgorithm()); keyManagerFactory.init(keyStore, storePassword); keyManagers = keyManagerFactory.getKeyManagers(); } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException exc) { throw new IOException("Unable to initialise KeyManager[]", exc); } return keyManagers; } }
36.113924
98
0.681388
8c99a7d6206c0ab4559e82230d1664c4cdb26f99
487
package com.vanistudio.homer.Model; /** * Created by thuynh6 on 4/11/2016. */ public class Homer_Status { private String status; //on-sale, sold, deleted private String date; //date when status changes public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
18.730769
51
0.616016
f373dc69fb8f6365aded116117713671bd986d27
199
package com.trifork.impromptu; import java.util.Enumeration; import java.util.List; public interface HeaderValueResolver { List<String> getValue(String key); Enumeration<String> getKeys(); }
18.090909
38
0.773869
ebdb4f885f8dd8f0610a8ad565998452f3917c03
1,303
package com.immoc.order.message.stream; import org.springframework.cloud.stream.annotation.Input; import org.springframework.cloud.stream.annotation.Output; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.SubscribableChannel; /** * StreamClient 接口,通过 @Input和 @Output注解定义输入通道和输出通道 */ public interface StreamClient { //@Input 和 @Output 注解都还有一个 value 属性,该属性可以用来设置消息通道的名称 String INPUT = "myInput"; String OUTPUT = "myOutput"; //下面2个是消息接收后,返回确认消息 String RESPONSE_INPUT = "responseInput"; String RESPONSE_OUTPUT = "responseOutput"; /* 相对于application 方来说的 输入还是输出 当定义输出通道的时候,需要返回 MessageChannel 接口对象, 该接口定义了向消息通道发送消息的方法;定义输入通道时,需要返回 SubscribableChannel 接口对象, 该接口集成自 MessageChannel 接口,它定义了维护消息通道订阅者的方法。 */ @Input(StreamClient.INPUT) SubscribableChannel input(); @Output(StreamClient.OUTPUT) MessageChannel output(); //下面2个是消息接收后,返回确认消息 @Input(StreamClient.RESPONSE_INPUT) SubscribableChannel responseInput(); @Output(StreamClient.RESPONSE_OUTPUT) MessageChannel responseOutput(); /* 在完成了消息通道绑定的定义后,这些用于定义绑定消息通道的接口则可以被 @EnableBinding 注解的 value 参数指定, 从而在应用启动的时候实现对定义消息通道的绑定,Spring Cloud Stream 会为其创建具体的实例, 而开发者只需要通过注入的方式来获取这些实例并直接使用即可 */ }
30.302326
66
0.749041
209d25639227974f2cd1f5cc6f85e67f9a8399a2
2,100
package org.openforis.collect.metamodel.uiconfiguration.view; import java.util.ArrayList; import java.util.List; import org.openforis.collect.metamodel.ui.UITable; import org.openforis.collect.metamodel.ui.UITable.Direction; import org.openforis.collect.metamodel.ui.UITableHeadingComponent; import org.openforis.collect.metamodel.view.ViewContext; public class UITableView extends UIModelObjectView<UITable> implements UITabComponentView<UITable> { public UITableView(UITable uiObject, ViewContext context) { super(uiObject, context); } @Override public String getType() { return "TABLE"; } public int getEntityDefinitionId() { return uiObject.getEntityDefinitionId(); } public List<UITableHeadingComponentView<?>> getHeadingComponents() { return UITableHeadingComponentView.fromObjects(uiObject.getHeadingComponents(), context); } public List<List<UITableHeadingComponentView<?>>> getHeadingRows() { List<List<UITableHeadingComponentView<?>>> rowViews = new ArrayList<List<UITableHeadingComponentView<?>>>(); List<List<UITableHeadingComponent>> rows = uiObject.getHeadingRows(); for (List<UITableHeadingComponent> row : rows) { List<UITableHeadingComponentView<?>> rowView = UITableHeadingComponentView.fromObjects(row, context); rowViews.add(rowView); } return rowViews; } public int getTotalHeadingRows() { return uiObject.getTotalHeadingRows(); } public List<UIColumnView> getHeadingColumns() { return UITableHeadingComponentView.fromObjects(uiObject.getHeadingColumns(), context); } public int getTotalHeadingColumns() { return uiObject.getTotalHeadingColumns(); } public boolean isShowRowNumbers() { return uiObject.isShowRowNumbers(); } public boolean isCountInSummaryList() { return uiObject.isCountInSummaryList(); } public Direction getDirection() { return uiObject.getDirection(); } @Override public int getColumn() { return uiObject.getColumn(); } @Override public int getColumnSpan() { return uiObject.getColumnSpan(); } @Override public int getRow() { return uiObject.getRow(); } }
26.582278
110
0.770952
3b32915a837519e1b81edebc168f88740cd4c6f0
99
package com.company.move; public abstract class Move { public abstract void performMove(); }
14.142857
39
0.737374
61a6743e038f07ce893cfedec55f5172fe9634ba
6,316
/* Copyright (C) 2012 Haowen Ning This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.liberty.android.fantastischmemo.ui; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.liberty.android.fantastischmemo.R; import org.liberty.android.fantastischmemo.common.AMPrefKeys; import org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper; import org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelperManager; import org.liberty.android.fantastischmemo.common.BaseActivity; import org.liberty.android.fantastischmemo.dao.CardDao; import org.liberty.android.fantastischmemo.entity.Card; import org.liberty.android.fantastischmemo.entity.Category; import org.liberty.android.fantastischmemo.entity.LearningData; import org.liberty.android.fantastischmemo.utils.AMGUIUtility; import org.liberty.android.fantastischmemo.utils.RecentListUtil; import javax.inject.Inject; /* * This class is invoked when the user share the card from other * apps like ColorDict */ public class ShareScreen extends BaseActivity implements View.OnClickListener{ private TextView dbnameView; private TextView questionView; private TextView answerView; private TextView noteView; private Button saveButton; private Button savePrevButton; private Button cancelButton; private SharedPreferences settings; private final int ACTIVITY_FB = 1; @Inject RecentListUtil recentListUtil; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activityComponents().inject(this); setContentView(R.layout.share_screen); dbnameView = (TextView)findViewById(R.id.share_db_name_entry); questionView = (TextView)findViewById(R.id.share_question_entry); answerView = (TextView)findViewById(R.id.share_answer_entry); noteView = (TextView)findViewById(R.id.share_note_entry); noteView.setText(""); saveButton = (Button)findViewById(R.id.share_button_save); savePrevButton = (Button)findViewById(R.id.share_button_saveprev); cancelButton = (Button)findViewById(R.id.share_button_cancel); saveButton.setOnClickListener(this); savePrevButton.setOnClickListener(this); cancelButton.setOnClickListener(this); dbnameView.setOnClickListener(this); settings = PreferenceManager.getDefaultSharedPreferences(this); Intent intent = getIntent(); if (intent.getAction().equals(Intent.ACTION_SEND)) { Bundle extras = intent.getExtras(); String subject = extras.getString(Intent.EXTRA_SUBJECT); String text = extras.getString(Intent.EXTRA_TEXT); questionView.setText(subject); answerView.setText(text); String dbPath = settings.getString(AMPrefKeys.getRecentPathKey(0), ""); dbnameView.setText(dbPath); } else { finish(); } } @Override public void onClick(View v){ try{ String dbpath = dbnameView.getText().toString(); Log.v(TAG, dbpath); if(v == saveButton || v == savePrevButton){ AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(this, dbpath); CardDao cardDao = helper.getCardDao(); try { Card card = new Card(); card.setQuestion(questionView.getText().toString()); card.setAnswer(answerView.getText().toString()); card.setNote(noteView.getText().toString()); card.setCategory(new Category()); card.setLearningData(new LearningData()); cardDao.createCard(card); if(v == savePrevButton){ Intent myIntent = new Intent(this, PreviewEditActivity.class); /* This should be the newly created id */ myIntent.putExtra("id", card.getId()); myIntent.putExtra(PreviewEditActivity.EXTRA_DBPATH, dbpath); startActivity(myIntent); } finish(); } finally { AnyMemoDBOpenHelperManager.releaseHelper(helper); } } else if(v == cancelButton){ finish(); } else if(v == dbnameView){ Intent myIntent = new Intent(this, FileBrowserActivity.class); myIntent.putExtra(FileBrowserActivity.EXTRA_FILE_EXTENSIONS, ".db"); startActivityForResult(myIntent, ACTIVITY_FB); } } catch (Exception e){ AMGUIUtility.displayError(this, getString(R.string.error_text), "", e); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); if(resultCode ==Activity.RESULT_CANCELED){ return; } /* Refresh the activity according to activities */ switch(requestCode){ case ACTIVITY_FB: { String fullpath = data.getStringExtra(FileBrowserActivity.EXTRA_RESULT_PATH); recentListUtil.addToRecentList(fullpath); dbnameView.setText(fullpath); } break; } } }
39.475
96
0.664345
132d639eae38b13017393160c84ba2b951fd6f41
156
package org.springframework.context.annotation6; import org.springframework.stereotype.Component; @Component public class ComponentForScanning { }
19.5
49
0.807692
924320efb99438d3dbb52d1f883c039c7032e4be
1,807
package game.components; import engine.GameContainer; import engine.Renderer; import game.GameManager; import game.GameObject; import game.Physics; public class AABBComponent extends Component { private GameObject parent; private int centerX, centerY; private int halfWidth, halfHeight; public AABBComponent(GameObject parent) { this.parent = parent; this.tag = "aabb"; } @Override public void update(GameContainer gc, GameManager gm, float dt) { centerX = (int) (parent.getPositionX() + (parent.getWidth() / 2)); centerY = (int) (parent.getPositionY() + (parent.getHeight() / 2) + (parent.getPaddingTop() / 2)); halfWidth = parent.getWidth() - parent.getPadding(); halfHeight = parent.getHeight() - parent.getPaddingTop() / 2; Physics.addAABBComponent(this); } @Override public void render(GameContainer gc, Renderer r) { int positionX = (int) parent.getPositionX(); int positionY = (int) parent.getPositionY(); // r.drawRect(parent.getWidth(), parent.getHeight(), positionX, positionY, 0xffffffff); // r.drawRect(halfHeight * 2, halfWidth * 2, centerX - halfWidth, centerY - halfHeight, 0xffffffff); } public GameObject getParent() { return parent; } public void setParent(GameObject parent) { this.parent = parent; } public int getCenterX() { return centerX; } public void setCenterX(int centerX) { this.centerX = centerX; } public int getCenterY() { return centerY; } public void setCenterY(int centerY) { this.centerY = centerY; } public int getHalfWidth() { return halfWidth; } public void setHalfWidth(int halfWidth) { this.halfWidth = halfWidth; } public int getHalfHeight() { return halfHeight; } public void setHalfHeight(int halfHeight) { this.halfHeight = halfHeight; } }
22.036585
107
0.702822
7196bc0a3033ac31822aba673c7b2c404f1b4211
3,304
package seleniumutils.methods.helpers; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import seleniumutils.methods.GlobalProperties; /** * @author Gajendra Mahadevan */ public class JSONHelper { /** Thread-safe write to a json file * @param jsonObject : String : The JSON object * @param path : String : The path where the file resides * @param filename : String : The filename */ @SuppressWarnings("unchecked") public static synchronized void JSONWrite(String jsonObject,String path, String filename){ // try-with-resources statement based on post comment below :) File f = new File(path,filename); try { if(!f.getParentFile().exists()) f.getParentFile().mkdirs(); f.createNewFile(); FileWriter file = new FileWriter(f); file.write(jsonObject); file.close(); }catch (IOException e){ e.printStackTrace(); } } /** Thread-safe read from file * @param path : String : The path where the file resides * @param filename : String : The filename * @return : A JSONObject read from the file */ public static synchronized JSONObject JSONRead(String path,String filename) { // try-with-resources statement based on post comment below :) JSONParser parser = new JSONParser(); JSONObject jsonObject = null; try { File file = new File(path, filename); //create the file if it does not exist if (file.exists()) { FileReader fileReader = new FileReader(file); Object obj = parser.parse(fileReader); jsonObject = (JSONObject) obj; fileReader.close(); } else { if(!file.getParentFile().exists()) file.getParentFile().mkdirs(); file.createNewFile(); jsonObject = new JSONObject(new HashMap()); } } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return jsonObject; } public static synchronized void appendToJSON(HashMap<String,Object> hashMap, String path, String filename, TypeReference valueTypeRef, Object toBeAppended) throws IOException{ ObjectMapper objectMapper = new ObjectMapper(); DateTimeHelper dateTimeHelper = new DateTimeHelper(); String timeStamp=dateTimeHelper.getTimeStamp(); hashMap=objectMapper.readValue(JSONHelper.JSONRead(path,filename).toString(),valueTypeRef); HashMap hMap = new HashMap<String,Object>(); hMap.put("Policy_Number",toBeAppended); hashMap.put(timeStamp,hMap); String jsonObject = objectMapper.writeValueAsString(hashMap); JSONHelper.JSONWrite(jsonObject,path,filename); } }
35.148936
179
0.643462
528667b07afc9da8d5836a45f77f60f81f70afb5
1,047
package mezz.jei.support; import mezz.jei.api.ISubtypeRegistry; import mezz.jei.api.ISubtypeRegistry.ISubtypeInterpreter; import mezz.jei.util.Log; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.common.Loader; import vazkii.patchouli.common.item.PatchouliItems; /** * A static class containing mod support injections and more */ public class ModSupport { public static void registerSubtypeInterpreters(ISubtypeRegistry registry) { if (Loader.isModLoaded("patchouli")) { Log.get().info("Registering SubtypeInterpreter for Patchouli's Books."); registry.registerSubtypeInterpreter(PatchouliItems.book, stack -> { NBTTagCompound tag = stack.getTagCompound(); if (tag == null) { return ISubtypeInterpreter.NONE; } NBTTagCompound bookTag = tag.getCompoundTag("patchouli:book"); return bookTag.isEmpty() ? ISubtypeInterpreter.NONE : bookTag.toString(); }); } } }
34.9
89
0.672397
dc43dbd40dafeccf78292f64fcbb4c66ecb3e977
70
package net.sqlcipher.database; public class SQLiteCursorDriver { }
11.666667
33
0.8
9811ea1e8f00e349bf84c410e186a4a018e2320b
1,745
package net.sf.okapi.applications.lapwing.soap; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.jws.WebService; import javax.mail.util.ByteArrayDataSource; import net.sf.okapi.applications.lapwing.core.Input; import net.sf.okapi.applications.lapwing.core.Output; import net.sf.okapi.applications.lapwing.core.Pipeline; import net.sf.okapi.applications.lapwing.exceptions.ServerException; import org.apache.cxf.helpers.IOUtils; @WebService(endpointInterface = "net.sf.okapi.applications.lapwing.soap.IITSProcessor", serviceName = "itsprocessor", targetNamespace = "http://lapwing.applications.okapi.sf.net", portName = "itsprocessor") public class ITSProcessorImpl implements IITSProcessor { private static final String OUTPUT_MIME_TYPE = "application/xml"; public ITSProcessorImpl() { } @Override public SOAPResponse check(SOAPRequest input) throws ServerException { Pipeline pipeline = new Pipeline(); byte[] annotatedFile; try { Input ltinput = new Input(); ltinput.setData(input.getData().getInputStream()); ltinput.setEncoding(input.getEncoding()); ltinput.setSrcLocale(input.getSource()); ltinput.setTgtLocale(input.getTarget()); Output output = pipeline.check(ltinput); SOAPResponse response = new SOAPResponse(); annotatedFile = IOUtils.readBytesFromStream(output.getData()); DataSource responseFile = new ByteArrayDataSource(annotatedFile, ITSProcessorImpl.OUTPUT_MIME_TYPE); DataHandler handler = new DataHandler(responseFile); response.setData(handler); response.setEncoding(output.getEncoding()); return response; } catch (Exception e) { throw new ServerException(e); } } }
34.9
207
0.75702
5e06d1b4452a4270696bc5dd56ed32fcbd74d9e0
2,000
/* ************************************************************************ # # DivConq # # http://divconq.com/ # # Copyright: # Copyright 2014 eTimeline, LLC. All rights reserved. # # License: # See the license.txt file in the project's top-level directory for details. # # Authors: # * Andy White # ************************************************************************ */ package divconq.web; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.LastHttpContent; import divconq.bus.MessageUtil; import divconq.bus.net.StreamMessage; import divconq.lang.op.OperationResult; import divconq.session.DataStreamChannel; public class HttpUploadDecoder implements IContentDecoder { protected int max = 0; protected int seq = 0; protected DataStreamChannel channel = null; public HttpUploadDecoder(int max, DataStreamChannel chan) { this.channel = chan; this.max = max; } @Override public void offer(HttpContent chunk) { if (this.channel.isClosed()) return; // TODO somehow connect the cancel back to netsession if (chunk.content().readableBytes() > this.max) { this.channel.abort(); // TODO somehow connect the cancel back to netsession return; } ByteBuf bb = chunk.content(); bb.retain(); // we will use it in upcoming send System.out.println("ref count a: " + bb.refCnt()); StreamMessage b = new StreamMessage("Block", bb); b.setField("Sequence", this.seq); OperationResult or = this.channel.send(b); // bb should now be back to 1 System.out.println("ref count b: " + bb.refCnt()); if (or.hasErrors()) { this.channel.close(); return; } this.seq++; // TODO track progress if possible // final only if not canceled if (chunk instanceof LastHttpContent) this.channel.send(MessageUtil.streamFinal()); } @Override public void release() { } }
25.316456
80
0.618
3f40399543ee57ff5c3887c486f67dd44cb5fc9e
2,328
package quiz.controller; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import quiz.controllerAdvice.CorrectAnswerExceptionHandler; import quiz.entity.CorrectAnswer; import quiz.model.Response; import quiz.service.CorrectAnswerService; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class CorrectAnswerControllerTest { @Mock private CorrectAnswerService correctAnswerService; @InjectMocks private CorrectAnswerController correctAnswerController; private MockMvc mockMvc; private ObjectMapper mapper; @Before public void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(correctAnswerController) .setControllerAdvice(new CorrectAnswerExceptionHandler()) .setUseSuffixPatternMatch(false) .build(); mapper = new ObjectMapper(); when(correctAnswerService.saveCorrectAnswer(any(CorrectAnswer.class))) .thenReturn(new Response(HttpStatus.OK.value(), "Successfully saved!")); } @Test public void testSaveCorrectAnswer() throws Exception { MvcResult result = mockMvc .perform(MockMvcRequestBuilders .post(CorrectAnswerController.PATH) .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{}")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn(); assertEquals(mapper.writeValueAsString(new Response(HttpStatus.OK.value(), "Successfully saved!")), result.getResponse().getContentAsString()); } }
36.952381
107
0.733677
6b5ea9ea5d2c0e079322add8dfb60b51ae55d769
3,866
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * GraphIsomorphismInspector.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: GraphIsomorphismInspector.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import java.util.*; /** * <b>Isomorphism Overview</b> * * <p>Isomorphism is the problem of testing whether two graphs are topologically * the same. Suppose we are given a collection of graphs and must perform some * operation on each of them. If we can identify which of the graphs are * duplicates, they can be discarded so as to avoid redundant work. * * <p>In Formal Math: <i>Input description:</i> Two graphs, G and H. <i>Problem * description:</i> Find a (or all) mappings f of the vertices of G to the * vertices of H such that G and H are identical; i.e. (x,y) is an edge of G iff * (f(x),f(y)) is an edge of H. <a * href="http://www2.toki.or.id/book/AlgDesignManual/BOOK/BOOK4/NODE180.HTM"> * http://www2.toki.or.id/book/AlgDesignManual/BOOK/BOOK4/NODE180.HTM</a>. * * <p><i>Efficiency:</i> The general algorithm is not polynomial, however * polynomial algorithms are known for special cases, like acyclic graphs, * planar graphs etc. There are several heuristic algorithms which gives quite * good results (polynomial) in general graphs, for most but not all cases. * * <p><b>Usage:</b> * * <ol> * <li>Choose comparators for the vertexes and edges. You may use the default * comparator by sending null parameters for them to the constructor. Example: * Assume Your graphs are of human relations. Each vertex is either a man or a * woman and also has the person name. You may decide that isomorphism is * checked according to gender, but not according to the specific name. So you * will create a comparator that distinguishes vertexes only according to * gender. * <li>Use the isIsomorphic() method as a boolean test for isomorphism * <li>Use the Iterator interface to iterate through all the possible * isomorphism ordering. * </ol> * * @author Assaf Lehr * @since Jul 15, 2005 */ // REVIEW jvs 5-Sept-2005: Since we're using JDK1.5 now, we should be // able to declare this as Iterator<GraphMapping>, correct? Otherwise // the caller doesn't even know what they're getting back. public interface GraphIsomorphismInspector<E> extends Iterator<E> { //~ Methods ---------------------------------------------------------------- /** * @return <code>true</code> iff the two graphs are isomorphic */ public boolean isIsomorphic(); } // End GraphIsomorphismInspector.java
40.270833
81
0.669684
47b5e223507e0a1e166ded47f1b7d18c04c99ac1
1,522
package io.subutai.core.peer.impl.entity; import java.io.Serializable; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; @Entity @Table( name = "peer_data" ) @Access( AccessType.FIELD ) public class PeerData implements Serializable { @Id @Column( name = "id" ) private String id; @Column( name = "key_phrase" ) private String keyPhrase; @Column private Integer order; @Lob @Column( name = "info" ) private String info; @Lob @Column( name = "policy" ) private String policy; public PeerData( final String id, final String info, final String keyPhrase, final String policy, final Integer order ) { this.id = id; this.info = info; this.keyPhrase = keyPhrase; this.policy = policy; this.order = order; } public String getId() { return id; } public String getInfo() { return info; } public void setInfo( final String info ) { this.info = info; } public String getKeyPhrase() { return keyPhrase; } public String getPolicy() { return policy; } public void setPolicy( final String policy ) { this.policy = policy; } public Integer getOrder() { return order; } }
16.543478
101
0.60841
671aa1db9ae804345eb203bf9eb54ff37c1457ba
904
package com.marqusm.example.moneytransaction.controller.base; import static spark.Spark.*; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.marqusm.example.moneytransaction.configuration.ApiConfig; import com.marqusm.example.moneytransaction.configuration.DefaultModule; import lombok.val; /** * @author : Marko * @createdOn : 28-Jan-20 */ public abstract class ControllerITest { public static Injector createInjectorAndInitServer(Module module) { val injector = Guice.createInjector(module); val apiConfig = injector.getInstance(ApiConfig.class); apiConfig.establishApi(); awaitInitialization(); return injector; } public static Injector createInjectorAndInitServer() { return createInjectorAndInitServer(new DefaultModule()); } public static void stopServer() { stop(); awaitStop(); } }
25.828571
72
0.762168
542219ceaddbdad40322e8826c709214432b80ce
223
package playwell.common; /** * 该接口用于修饰Playwell标准集成组件,为组件约定一些统一的行为以便于集成 * * @author chihongze */ public interface PlaywellComponent { /** * 执行初始化操作 * * @param config 配置信息 */ void init(Object config); }
13.117647
42
0.663677
9ba08b71881214f0692ec52d4694e2d0e9a05a1c
3,202
/* * Copyright 2016 Hammock and its contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package ws.ament.hammock.rest.resteasy; import org.jboss.resteasy.cdi.ResteasyCdiExtension; import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher; import org.jboss.resteasy.spi.ResteasyDeployment; import ws.ament.hammock.utils.ClassUtils; import ws.ament.hammock.web.spi.RestServerConfiguration; import ws.ament.hammock.web.spi.ServletContextAttributeProvider; import ws.ament.hammock.web.api.ServletDescriptor; import ws.ament.hammock.web.spi.WebParam; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Instance; import javax.enterprise.inject.Produces; import javax.inject.Inject; import javax.servlet.annotation.WebInitParam; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import java.util.Map; import static java.util.Collections.singletonMap; @ApplicationScoped public class ResteasyServletContextAttributeProvider implements ServletContextAttributeProvider { @Inject private ResteasyCdiExtension resteasyCdiExtension; @Inject private Instance<Application> applicationInstance; @Inject private RestServerConfiguration restServerConfiguration; @Override public Map<String, Object> getAttributes() { ResteasyDeployment deployment = new ResteasyDeployment(); deployment.getActualResourceClasses().addAll(resteasyCdiExtension.getResources()); deployment.getActualProviderClasses().addAll(resteasyCdiExtension.getProviders()); if( !(applicationInstance.isUnsatisfied() || applicationInstance.isAmbiguous())) { deployment.setApplication(applicationInstance.get()); } deployment.setInjectorFactoryClass(Cdi11InjectorFactory.class.getName()); return singletonMap(ResteasyDeployment.class.getName(), deployment); } @Produces public ServletDescriptor resteasyServlet() { String path = restServerConfiguration.getRestServerUri(); if( !(applicationInstance.isUnsatisfied() || applicationInstance.isAmbiguous())) { ApplicationPath appPath = ClassUtils.getAnnotation(applicationInstance.get().getClass(), ApplicationPath.class); if(appPath != null) { path = appPath.value(); } } String pattern = path.endsWith("/") ? path + "*" : path + "/*"; WebInitParam param = new WebParam("resteasy.servlet.mapping.prefix", path); return new ServletDescriptor("ResteasyServlet",new String[]{pattern}, new String[]{pattern}, 1,new WebInitParam[]{param},true,HttpServlet30Dispatcher.class); } }
41.584416
124
0.748595
1e351d3a4a3378f3b9406be269e19e9bc4eed28b
3,845
/* * Copyright (C) 2014-2016 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. */ package gobblin.writer; import gobblin.configuration.ConfigurationKeys; import gobblin.configuration.State; import gobblin.writer.test.TestPartitionAwareWriterBuilder; import gobblin.writer.test.TestPartitioner; import java.io.IOException; import org.testng.Assert; import org.testng.annotations.Test; /** * Test {@link gobblin.writer.PartitionedDataWriter} */ public class PartitionedWriterTest { @Test public void test() throws IOException { State state = new State(); state.setProp(ConfigurationKeys.WRITER_PARTITIONER_CLASS, TestPartitioner.class.getCanonicalName()); TestPartitionAwareWriterBuilder builder = new TestPartitionAwareWriterBuilder(); DataWriter<String> writer = new PartitionedDataWriter<String, String>(builder, state); Assert.assertEquals(builder.actions.size(), 0); String record1 = "abc"; writer.write(record1); Assert.assertEquals(builder.actions.size(), 2); TestPartitionAwareWriterBuilder.Action action = builder.actions.poll(); Assert.assertEquals(action.getPartition(), "a"); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.BUILD); action = builder.actions.poll(); Assert.assertEquals(action.getPartition(), "a"); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.WRITE); Assert.assertEquals(action.getTarget(), record1); String record2 = "bcd"; writer.write(record2); Assert.assertEquals(builder.actions.size(), 2); action = builder.actions.poll(); Assert.assertEquals(action.getPartition(), "b"); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.BUILD); action = builder.actions.poll(); Assert.assertEquals(action.getPartition(), "b"); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.WRITE); Assert.assertEquals(action.getTarget(), record2); writer.write(record1); Assert.assertEquals(builder.actions.size(), 1); action = builder.actions.poll(); Assert.assertEquals(action.getPartition(), "a"); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.WRITE); Assert.assertEquals(action.getTarget(), record1); Assert.assertEquals(writer.recordsWritten(), 3); Assert.assertEquals(writer.bytesWritten(), 3); writer.cleanup(); Assert.assertEquals(builder.actions.size(), 2); action = builder.actions.poll(); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.CLEANUP); action = builder.actions.poll(); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.CLEANUP); writer.close(); Assert.assertEquals(builder.actions.size(), 2); action = builder.actions.poll(); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.CLOSE); action = builder.actions.poll(); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.CLOSE); writer.commit(); Assert.assertEquals(builder.actions.size(), 2); action = builder.actions.poll(); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.COMMIT); action = builder.actions.poll(); Assert.assertEquals(action.getType(), TestPartitionAwareWriterBuilder.Actions.COMMIT); } }
36.619048
104
0.749025
e32ab8c6f5abedf8296f5a10d44de1fa1879545e
310
package es.codeurjc.gamepost.repositories.enums; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import es.codeurjc.gamepost.objects.enums.Genre; public interface GenreRepository extends JpaRepository<Genre, Integer>{ Optional<Genre> findByText(String text); }
25.833333
71
0.819355
7de7b1a76c2722d64e9a116b8d0916ef1e06cf01
498
package com.miaoshaproject.service; import com.miaoshaproject.error.BussinessException; import com.miaoshaproject.service.model.UserModel; public interface UserService { //通过对象id获取对象 UserModel getUserById(Integer id); //注册 void register(UserModel userModel) throws BussinessException; /** * 登陆验证 * @param telphone 用户注册的手机 * @param encrptPassword 用户加密后的密码 */ UserModel validateLogin(String telphone,String encrptPassword) throws BussinessException; }
24.9
93
0.748996
e3ec0a096a605c822e37f6265a836d06f9fe973a
1,018
package com.byd.zzjmes.modules.produce.service; import java.util.List; import java.util.Map; import com.byd.utils.PageUtils; /** * 机台计划 * @author tangj * @email * @date 2019-09-03 15:12:08 */ public interface MachinePlanService{ public PageUtils queryPage(Map<String, Object> params); List<Map<String,Object>> getMachinePlanList(Map<String,Object> param); // 导入保存 void save(Map<String,Object> param); // 删除 void del(Map<String,Object> param); // 获取计划信息 Map<String,Object> getPlanByMap(Map<String,Object> param); // 本批次在整个订单中所属数量范围,的起始数 int getZzjPlanBatchQuantity(Map<String,Object> param); // 查询下料明细是否存在 List<Map<String,Object>> getExistPmdList(Map<String,Object> param); // 取已存在的机台计划数量列表 判断数量是否超出 List<Map<String,Object>> checkMachinePlanList(Map<String,Object> params); // 导入时校验机台信息 List<String> checkMachine(Map<String,Object> params); List<Map<String,Object>> getOutputRecords(Map<String,Object> params); List<Map<String,Object>> getTemplateData(Map<String,Object> params); }
26.102564
74
0.747544
9246b4482503ad8860c8a1816aaea1f02fedcd89
608
package org.xbib.elasticsearch.river.jdbc; import org.xbib.elasticsearch.plugin.feeder.jdbc.JDBCFeeder; import org.xbib.elasticsearch.plugin.jdbc.RiverContext; public interface RiverFlow { /** * The river strategy * * @return the strategy */ String strategy(); RiverFlow setRiverContext(RiverContext riverContext); /** * Set the feeder * * @param feeder the feeder * @return this river flow */ RiverFlow setFeeder(JDBCFeeder feeder); /** * Return the feeder * * @return the feeder */ JDBCFeeder getFeeder(); }
19.612903
60
0.639803
a56939018c2e599f39c4ea31cbdf3d6541c1c332
1,812
package com.verdantartifice.primalmagick.common.containers.slots; import java.util.function.Supplier; import com.verdantartifice.primalmagick.common.crafting.WandInventory; import com.verdantartifice.primalmagick.common.sources.SourceList; import com.verdantartifice.primalmagick.common.wands.IWand; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.inventory.ResultSlot; import net.minecraft.world.item.ItemStack; /** * Custom GUI slot for spellcrafting altar outputs. * * @author Daedalus4096 */ public class SpellcraftingResultSlot extends ResultSlot { protected final WandInventory wandInventory; protected final Player player; protected final Supplier<SourceList> costSupplier; public SpellcraftingResultSlot(Player player, CraftingContainer craftingInventory, WandInventory wandInventory, Supplier<SourceList> costSupplier, Container inventoryIn, int slotIndex, int xPosition, int yPosition) { super(player, craftingInventory, inventoryIn, slotIndex, xPosition, yPosition); this.wandInventory = wandInventory; this.player = player; this.costSupplier = costSupplier; } @Override public void onTake(Player player, ItemStack stack) { // Deduct the cost of the spell from the wand SourceList manaCosts = this.costSupplier.get(); if (manaCosts != null && !manaCosts.isEmpty()) { ItemStack wandStack = this.wandInventory.getItem(0); if (wandStack != null && !wandStack.isEmpty() && wandStack.getItem() instanceof IWand wand) { wand.consumeRealMana(wandStack, this.player, manaCosts); } } super.onTake(player, stack); } }
40.266667
220
0.739514
26edd2d8092476a168d8eebb4cae45eea870da20
629
package ru.sdetteam.easygauge.model; import lombok.Data; /** * Table: mantis_project_version_table */ @Data public class ProjectVersion { /** * Column: id */ private Integer id; /** * Column: project_id */ private Integer projectId; /** * Column: version */ private String version; /** * Column: released */ private Byte released; /** * Column: obsolete */ private Byte obsolete; /** * Column: date_order */ private Integer dateOrder; /** * Column: description */ private String description; }
14.295455
38
0.558029
cedf408ad18e9feaa234db282730488f696aa08e
1,752
package com.ctg.controller.portal; import com.ctg.common.Const; import com.ctg.common.ServerResponse; import com.ctg.pojo.User; import com.ctg.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; /** * Created by hfangjian on 2017/6/29. */ @Controller @RequestMapping("/user") public class UserController { @Autowired private IUserService iUserService; @RequestMapping(value = "/login",method = RequestMethod.POST) @ResponseBody public ServerResponse<User> login(String username, String password, HttpSession session){ ServerResponse<User> response = iUserService.login(username,password); if(response.isSuccess()){ session.setAttribute(Const.CURRENT_USER,response.getData()); } return response; } @RequestMapping(value = "/logout",method = RequestMethod.GET) @ResponseBody public ServerResponse<String> logout(HttpSession session){ session.removeAttribute(Const.CURRENT_USER); return ServerResponse.createBySuccess(); } @RequestMapping(value = "/register",method = RequestMethod.POST) @ResponseBody public ServerResponse<String> register(User user){ return iUserService.register(user); } @RequestMapping(value = "/check_valid.do",method = RequestMethod.POST) @ResponseBody public ServerResponse<String> checkValid(String str,String type){ return iUserService.checkValid(str,type); } }
31.854545
93
0.742009
08c563cb1545694a7c5425a270054240f2b3ac71
1,568
package org.activiti5.engine.impl.event.logger.handler; import java.util.HashMap; import java.util.Map; import org.activiti.engine.delegate.event.ActivitiMessageEvent; import org.activiti5.engine.impl.interceptor.CommandContext; import org.activiti5.engine.impl.persistence.entity.EventLogEntryEntity; /** * @author Joram Barrez */ public class ActivityMessageEventHandler extends AbstractDatabaseEventLoggerEventHandler { @Override public EventLogEntryEntity generateEventLogEntry(CommandContext commandContext) { ActivitiMessageEvent messageEvent = (ActivitiMessageEvent) event; Map<String, Object> data = new HashMap<String, Object>(); putInMapIfNotNull(data, Fields.ACTIVITY_ID, messageEvent.getActivityId()); putInMapIfNotNull(data, Fields.ACTIVITY_NAME, messageEvent.getActivityName()); putInMapIfNotNull(data, Fields.PROCESS_DEFINITION_ID, messageEvent.getProcessDefinitionId()); putInMapIfNotNull(data, Fields.PROCESS_INSTANCE_ID, messageEvent.getProcessInstanceId()); putInMapIfNotNull(data, Fields.EXECUTION_ID, messageEvent.getExecutionId()); putInMapIfNotNull(data, Fields.ACTIVITY_TYPE, messageEvent.getActivityType()); putInMapIfNotNull(data, Fields.BEHAVIOR_CLASS, messageEvent.getBehaviorClass()); putInMapIfNotNull(data, Fields.MESSAGE_NAME, messageEvent.getMessageName()); putInMapIfNotNull(data, Fields.MESSAGE_DATA, messageEvent.getMessageData()); return createEventLogEntry(messageEvent.getProcessDefinitionId(), messageEvent.getProcessInstanceId(), messageEvent.getExecutionId(), null, data); } }
43.555556
105
0.819515
1c1f27af6f8dd01baef96b25b2f994c95251c020
844
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class ScoringMatrixTest { ScoringMatrix sm; public ScoringMatrixTest(){ this.sm = new ScoringMatrix(); } // @Before // public void setup(){ // sm = new ScoringMatrix(); // } @DataProvider(name = "testScoringProvider") public static Object[][] testScoringProvider(){ return new Object[][] { // sigBit, aminoAcid, expectedVal {'A', 'A', 4}, {'K', 'L', -2}, {'Z', 'R', 0} }; } @Test(dataProvider = "testScoringProvider") public void testScoring(char sigBit, char aminoAcid, int expectedVal){ assertEquals(sm.getCharScore(sigBit, aminoAcid), expectedVal); } }
21.641026
74
0.593602
3054d684244381085140287af289261798ed242f
1,183
/** * Classe used to produce calculator. * * @since 1.0 * @author Dinar Khalfin * @version 1.0 */ package ru.job4j.calculator; /** * Calculator. * * @author Dinar Khalfin (dinarhalfin@yahoo.com) * @version $Id$ * @since 27.06.2017 */ public class Calculator { /** * Result. */ private double result; /** * Summ. * @param first - first. * @param second - second. */ public void add(double first, double second) { this.result = first + second; } /** * Substruct. * @param first - first. * @param second - second. */ public void substruct(double first, double second) { this.result = first - second; } /** * Division. * @param first - first. * @param second - second. */ public void div(double first, double second) { this.result = first / second; } /** * Multiplication. * @param first - first. * @param second - second. */ public void multiple(double first, double second) { this.result = first * second; } /** * Get the result. * @return result. */ public double getResult() { return this.result; } }
19.393443
58
0.56213
8b2c2f155edd1e88c8c34fd4190f774f26412c68
1,243
package com.breakersoft.plow; import java.util.UUID; public class TaskE implements Task { private UUID jobId; private UUID layerId; private UUID taskId; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public UUID getLayerId() { return layerId; } @Override public UUID getTaskId() { return taskId; } @Override public UUID getJobId() { return jobId; } public void setJobId(UUID jobId) { this.jobId = jobId; } public void setLayerId(UUID layerId) { this.layerId = layerId; } public void setTaskId(UUID frameId) { this.taskId = frameId; } public int hashCode() { return taskId.hashCode(); } public String toString() { return String.format("%s [%s]", name, taskId); } public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj.getClass() != getClass()) return false; Task other = (Task) obj; return taskId.equals(other.getTaskId()); } }
18.833333
54
0.56074
96273bbc2536afba3ee6ba327917640d7ee26c07
9,472
package com.thinkgem.jeesite.modules.gsp.service.t01complprod; import com.thinkgem.jeesite.common.StatusEnum.ApprStatus; import com.thinkgem.jeesite.common.service.GenericBusinessService; import com.thinkgem.jeesite.common.service.ServiceFlag; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.modules.gsp.dao.t01complprod.T01ComplProdDao; import com.thinkgem.jeesite.modules.gsp.dao.t01complprodcert.T01ComplProdCertDao; import com.thinkgem.jeesite.modules.gsp.dao.t01matrinfo.T01MatrInfoDao; import com.thinkgem.jeesite.modules.gsp.dao.t01prodcert.T01ProdCertDao; import com.thinkgem.jeesite.modules.gsp.entity.t01complprod.ComplProdStates; import com.thinkgem.jeesite.modules.gsp.entity.t01complprod.T01ComplProd; import com.thinkgem.jeesite.modules.gsp.entity.t01complprodcert.T01ComplProdCert; import com.thinkgem.jeesite.modules.gsp.entity.t01matrinfo.MatrInfoStates; import com.thinkgem.jeesite.modules.gsp.entity.t01matrinfo.MatrType; import com.thinkgem.jeesite.modules.gsp.entity.t01matrinfo.T01MatrInfo; import com.thinkgem.jeesite.modules.gsp.entity.t01prodcert.T01ProdCert; import com.thinkgem.jeesite.modules.gsp.service.exception.ApprStatusException; import com.thinkgem.jeesite.modules.gsp.service.exception.BusinessException; import com.thinkgem.jeesite.modules.gsp.service.exception.EntityExistedException; import com.thinkgem.jeesite.modules.gsp.service.exception.NoSuchTypeException; import com.thinkgem.jeesite.modules.gsp.service.t01complprodcert.T01ComplProdCertService; import com.thinkgem.jeesite.modules.gsp.service.t01prodcert.ProdCertStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * 首营产品Service * @author XXS * @version 2016-12-06 */ @Service @Transactional public class T01ComplProdBusinessService extends GenericBusinessService<T01ComplProd> { /** 首营产品资质关联Service */ private T01ComplProdCertService t01ComplProdCertService; /** 首营产品资质关联Dao */ private T01ComplProdCertDao t01ComplProdCertDao; /** 物料信息Dao */ private T01MatrInfoDao t01MatrInfoDao; /** 产品资质Dao */ private T01ProdCertDao t01ProdCertDao; /** 首营产品Dao */ private T01ComplProdDao t01ComplProdDao; @Autowired public T01ComplProdBusinessService( T01ComplProdCertService t01ComplProdCertService, T01ComplProdCertDao t01ComplProdCertDao, T01MatrInfoDao t01MatrInfoDao, T01ProdCertDao t01ProdCertDao, T01ComplProdDao t01ComplProdDao) { Assert.notNull(t01ComplProdCertService); Assert.notNull(t01ComplProdCertDao); Assert.notNull(t01MatrInfoDao); Assert.notNull(t01ProdCertDao); Assert.notNull(t01ComplProdDao); this.t01ComplProdCertService = t01ComplProdCertService; this.t01ComplProdCertDao=t01ComplProdCertDao; this.t01MatrInfoDao=t01MatrInfoDao; this.t01ProdCertDao=t01ProdCertDao; this.t01ComplProdDao=t01ComplProdDao; } /** * 插入entity前进行唯一和状态检查,进行默认值赋值 * @param entity entity * @return ServiceFlag * @throws BusinessException exception */ @Override public ServiceFlag preInsert(T01ComplProd entity) throws BusinessException { checkOnly(entity); checkApprStatu(entity); //设置新添加的数据审核状态为未提交 entity.setApprStat(ApprStatus.NOSUBMIT.toString()); entity.setComplProdStat(ComplProdStates.EFFECTIVE.toString()); return ServiceFlag.SUCCESS; } /** * 更新entity前进行唯一和状态检查 * @param entity entity * @return ServiceFlag * @throws BusinessException exception */ @Override public ServiceFlag preUpdate(T01ComplProd entity) throws BusinessException { checkOnly(entity); checkApprStatu(entity); return ServiceFlag.SUCCESS; } /** * 关联物料与资质前,检查两者审批状态。要求为审批通过 * 同时要求物料和资质不能为空 * @param t01ComplProd entity */ private void checkApprStatu(T01ComplProd t01ComplProd) throws BusinessException { if (t01ComplProd != null) { if (StringUtils.isNotBlank(t01ComplProd.getMatrId())) { T01MatrInfo t01MatrInfo = new T01MatrInfo(); t01MatrInfo.setId(t01ComplProd.getMatrId()); T01MatrInfo t01MatrInfoResult = t01MatrInfoDao.get(t01MatrInfo); if (t01MatrInfoResult != null) { if (!ApprStatus.PASS.toString().equals(t01MatrInfoResult.getApprStat())) { throw new ApprStatusException("保存失败,相关信息通过审批后才能进行关联保存", ""); } if (MatrInfoStates.FREEZE.toString().equals(t01MatrInfoResult.getMartStat())) { throw new ApprStatusException("保存失败,相关信息在冻结状态无法进行关联保存", ""); } if (MatrType.NOT_MEDICAL.toString().equals(t01MatrInfoResult.getMatrType())) { throw new ApprStatusException("保存失败,非医疗器械物料信息无法进行关联保存", ""); } } }else { throw new NoSuchTypeException("保存失败,必须关联物料信息",""); } if (t01ComplProd.getProdCertIdList()!=null) { for (String prodCertId : t01ComplProd.getProdCertIdList()) { T01ProdCert t01ProdCert = new T01ProdCert(); t01ProdCert.setId(prodCertId); T01ProdCert t01ProdCertResult = t01ProdCertDao.get(t01ProdCert); if (t01ProdCertResult != null) { if (!ApprStatus.PASS.toString().equals(t01ProdCertResult.getApprStat())) { throw new ApprStatusException("保存失败,相关信息通过审批后才能进行关联保存", ""); } if (ProdCertStatus.CertStatus.FREEZE.toString().equals(t01ProdCertResult.getCertStat())) { throw new ApprStatusException("保存失败,相关信息在冻结状态无法进行关联保存", ""); } } } }else { throw new NoSuchTypeException("保存失败,必须关联产品资质信息",""); } } } /** * 相同物料号+规格型号只能保存一次 * @param t01ComplProd entity * @throws BusinessException exception */ private void checkOnly(T01ComplProd t01ComplProd) throws BusinessException { if (t01ComplProd != null) { T01ComplProd t01ComplProdSearch = new T01ComplProd(); t01ComplProdSearch.setMatrId(t01ComplProd.getMatrId()); t01ComplProdSearch.setSpecType(t01ComplProd.getSpecType()); List<T01ComplProd> t01ComplProdList = t01ComplProdDao.findList(t01ComplProdSearch); if (StringUtils.isNotBlank(t01ComplProd.getId())) { t01ComplProdList = t01ComplProdList.stream().filter(item -> !t01ComplProd.getId().equals(item.getId())).collect(Collectors.toList()); } if (t01ComplProdList != null && !t01ComplProdList.isEmpty()) { throw new EntityExistedException("保存失败,相同首营产品信息已存在", ""); } } } /** * 在插入首营产品信息后,插入新的资质关联 * @param entity entity * @return ServiceFlag * @throws BusinessException exception */ @Override public ServiceFlag postInsert(T01ComplProd entity) throws BusinessException { saveProdCertIdList(entity); return ServiceFlag.SUCCESS; } /** * 在更新首营产品信息后,删除原来资质关联信息,插入新的资质关联 * @param entity entity * @return ServiceFlag * @throws BusinessException exception */ @Override public ServiceFlag postUpdate(T01ComplProd entity) throws BusinessException { t01ComplProdCertDao.deleteByComplProdId(entity.getId()); saveProdCertIdList(entity); return ServiceFlag.SUCCESS; } /** * 保持资质关联 * @param entity 首营产品entity * @throws BusinessException exception */ private void saveProdCertIdList(T01ComplProd entity) throws BusinessException { if (entity.getProdCertIdList() != null) { for (String prodCertId : entity.getProdCertIdList()) { T01ComplProdCert t01ComplProdCert = new T01ComplProdCert(); t01ComplProdCert.setComplProdId(entity.getId()); t01ComplProdCert.setProdCertId(prodCertId); t01ComplProdCertService.save(t01ComplProdCert); } } } /** * 获取entity后给ProdCertIdList赋值 * @param entity entity * @return ServiceFlag */ @Override public ServiceFlag postFetch(T01ComplProd entity) { if (entity != null && StringUtils.isNotBlank(entity.getId())) { T01ComplProdCert t01ComplProdCert = new T01ComplProdCert(); t01ComplProdCert.setComplProdId(entity.getId()); List<T01ComplProdCert> t01ComplProdCertList = t01ComplProdCertService.findList(t01ComplProdCert); if (!t01ComplProdCertList.isEmpty()) { List<String> prodCertIdList = new ArrayList<>(); for (T01ComplProdCert item : t01ComplProdCertList) { prodCertIdList.add(item.getProdCertId()); } entity.setProdCertIdList(prodCertIdList); } } return ServiceFlag.SUCCESS; } }
38.979424
149
0.670503
9baa64f172978187b34c52a2d2dce04bc083fdc9
3,423
package net.chestnut; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.stream.Collectors; import java.util.List; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.player.PlayerEntity; public final class PlayerRitualItem { private ItemEntity itemEntity; private String playerName; private String itemName; private Integer itemId; private static final List<String> ritualItemNames = new ArrayList<String>() {{ add("Dirt"); add("Birch Log"); }}; public PlayerRitualItem(ItemEntity itemEntity, PlayerEntity player) throws Exception { this.itemId = itemEntity.getId(); this.itemName = itemEntity.getStack().getName().getString(); this.playerName = player.getName().getString(); this.itemEntity = itemEntity; } public static Boolean HasDonatedEnoughItems(PlayerEntity player) { List<PlayerRitualItem> playerRitualItems = flattenListOfArrays(PlayerRitual.Inventory.values()); playerRitualItems = playerRitualItems.stream().filter(p -> p.getPlayerName().equals(player.getName().getString())).toList(); return HasRitualItems(playerRitualItems, "Dirt", 1) && HasRitualItems(playerRitualItems, "Birch Log", 1); // return HasItem(filteredPlayerRitualItems, "diamond", 2) && HasItem(filteredPlayerRitualItems, "rottenflesh", 10); } public static Boolean IsRitualItem(ItemEntity itemEntity) { return ritualItemNames.contains(itemEntity.getStack().getName().getString()); } public String getPlayerName() { return this.playerName; } public String getItemName() { return this.itemName; } public Integer getItemId() { return this.itemId; } private static Boolean HasRitualItems(List<PlayerRitualItem> playerRitualItems, String itemName, Integer minimumItemCount) { Hashtable<String, Integer> playerRitualItemCount = new Hashtable<String, Integer>(); for (PlayerRitualItem playerRitualItem : playerRitualItems) { if (!playerRitualItemCount.containsKey(playerRitualItem.getPlayerName())) { playerRitualItemCount.put(playerRitualItem.getPlayerName(), 0); } } for (PlayerRitualItem playerRitualItem : playerRitualItems) { String storedItemName = playerRitualItem.getItemName(); Boolean isItemMatch = storedItemName.equals(itemName); if (!playerRitualItem.itemEntity.getStack().isEmpty() && isItemMatch) { Integer itemCount = playerRitualItemCount.get(playerRitualItem.getPlayerName()); itemCount++; playerRitualItemCount.replace(playerRitualItem.getPlayerName(), itemCount); } } //check proximities and remove players that are not involved in the ritual Boolean hasRitualItems = true; for (PlayerRitualItem playerRitualItem : playerRitualItems) { if (playerRitualItemCount.get(playerRitualItem.getPlayerName()) < minimumItemCount){ hasRitualItems = false; break; } } return hasRitualItems; } private static <T> List<T> flattenListOfArrays(Collection<ArrayList<T>> arrayList) { return arrayList.stream() .flatMap(Collection::stream) .collect(Collectors.toList()); } }
45.64
132
0.684195
9c7f0e2df47bdf40221e6102aa26ab5f7973b755
1,234
/* * Java Examples * Version 1.0 * Copyright (C) GiusNiyyel, Inc - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Daniel Campos <giusniyyel@gmail.com>, May 2018 */ package Banco; import java.util.Scanner; /** * @author Admin */ public class BancoC { public static void main(String[] args) { Scanner entrada = new Scanner(System.in); int nc; double sa, tsa=0.0; do{ System.out.println("Introduzca su número de cuenta"); nc=entrada.nextInt(); if(nc>0){ System.out.println("Introduzca su saldo"); sa=entrada.nextInt(); System.out.println("\nCuenta: "+nc); if(sa>0){ System.out.println("Estado: Acreedor\n"); tsa+=sa; } else if(sa<0) System.out.println("Estado: Deudor\n"); else System.out.println("Estado: Nulo\n"); } }while(nc>0); System.out.println("Suma total de los saldos acreedores: "+tsa); } }
28.045455
75
0.519449
24fc916c7c7ae2f3a7837d4d6b3f5399f48f0381
487
package com.dlsc.workbenchfx.controls; import com.dlsc.workbenchfx.Workbench; import com.dlsc.workbenchfx.view.controls.module.Tab; import javafx.scene.control.Skin; public class CustomTab extends Tab { /** * Constructs a new {@link CustomTab}. * * @param workbench which created this {@link CustomTab} */ public CustomTab(Workbench workbench) { super(workbench); } @Override protected Skin<?> createDefaultSkin() { return new CustomTabSkin(this); } }
22.136364
58
0.718686
42d04c15fe82170e2d1ef26a1d19548406f4c230
3,806
package algo.leetcode; import java.util.ArrayList; import java.util.List; public class SumDistancesTree { class Node{ int father; List<Integer> childs = new ArrayList<>(); int count; int sum; } public int[] sumOfDistancesInTree(int N, int[][] edges) { Node[] nodes = new Node[N]; for(int[] edge : edges){ int f = edge[0]; int s = edge[1]; nodes[f].childs.add(s); nodes[s].father = f; nodes[f].sum = 0; nodes[s].count = 0; } int[] res = new int[N]; for(int i = 0; i < N; i ++){ res[i] = getDistance(i, nodes); } return res; } public int getDistance(int index, Node[] nodes){ int sum = 0; if(nodes[index].sum != 0)return nodes[index].sum; for(int child : nodes[index].childs){ sum += getDistance(child, nodes); } sum += getDistance(nodes[index].father, nodes); return sum; } public int[] sumOfDistancesInTree2(int N, int[][] edges) { if (N == 1) { return new int[N]; } if (N == 2) { return new int[]{1, 1}; } List<int[]>[] graph = new ArrayList[N]; for (int i = 0; i < N; i++) { graph[i] = new ArrayList<>(); } for (int i = 0; i < edges.length; i++) { // [0] = to [1] = sum [2] = num graph[edges[i][0]].add(new int[]{edges[i][1], 0, 0}); graph[edges[i][1]].add(new int[]{edges[i][0], 0, 0}); } int[] result = new int[N]; boolean[] seen = new boolean[N]; for (int i = 0; i < N; i++) { result[i] = dfs(graph, i, seen)[0]; } return result; } private int[] dfs(List<int[]>[] graph, int i, boolean[] seen) { seen[i] = true; int sum = 0; int num = 1; for (int[] adj : graph[i]) { if (!seen[adj[0]]) { if (adj[1] == 0 && adj[2] == 0) { int[] res = dfs(graph, adj[0], seen); adj[1] = res[0]; adj[2] = res[1]; } sum += (adj[1] + adj[2]); num += adj[2]; } } seen[i] = false; return new int[]{sum, num}; } int sum; int[] head; int[] e, next; int cnt; private void add(int u, int v) { next[cnt] = head[u]; e[cnt] = v; head[u] = cnt++; } public int[] sumOfDistancesInTree3(int n, int[][] ed) { int[] sz = new int[n]; int[] ans = new int[n]; head = new int[n]; next = new int[n << 1]; e = new int[n << 1]; cnt = 0; sum = 0; for (int i = 0; i < n; ++i) { head[i] = -1; } for (int i = 0; i + 1 < n; ++i) { add(ed[i][0], ed[i][1]); add(ed[i][1], ed[i][0]); } dfs(0, -1, sz, 0); ans[0] = sum; dfs(0, -1, ans, sz, n); return ans; } private void dfs(int u, int p, int[] ans, int[] sz, int n) { if (u == p) { return; } if (u != 0) { ans[u] = ans[p] - sz[u] + n - sz[u]; } for (int i = head[u]; i != -1; i = next[i]) { if (e[i] != p) { dfs(e[i], u, ans, sz, n); } } } private void dfs(int u, int p, int[] sz, int dis) { if (u == p) { return; } sum += dis; sz[u] = 1; for (int i = head[u]; i != -1; i = next[i]) { if (e[i] != p) { dfs(e[i], u, sz, dis + 1); sz[u] += sz[e[i]]; } } } }
25.543624
67
0.386495
f71fa6184db95eb1b092f86abdd59e0ea7ceb539
2,563
package mage.cards.p; import mage.abilities.condition.Condition; import mage.abilities.condition.common.PermanentsOnTheBattlefieldCondition; import mage.abilities.decorator.ConditionalOneShotEffect; import mage.abilities.effects.common.UntapTargetEffect; import mage.abilities.effects.common.continuous.GainAbilityTargetEffect; import mage.abilities.effects.common.continuous.GainControlTargetEffect; import mage.abilities.effects.keyword.ScryEffect; import mage.abilities.hint.ConditionHint; import mage.abilities.hint.Hint; import mage.abilities.keyword.HasteAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import mage.filter.FilterPermanent; import mage.filter.predicate.Predicates; import mage.target.common.TargetCreaturePermanent; import java.util.UUID; /** * @author TheElk801 */ public final class PacksBetrayal extends CardImpl { private static final FilterPermanent filter = new FilterPermanent(); static { filter.add(Predicates.or( SubType.WOLF.getPredicate(), SubType.WEREWOLF.getPredicate() )); } private static final Condition condition = new PermanentsOnTheBattlefieldCondition(filter); private static final Hint hint = new ConditionHint(condition, "You control a Wolf or Werewolf"); public PacksBetrayal(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{2}{R}"); // Gain control of target creature until end of turn. Untap that creature. It gains haste until end of turn. If you control a Wolf or Werewolf, scry 2. this.getSpellAbility().addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addEffect(new GainControlTargetEffect(Duration.EndOfTurn)); this.getSpellAbility().addEffect(new UntapTargetEffect().setText("Untap that creature")); this.getSpellAbility().addEffect(new GainAbilityTargetEffect( HasteAbility.getInstance(), Duration.EndOfTurn ).setText("It gains haste until end of turn.")); this.getSpellAbility().addEffect(new ConditionalOneShotEffect( new ScryEffect(2), condition, "If you control a Wolf or Werewolf, scry 2" )); this.getSpellAbility().addHint(hint); } private PacksBetrayal(final PacksBetrayal card) { super(card); } @Override public PacksBetrayal copy() { return new PacksBetrayal(this); } }
38.253731
159
0.736637
eb3652f80da19b3ae7095bf940e7a269ac3a8317
3,004
package me.bscal.game.mapping; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import me.bscal.game.graphics.Render; import me.bscal.game.sprites.AnimatedSprite; import me.bscal.game.sprites.Sprite; import me.bscal.game.sprites.SpriteHandler; import me.bscal.game.sprites.SpriteSheet; public class Tiles { private Scanner scanner; public List<Tile> tileList = new ArrayList<Tile>(); public Tiles(File tilesFile, SpriteSheet sheet) { try { scanner = new Scanner(tilesFile); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (!line.startsWith("//")) { String[] split = line.split(","); String tileName = split[0]; int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); Tile tile; if(tileName.equalsIgnoreCase("Water3")) { AnimatedSprite sprite = new AnimatedSprite(SpriteHandler.waterTiles, 6); tile = new Tile(tileName, sprite); } else { tile = new Tile(tileName, sheet.getSprite(x, y)); } if (split.length >= 4) { tile.collisionType = Integer.parseInt(split[3]); } tileList.add(tile); } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { scanner.close(); } } public void renderTile(int tileID, Render renderer, int xPos, int yPos, int xZoom, int yZoom) { if (tileList.size() > tileID && tileID >= 0) { renderer.renderSprite(tileList.get(tileID).sprite, xPos, yPos, xZoom, yZoom, false); } else { System.out.println("TileID out of bounds: " + tileID); } } public int size() { return tileList.size(); } public Sprite[] getSprites() { Sprite[] sprites = new Sprite[size()]; for (int i = 0; i < size(); i++) { sprites[i] = tileList.get(i).sprite; } return sprites; } public int getCollisionType(int tileID) { if (tileList.size() > tileID && tileID >= 0) { return tileList.get(tileID).collisionType; } else { System.out.println("Tile Collision: TileID out of bounds: " + tileID); } return -1; } public boolean isSolid(int tileID) { if (tileList.size() > tileID) { Tile tile = tileList.get(tileID); if (tile.collisionType >= 0) { return true; } } else { System.out.println("Tile Collision: TileID out of bounds: " + tileID); } return false; } public class Tile { public String tileName; public Sprite sprite; public AnimatedSprite animSprite; public int collisionType = -1; // -1 = Tile has no collision. public Tile(String tileName, Sprite sprite) { this.tileName = tileName; this.sprite = sprite; if (sprite instanceof AnimatedSprite) { this.animSprite = (AnimatedSprite) sprite; } } public void update() { if (sprite instanceof AnimatedSprite) { this.animSprite.update(null); } } } }
26.121739
97
0.634487
2cba0b37b707409308daf30e69f580cd867d7eae
57,697
package com.rbmhtechnology.vind.solr.backend; import com.fasterxml.jackson.databind.node.ObjectNode; import com.rbmhtechnology.vind.SearchServerException; import com.rbmhtechnology.vind.SearchServerProviderLoaderException; import com.rbmhtechnology.vind.annotations.AnnotationUtil; import com.rbmhtechnology.vind.api.Document; import com.rbmhtechnology.vind.api.SmartSearchServerBase; import com.rbmhtechnology.vind.api.ServiceProvider; import com.rbmhtechnology.vind.api.query.FulltextSearch; import com.rbmhtechnology.vind.api.query.delete.Delete; import com.rbmhtechnology.vind.api.query.division.Page; import com.rbmhtechnology.vind.api.query.division.Slice; import com.rbmhtechnology.vind.api.query.facet.Facet; import com.rbmhtechnology.vind.api.query.facet.Interval; import com.rbmhtechnology.vind.api.query.get.RealTimeGet; import com.rbmhtechnology.vind.api.query.inverseSearch.InverseSearch; import com.rbmhtechnology.vind.api.query.suggestion.DescriptorSuggestionSearch; import com.rbmhtechnology.vind.api.query.suggestion.ExecutableSuggestionSearch; import com.rbmhtechnology.vind.api.query.suggestion.StringSuggestionSearch; import com.rbmhtechnology.vind.api.query.update.Update; import com.rbmhtechnology.vind.api.query.update.Update.UpdateOperations; import com.rbmhtechnology.vind.api.query.update.UpdateOperation; import com.rbmhtechnology.vind.api.result.BeanGetResult; import com.rbmhtechnology.vind.api.result.BeanSearchResult; import com.rbmhtechnology.vind.api.result.DeleteResult; import com.rbmhtechnology.vind.api.result.FacetResults; import com.rbmhtechnology.vind.api.result.GetResult; import com.rbmhtechnology.vind.api.result.IndexResult; import com.rbmhtechnology.vind.api.result.InverseSearchResult; import com.rbmhtechnology.vind.api.result.PageResult; import com.rbmhtechnology.vind.api.result.SearchResult; import com.rbmhtechnology.vind.api.result.SliceResult; import com.rbmhtechnology.vind.api.result.StatusResult; import com.rbmhtechnology.vind.api.result.SuggestionResult; import com.rbmhtechnology.vind.configure.SearchConfiguration; import com.rbmhtechnology.vind.model.DocumentFactory; import com.rbmhtechnology.vind.model.FieldDescriptor; import com.rbmhtechnology.vind.model.InverseSearchQuery; import com.rbmhtechnology.vind.model.value.LatLng; import com.rbmhtechnology.vind.utils.SpecialCharacterEscaping; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.StringUtils; import org.apache.http.util.Asserts; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.SolrPingResponse; import org.apache.solr.client.solrj.response.UpdateResponse; import org.apache.solr.client.solrj.response.schema.SchemaResponse; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.DisMaxParams; import org.apache.solr.common.params.FacetParams; import org.apache.solr.common.params.StatsParams; import org.apache.solr.common.util.NamedList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.text.NumberFormat; import java.text.ParseException; import java.time.Instant; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.ServiceLoader; import java.util.Set; import java.util.SortedSet; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.rbmhtechnology.vind.api.query.update.Update.UpdateOperations.set; import static com.rbmhtechnology.vind.model.FieldDescriptor.*; import static com.rbmhtechnology.vind.solr.backend.SolrUtils.Fieldname.DISTANCE; import static com.rbmhtechnology.vind.solr.backend.SolrUtils.Fieldname.ID; import static com.rbmhtechnology.vind.solr.backend.SolrUtils.Fieldname.TEXT; import static com.rbmhtechnology.vind.solr.backend.SolrUtils.Fieldname.TYPE; import static com.rbmhtechnology.vind.solr.backend.SolrUtils.Fieldname.getFieldname; import static com.rbmhtechnology.vind.utils.SpecialCharacterEscaping.escapeSpecialCharacters; /** * @author Thomas Kurz (tkurz@apache.org) * @since 21.06.16. */ public class SolrSearchServer extends SmartSearchServerBase { private static final Logger log = LoggerFactory.getLogger(SolrSearchServer.class); private static final Logger solrClientLogger = LoggerFactory.getLogger(log.getName() + "#solrClient"); public static final String SOLR_WILDCARD = "*"; public static final String SUGGESTION_DF_FIELD = "suggestions"; public static SolrRequest.METHOD REQUEST_METHOD; private ServiceProvider serviceProviderClass; private final SolrClient solrClient; public SolrSearchServer() { // this is mainly used with the ServiceLoader infrastructure this(getSolrServerProvider() != null ? getSolrServerProvider().getInstance() : null); serviceProviderClass = getSolrServerProvider(); final String clientClass = serviceProviderClass.getClass().getSimpleName(); switch (clientClass) { case "EmbeddedSolrServerProvider": REQUEST_METHOD = SolrRequest.METHOD.GET; break; default: REQUEST_METHOD = SolrRequest.METHOD.POST; } } public SolrSearchServer(SolrClient client) { this(client, true); } /** * Creates an instance of SolrSearch server allowing to avoid the schema validity check. * @param client SolrClient to connect to. * @param check true to perform local schema validity check against remote schema, false otherwise. */ protected SolrSearchServer(SolrClient client, boolean check) { if(SearchConfiguration.get(SearchConfiguration.SERVER_COLLECTION_AUTOCREATE, false)) { log.warn("AutoGeneration of solr collection is not implemented, use collection management tool instead"); } solrClient = client; //In order to perform unit tests with mocked solrClient, we do not need to do the schema check. if(check && client != null) { try { final SolrPingResponse ping = solrClient.ping(); if (ping.getStatus() == 0) { log.debug("Pinged Solr in {}", ping.getQTime()); } } catch (SolrServerException | IOException e) { log.error("Cannot connect to solr server", e); throw new RuntimeException(); } log.info("Connection to solr server successful"); checkVersionAndSchema(); } else { log.warn("Solr ping and schema validity check has been deactivated."); } } private void checkVersionAndSchema() { //check schema try { final SchemaResponse response = new SchemaRequest().process(solrClient); final InputStream localSchema = this.getClass().getClassLoader().getResourceAsStream("solrhome/core/conf/schema.xml"); SolrSchemaChecker.checkSchema(localSchema, response); } catch (SolrServerException e) { log.error("Cannot get schema for solr client", e); throw new RuntimeException(e); } catch (IOException e) { log.error("Cannot read schema", e); throw new RuntimeException(e); } catch (SchemaValidationException e) { log.error("Schema is not valid for library", e); throw new RuntimeException(e); } } @Override public Object getBackend() { return solrClient; } @Override public StatusResult getBackendStatus() { try { SolrPingResponse ping = solrClient.ping(); int statusCode = ping.getStatus(); if(statusCode != 0) { return StatusResult.down().setDetail("status", statusCode); } else { return StatusResult.up().setDetail("status", statusCode); } } catch (SolrServerException | IOException e) { log.error("Cannot ping server"); throw new SearchServerException("Cannot ping server", e); } } @Override public IndexResult index(Document ... docs) { Asserts.notNull(docs,"Document to index should not be null."); Asserts.check(docs.length > 0, "Should be at least one document to index."); return indexMultipleDocuments(Arrays.asList(docs), -1); } @Override public IndexResult index(List<Document> docs) { Asserts.notNull(docs,"Document to index should not be null."); Asserts.check(docs.size() > 0, "Should be at least one document to index."); return indexMultipleDocuments(docs, -1); } @Override public IndexResult indexWithin(Document doc, int withinMs) { return this.indexSingleDocument(doc, withinMs); } @Override public IndexResult indexWithin(List<Document> doc, int withinMs) { return this.indexMultipleDocuments(doc, withinMs); } private IndexResult indexSingleDocument(Document doc, int withinMs) { final SolrInputDocument document = createInputDocument(doc); try { if (solrClientLogger.isTraceEnabled()) { solrClientLogger.debug(">>> add({}): {}", doc.getId(), ClientUtils.toXML(document)); } else { solrClientLogger.debug(">>> add({})", doc.getId()); } removeNonParentDocument(doc, withinMs); final UpdateResponse response = withinMs < 0 ? this.solrClient.add(document) : this.solrClient.add(document, withinMs); return new IndexResult(Long.valueOf(response.getQTime())).setElapsedTime(response.getElapsedTime()); } catch (SolrServerException | IOException e) { log.error("Cannot index document {}", document.getField(ID) , e); throw new SearchServerException("Cannot index document", e); } } private IndexResult indexMultipleDocuments(List<Document> docs, int withinMs) { final List<SolrInputDocument> solrDocs = docs.parallelStream() .map(doc -> createInputDocument(doc)) .collect(Collectors.toList()); try { if (solrClientLogger.isTraceEnabled()) { solrClientLogger.debug(">>> add({})", solrDocs); } else { solrClientLogger.debug(">>> add({})", solrDocs); } for(Document doc : docs){ removeNonParentDocument(doc, withinMs); } final UpdateResponse response = withinMs < 0 ? this.solrClient.add(solrDocs) : this.solrClient.add(solrDocs, withinMs); return new IndexResult(Long.valueOf(response.getQTime())).setElapsedTime(response.getElapsedTime()); } catch (SolrServerException | IOException e) { log.error("Cannot index documents {}", solrDocs, e); throw new SearchServerException("Cannot index documents", e); } } private void removeNonParentDocument(Document doc, int withinMs) throws SolrServerException, IOException { if(CollectionUtils.isNotEmpty(doc.getChildren())) { //Get the nested docs of the document if existing final SolrQuery q = new SolrQuery("!( _id_:"+ doc.getId()+")AND(_root_:"+ doc.getId()+")"); final QueryResponse query = solrClient.query(q, REQUEST_METHOD); if (CollectionUtils.isEmpty(query.getResults())) log.debug("Deleting document `{}`: document is becoming parent.",doc.getId()); if(withinMs < 0) { this.solrClient.deleteById(doc.getId()); } else { this.solrClient.deleteById(doc.getId(), withinMs); } } } private SolrInputDocument createInputDocument(Document doc) { final SolrInputDocument document = new SolrInputDocument(); //add fields doc.listFieldDescriptors() .values() .stream() .filter(doc::hasValue) //TODO: move again to an approach where we do not go through all the use cases but based on which flags the descriptor has set to true .forEach(descriptor -> doc.getFieldContexts(descriptor).stream().forEach(context -> Stream.of(UseCase.values()) .forEach(useCase -> { final String fieldname = getFieldname(descriptor, useCase, context); if (Objects.nonNull(fieldname)) { final Object value = doc.getContextualizedValue(descriptor, context); final Object caseValue = SolrUtils.FieldValue.getFieldCaseValue(value, descriptor, useCase); if(Objects.nonNull(caseValue)) { document.addField( fieldname, toSolrJType(caseValue) //,descriptor.getBoost() TODO should we have index time boost? ); } } } ))); //add subdocuments if (doc.hasChildren()) { doc.getChildren().forEach(childDocument -> document.addChildDocument(createInputDocument(childDocument)) ); } document.addField(ID, doc.getId()); document.addField(TYPE, doc.getType()); return document; } private Object toSolrJType(Object value) { if(value!=null) { if(Object[].class.isAssignableFrom(value.getClass())){ return toSolrJType(Arrays.asList((Object[])value)); } if(Collection.class.isAssignableFrom(value.getClass())){ return((Collection)value).stream() .map(o -> toSolrJType(o)) .collect(Collectors.toList()); } if(value instanceof ZonedDateTime) { return Date.from(((ZonedDateTime) value).toInstant()); } if(value instanceof LatLng) { return value.toString(); } if(value instanceof Date) { //noinspection RedundantCast return ((Date) value); } } return value; } @Override public void commit(boolean optimize) { try { solrClientLogger.debug(">>> commit()"); this.solrClient.commit(); if(optimize) { solrClientLogger.debug(">>> optimize()"); this.solrClient.optimize(); } } catch (SolrServerException | IOException e) { log.error("Cannot commit", e); throw new SearchServerException("Cannot commit", e); } } @Override protected <T> BeanSearchResult<T> doExecute(FulltextSearch search, Class<T> c) { final DocumentFactory factory = AnnotationUtil.createDocumentFactory(c); final SearchResult docResult = this.execute(search, factory); return docResult.toPojoResult(docResult, c); } @Override public DeleteResult delete(Document doc) { return this.deleteWithin(doc, -1); } @Override public DeleteResult deleteWithin(Document doc, int withinMs) { try { long qTime = 0; long elapsedTime = 0; solrClientLogger.debug(">>> delete({})", doc.getId()); final UpdateResponse deleteResponse = withinMs < 0 ? solrClient.deleteById(doc.getId()) : solrClient.deleteById(doc.getId(), withinMs); qTime = deleteResponse.getQTime(); elapsedTime = deleteResponse.getElapsedTime(); //Deleting nested documents final UpdateResponse deleteNestedResponse = withinMs < 0 ? solrClient.deleteByQuery("_root_:" + doc.getId()) : solrClient.deleteByQuery("_root_:" + doc.getId(), withinMs); qTime += deleteNestedResponse.getQTime(); elapsedTime += deleteNestedResponse.getElapsedTime(); return new DeleteResult(qTime).setElapsedTime(elapsedTime); } catch (SolrServerException | IOException e) { log.error("Cannot delete document {}", doc.getId() , e); throw new SearchServerException("Cannot delete document", e); } } @Override protected SearchResult doExecute(FulltextSearch search, DocumentFactory factory) { final SolrQuery query = buildSolrQuery(search, factory); //query try { solrClientLogger.debug(">>> query({})", query.toString()); final QueryResponse response = solrClient.query(query, REQUEST_METHOD); if(response!=null){ final SolrDocumentList responseResults = response.getResults(); if (search.isSpellcheck() && responseResults.getNumFound() <= 0 && response.getSpellCheckResponse() != null && !response.getSpellCheckResponse().isCorrectlySpelled() && CollectionUtils.isNotEmpty(response.getSpellCheckResponse().getCollatedResults())) { final FulltextSearch spellcheckSearch = search.copy().spellcheck(false).text(response.getSpellCheckResponse().getCollatedResult()); return execute(spellcheckSearch, factory); } final Map<String,Integer> childCounts = SolrUtils.getChildCounts(response); final List<Document> documents = SolrUtils.Result.buildResultList(responseResults, childCounts, factory, search.getSearchContext()); final FacetResults facetResults = SolrUtils.Result.buildFacetResult(response, factory, search.getChildrenFactory(), search.getFacets(),search.getSearchContext()); switch(search.getResultSet().getType()) { case page:{ return new PageResult(responseResults.getNumFound(), response.getQTime(), documents, search, facetResults, this, factory).setElapsedTime(response.getElapsedTime()); } case slice: { return new SliceResult(responseResults.getNumFound(), response.getQTime(), documents, search, facetResults, this, factory).setElapsedTime(response.getElapsedTime()); } default: return new PageResult(responseResults.getNumFound(), response.getQTime(), documents, search, facetResults, this, factory).setElapsedTime(response.getElapsedTime()); } }else { throw new SolrServerException("Null result from SolrClient"); } } catch (SolrServerException | IOException e) { throw new SearchServerException("Cannot issue query", e); } } @Override public String getRawQuery(FulltextSearch search, DocumentFactory factory) { final SolrQuery query = buildSolrQuery(search, factory); return query.toString(); } @Override public <T> String getRawQuery(FulltextSearch search, Class<T> c) { final DocumentFactory factory = AnnotationUtil.createDocumentFactory(c); final SolrQuery query = buildSolrQuery(search, factory); return query.toString(); } protected SolrQuery buildSolrQuery(FulltextSearch search, DocumentFactory factory) { //build query final SolrQuery query = new SolrQuery(); final String searchContext = search.getSearchContext(); if(search.getTimeZone() != null) { query.set(CommonParams.TZ,search.getTimeZone()); } // fulltext search query.set( CommonParams.Q, search.isEscapeCharacter() ? escapeSpecialCharacters(search.getSearchString()) : search.getSearchString() ); if(SearchConfiguration.get(SearchConfiguration.SEARCH_RESULT_SHOW_SCORE, true)) { query.set(CommonParams.FL, "*,score"); } else { query.set(CommonParams.FL, "*"); } if(search.getGeoDistance() != null) { final FieldDescriptor descriptor = factory.getField(search.getGeoDistance().getFieldName()); if (Objects.nonNull(descriptor)) { query.setParam(CommonParams.FL, query.get(CommonParams.FL) + "," + DISTANCE + ":geodist()"); query.setParam("pt", search.getGeoDistance().getLocation().toString()); query.setParam("sfield", getFieldname(descriptor, UseCase.Facet, searchContext)); } } Collection<FieldDescriptor<?>> fulltext = factory.listFields().stream().filter(FieldDescriptor::isFullText).collect(Collectors.toList()); if(!fulltext.isEmpty()) { query.setParam(DisMaxParams.QF, SolrUtils.Query.buildQueryFieldString(fulltext, searchContext)); query.setParam("defType","edismax"); } else { query.setParam(CommonParams.DF, TEXT); } //filters query.add(CommonParams.FQ,"_type_:"+factory.getType()); //mm query.setParam("mm", search.getMinimumShouldMatch()); if(search.hasFilter()) { SolrUtils.Query.buildFilterString(search.getFilter(), factory,search.getChildrenFactory(),query, searchContext, search.getStrict()); } if (search.isSpellcheck()) { query.setParam("spellcheck", true); query.setParam("spellcheck.collate", true); query.setParam("spellcheck.q", search.getSearchString()); } // fulltext search deep search if(search.isChildrenSearchEnabled()) { //append childCount facet search.facet(new Facet.SubdocumentFacet(factory)); //TODO: move to SolrUtils final String parentSearchQuery = "((" + query.get(CommonParams.Q) + ") AND " + TYPE + ":" + factory.getType() + ")"; final String childrenSearchQuery = search.getChildrenSearches().stream() .map( childrenSearch -> "_query_:\"{!parent which="+ TYPE+":"+factory.getType()+"}(" + TYPE+":"+search.getChildrenFactory().getType()+" AND (" + childrenSearch.getEscapedSearchString()+"))\"") .collect(Collectors.joining( " " + search.getChildrenSearchOperator().name() + " ")); query.set(CommonParams.Q, String.join(" ", parentSearchQuery, search.getChildrenSearchOperator().name(), childrenSearchQuery)); search.getChildrenSearches().forEach( childrenSearch -> { if(childrenSearch.hasFilter()){ //TODO clean up! final String parentFilterQuery = "(" + String.join(" AND ", query.getFilterQueries()) + ")"; final String childrenFilterQuery = new ChildrenFilterSerializer(factory,search.getChildrenFactory(),searchContext, search.getStrict(), true) .serialize(childrenSearch.getFilter()); query.set(CommonParams.FQ, String.join(" ", parentFilterQuery, search.getChildrenSearchOperator().name(), "(" + childrenFilterQuery + ")")); } } ); } if(search.hasFacet()) { query.setFacet(true); query.setFacetMinCount(search.getFacetMinCount()); query.setFacetLimit(search.getFacetLimit()); //Query facets search.getFacets().values().stream() .filter(facet -> Facet.QueryFacet.class.isAssignableFrom(facet.getClass())) .map(genericFacet -> (Facet.QueryFacet)genericFacet) .forEach(queryFacet -> query.addFacetQuery(StringUtils.join(SolrUtils.Query.buildSolrFacetCustomName(SolrUtils.Query.buildFilterString(queryFacet.getFilter(), factory, search.getChildrenFactory(), searchContext,search.getStrict()), queryFacet))) ); //Numeric Range facet search.getFacets().values().stream() .filter(facet -> Facet.NumericRangeFacet.class.isAssignableFrom(facet.getClass())) .map(genericFacet -> (Facet.NumericRangeFacet) genericFacet) .forEach(numericRangeFacet -> { final UseCase useCase = UseCase.valueOf(numericRangeFacet.getScope().name()); final String fieldName = getFieldname(numericRangeFacet.getFieldDescriptor(), useCase, searchContext); query.add(FacetParams.FACET_RANGE,SolrUtils.Query.buildSolrFacetCustomName(fieldName, numericRangeFacet)); query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName, FacetParams.FACET_RANGE_START), numericRangeFacet.getStart().toString()); query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName, FacetParams.FACET_RANGE_END), numericRangeFacet.getEnd().toString()); query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName, FacetParams.FACET_RANGE_GAP), numericRangeFacet.getGap().toString()); /*query.addNumericRangeFacet( SolrUtils.Query.buildSolrFacetCustomName(fieldName, numericRangeFacet.getName()), numericRangeFacet.getStart(), numericRangeFacet.getEnd(), numericRangeFacet.getGap());*/}); //Interval Range facet search.getFacets().values().stream() .filter(facet -> Facet.IntervalFacet.class.isAssignableFrom(facet.getClass())) .map(genericFacet -> (Facet.IntervalFacet) genericFacet) .forEach(intervalFacet -> { final UseCase useCase = UseCase.valueOf(intervalFacet.getScope().name()); final String fieldName = getFieldname(intervalFacet.getFieldDescriptor(), useCase, searchContext); query.add(FacetParams.FACET_INTERVAL, SolrUtils.Query.buildSolrFacetKey(intervalFacet.getFacetName()) + fieldName); for(Object o : intervalFacet.getIntervals()) { Interval i = (Interval) o; //TODO why is this necessary? query.add(String.format("f.%s.%s", fieldName, FacetParams.FACET_INTERVAL_SET), String.format("%s%s%s,%s%s", SolrUtils.Query.buildSolrFacetKey(i.getName()), i.includesStart() ? "[" : "(", i.getStart() == null? SOLR_WILDCARD : SolrUtils.Query.buildSolrQueryValue(i.getStart()), i.getEnd() == null? SOLR_WILDCARD : SolrUtils.Query.buildSolrQueryValue(i.getEnd()), i.includesEnd() ? "]" : ")") ); } }); //Date Range facet search.getFacets().values().stream() .filter(facet -> Facet.DateRangeFacet.class.isAssignableFrom(facet.getClass())) .map(genericFacet -> (Facet.DateRangeFacet)genericFacet) .forEach(dateRangeFacet -> generateDateRangeQuery(dateRangeFacet, query, searchContext) ); //stats search.getFacets().values().stream() .filter(facet -> Facet.StatsFacet.class.isAssignableFrom(facet.getClass())) .map(genericFacet -> (Facet.StatsFacet)genericFacet) .forEach(statsFacet -> { final UseCase useCase = UseCase.valueOf(statsFacet.getScope().name()); String fieldName = getFieldname(statsFacet.getField(), useCase, searchContext); query.add(StatsParams.STATS, "true"); query.add(StatsParams.STATS_FIELD, SolrUtils.Query.buildSolrStatsQuery(fieldName, statsFacet)); }); //pivot facet search.getFacets().values().stream() .filter(facet -> Facet.PivotFacet.class.isAssignableFrom(facet.getClass())) .map(genericFacet -> (Facet.PivotFacet)genericFacet) .forEach(pivotFacet -> { String[] fieldNames= pivotFacet.getFieldDescriptors().stream() .map(fieldDescriptor -> getFieldname(fieldDescriptor, UseCase.Facet, searchContext)) .toArray(String[]::new); query.add(FacetParams.FACET_PIVOT,SolrUtils.Query.buildSolrPivotSubFacetName(pivotFacet.getFacetName(),fieldNames)); }); //facet fields final ObjectNode jsonFacet = SolrUtils.Query.buildJsonTermFacet(search.getFacets(), search.getFacetLimit(), factory, search.getChildrenFactory(), searchContext); query.add("json.facet", jsonFacet.toString()); //facet Subdocument count final String subdocumentFacetString = SolrUtils.Query.buildSubdocumentFacet(search, factory, searchContext); if(Objects.nonNull(subdocumentFacetString)) { query.add("json.facet", subdocumentFacetString); } } // sorting if(search.hasSorting()) { final String sortString = SolrUtils.Query.buildSortString(search, search.getSorting(), factory); query.set(CommonParams.SORT, sortString); } //boost functions //TODO this is a mess if(search.hasSorting()) { query.set(DisMaxParams.BF, SolrUtils.Query.buildBoostFunction(search.getSorting(), searchContext)); } // paging switch(search.getResultSet().getType()) { case slice: { final Slice resultSet = (Slice) search.getResultSet(); query.setStart(resultSet.getOffset()); query.setRows(resultSet.getSliceSize()); break; } case cursor: { throw new NotImplementedException("Result sub type cursor is not supported by Solr backend"); } case page: default: { final Page resultSet = (Page) search.getResultSet(); query.setStart(resultSet.getOffset()); query.setRows(resultSet.getPagesize()); break; } } return query; } private void generateDateRangeQuery(Facet.DateRangeFacet dateRangeFacet, SolrQuery query, String searchContext) { final UseCase useCase = UseCase.valueOf(dateRangeFacet.getScope().name()); final String fieldName = getFieldname(dateRangeFacet.getFieldDescriptor(), useCase, searchContext); query.add(FacetParams.FACET_RANGE,SolrUtils.Query.buildSolrFacetCustomName(fieldName, dateRangeFacet)); final Object startDate = dateRangeFacet.getStart(); final Object endDate = dateRangeFacet.getEnd(); String startString; String endString; if (dateRangeFacet instanceof Facet.DateRangeFacet.UtilDateRangeFacet){ final Instant startInstant = ((Date) startDate).toInstant(); startString = DateTimeFormatter.ISO_INSTANT.format(startInstant); final Instant endInstant = ((Date) endDate).toInstant(); endString = DateTimeFormatter.ISO_INSTANT.format(endInstant); } else if (dateRangeFacet instanceof Facet.DateRangeFacet.ZoneDateRangeFacet){ final Instant startInstant = ((ZonedDateTime) startDate).toInstant(); startString = DateTimeFormatter.ISO_INSTANT.format(startInstant); final Instant endInstant = ((ZonedDateTime) endDate).toInstant(); endString = DateTimeFormatter.ISO_INSTANT.format(endInstant); } else { startString = dateRangeFacet.getStart().toString(); endString = dateRangeFacet.getEnd().toString(); } query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName, FacetParams.FACET_RANGE_START), startString); query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName, FacetParams.FACET_RANGE_END), endString); query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName, FacetParams.FACET_RANGE_GAP), SolrUtils.Query.buildSolrTimeGap(dateRangeFacet.getGap())); } @Override public boolean execute(Update update,DocumentFactory factory) { //Check if document is updatable and all its fields are stored. final boolean isUpdatable = factory.isUpdatable() && factory.getFields().values().stream() .allMatch( descriptor -> descriptor.isUpdate()); if (isUpdatable) { //Creates an atomic update solr document final SolrInputDocument sdoc = getSolrUpdateDocument(update, factory.getType()); try { if (solrClientLogger.isTraceEnabled()) { solrClientLogger.debug(">>> add({}): {}", update.getId(), sdoc); } else { solrClientLogger.debug(">>> add({})", update.getId()); } SolrInputDocument finalDoc = sdoc; //Get the original document log.debug("Atomic Update - Get version of original document [{}].",update.getId()); final SolrDocument updatedDoc = solrClient.getById(update.getId()); if (updatedDoc == null){ throw new SearchServerException("Can not execute solr partial update for non existing document for update id " + update.getId()); } //Setting the document version for optimistic concurrency final Object version = updatedDoc.getFieldValue("_version_"); if (Objects.nonNull(version)) { finalDoc.setField("_version_", version); } else { log.warn("Error updating document [{}]: " + "Atomic updates in nested documents are not supported by Solr", updatedDoc.get(ID)); return false; } //Get the nested docs of the document if existing log.debug("Atomic Update - Get nested documents of [{}].",update.getId()); final NamedList<Object> paramList = new NamedList<>(); paramList.add(CommonParams.Q, "!( _id_:"+ update.getId()+")&(_root_:"+ update.getId()+")"); final QueryResponse query = solrClient.query(paramList.toSolrParams(), REQUEST_METHOD); //if the document has nested docs solr does not support atomic updates if (CollectionUtils.isNotEmpty(query.getResults())) { log.debug("Update document [{}]: doc has {} nested documents, changing from partial update to full index.", finalDoc.getFieldValue(SolrUtils.Fieldname.ID), query.getResults().size()); //Get the list of nested documents final List<SolrInputDocument> childDocs = query.getResults().stream() .map(nestedDoc -> SolrUtils.toSolrInputDocument(nestedDoc)) .collect(Collectors.toList()); finalDoc = this.getUpdatedSolrDocument(sdoc, updatedDoc, childDocs); } try { log.debug("Atomic Update - Updating document [{}]: current version [{}]", finalDoc.getFieldValue(SolrUtils.Fieldname.ID), version); final UpdateResponse response = solrClient.add(finalDoc); log.debug("Atomic Update - Solr update time: query time [{}] - elapsed time [{}]", response.getQTime(), response.getQTime()); return true; } catch (HttpSolrClient.RemoteSolrException e) { log.warn("Error updating document [{}]: [{}]", finalDoc.getFieldValue(ID),e.getMessage(), e); return false; } } catch (SolrServerException | IOException e) { log.error("Unable to perform solr partial update on document with id [{}]", update.getId(), e); throw new SearchServerException("Can not execute solr partial update.", e); } } else { Exception e = new SearchServerException("It is not safe to execute solr partial update: Document contains non stored fields"); log.error("Unable to perform solr partial update on document with id [{}]", update.getId(), e); throw new RuntimeException("Can not execute solr partial update.", e); } } private SolrInputDocument getSolrUpdateDocument(Update update, String type) { final SolrInputDocument sdoc = new SolrInputDocument(); sdoc.addField(ID, update.getId()); sdoc.addField(TYPE, type); log.debug("Atomic Update - Mapping the Vind update operations to a solr document with ID [{}].", update.getId()); final HashMap<FieldDescriptor<?>, HashMap<String, SortedSet<UpdateOperation>>> updateOptions = update.getOptions(); log.debug("Atomic Update - Updating {} fields.", updateOptions.keySet().size()); updateOptions.keySet() .forEach(fieldDescriptor -> { log.debug("Atomic Update - Updating {} different contexts for field [{}].", updateOptions.get(fieldDescriptor).keySet().size(), fieldDescriptor); updateOptions.get(fieldDescriptor).keySet() .stream().forEach(context -> Stream.of(UseCase.values()).forEach(useCase -> { //NOTE: Backwards compatibility final String updateContext = Objects.isNull(context)? update.getUpdateContext() : context; final String fieldName = getFieldname(fieldDescriptor, useCase, updateContext); if (fieldName != null) { final Map<String, Object> fieldModifiers = new HashMap<>(); updateOptions.get(fieldDescriptor).get(context).stream().forEach(entry -> { UpdateOperations opType = entry.getType(); if(fieldName.startsWith("dynamic_single_") && useCase.equals(UseCase.Sort) && opType.equals(UpdateOperations.add)) { opType = set; } fieldModifiers.put(opType.name(), toSolrJType(SolrUtils.FieldValue.getFieldCaseValue(entry.getValue(), fieldDescriptor, useCase))); }); sdoc.addField(fieldName, fieldModifiers); } }) ); } ); return sdoc; } private SolrInputDocument getUpdatedSolrDocument(SolrInputDocument sdoc, SolrDocument updatedDoc, List<SolrInputDocument> nestedDocs) { //TODO:find a better way - non deprecated way //Create an input document from the original doc to be updated final SolrInputDocument inputDoc = SolrUtils.toSolrInputDocument(updatedDoc); log.debug("Atomic Update - Manually update Document [{}].", sdoc.getField(ID).getValue()); //Add nested documents to the doc inputDoc.addChildDocuments(nestedDocs); //TODO: think about a cleaner solution //Update the original document sdoc.getFieldNames().stream() .filter(fn -> !fn.equals(ID) && !fn.equals(TYPE) && !fn.equals("_version_") )//TODO: Add all the special fields or do the oposite check, whether it fits a dynamic Vind field .forEach( fn -> { final ArrayList fieldOp = (ArrayList) sdoc.getFieldValues(fn); fieldOp.stream() .forEach( op -> { final Set<String> keys = ((HashMap<String, String>) op).keySet(); keys.stream() .forEach(k -> { switch (UpdateOperations.valueOf(k)) { case set: inputDoc.setField(fn, ((HashMap<String, String>) op).get(k) ); break; case add: inputDoc.addField(fn, ((HashMap<String, String>) op).get(k) ); break; case inc: final Number fieldValue; try { fieldValue = NumberFormat.getInstance().parse((String)inputDoc.getFieldValue(fn)); } catch (ParseException e) { throw new RuntimeException(); } inputDoc.setField(fn,String.valueOf(fieldValue.floatValue()+1)); break; case remove: inputDoc.removeField(fn); break; case removeregex: final String fieldStringValue = (String)inputDoc.getFieldValue(fn); final String regex = ((HashMap<String, String>) op).get(k); if (regex.matches(fieldStringValue)) { inputDoc.removeField(fn); } break; } }); } ); } ); return inputDoc; } @Override public DeleteResult execute(Delete delete, DocumentFactory factory) { String query = SolrUtils.Query.buildFilterString(delete.getQuery(), factory, delete.getUpdateContext(),true); try { solrClientLogger.debug(">>> delete query({})", query); final UpdateResponse deleteChildrenResponse = solrClient.deleteByQuery( String.format("{!child of='_type_:%s' v='%s'}", factory.getType(), query.trim().replaceAll("'","\""))); long qTime = deleteChildrenResponse.getQTime(); long elapsedTime = deleteChildrenResponse.getElapsedTime(); final UpdateResponse deleteResponse = solrClient.deleteByQuery(query.trim().replaceAll("^\\+","")); qTime += deleteResponse.getQTime(); elapsedTime += deleteResponse.getElapsedTime(); return new DeleteResult(qTime).setElapsedTime(elapsedTime); } catch (SolrServerException | IOException e) { log.error("Cannot delete with query {}", query, e); throw new SearchServerException("Cannot delete with query", e); } } @Override public <T> SuggestionResult execute(ExecutableSuggestionSearch search, Class<T> c) { DocumentFactory documentFactory = AnnotationUtil.createDocumentFactory(c); return this.execute(search, documentFactory); } @Override public SuggestionResult execute(ExecutableSuggestionSearch search, DocumentFactory assets) { return execute(search,assets,null); } @Override public SuggestionResult execute(ExecutableSuggestionSearch search, DocumentFactory assets,DocumentFactory childFactory) { SolrQuery query = buildSolrQuery(search, assets, childFactory); try { log.debug(">>> query({})", query.toString()); QueryResponse response = solrClient.query(query, REQUEST_METHOD); if(response!=null){ return SolrUtils.Result.buildSuggestionResult(response, assets, childFactory, search.getSearchContext()); }else { log.error("Null result from SolrClient"); throw new SolrServerException("Null result from SolrClient"); } } catch (SolrServerException | IOException e) { log.error("Cannot execute suggestion query"); throw new SearchServerException("Cannot execute suggestion query", e); } } @Override public String getRawQuery(ExecutableSuggestionSearch search, DocumentFactory factory) { final SolrQuery query = buildSolrQuery(search, factory, null); return query.toString(); } @Override public String getRawQuery(ExecutableSuggestionSearch search, DocumentFactory factory, DocumentFactory childFactory) { final SolrQuery query = buildSolrQuery(search, factory, childFactory); return query.toString(); } @Override public <T> String getRawQuery(ExecutableSuggestionSearch search, Class<T> c) { final DocumentFactory factory = AnnotationUtil.createDocumentFactory(c); final SolrQuery query = buildSolrQuery(search, factory, null); return query.toString(); } protected SolrQuery buildSolrQuery(ExecutableSuggestionSearch search, DocumentFactory assets, DocumentFactory childFactory) { final String searchContext = search.getSearchContext(); final SolrQuery query = new SolrQuery(); query.setRequestHandler("/suggester"); if(search.isStringSuggestion()) { StringSuggestionSearch s = (StringSuggestionSearch) search; query.setParam("suggestion.field", s.getSuggestionFields() .stream() .map(name -> { if(Objects.nonNull(childFactory)) { final FieldDescriptor<?> field = Objects.nonNull(assets.getField(name))? assets.getField(name): childFactory.getField(name); if(Objects.isNull(field)) { log.warn("No field descriptor found for field name {} in factories: {}, {}", name,assets.getType(), childFactory.getType()); } return getFieldname(field, UseCase.Suggest, searchContext); } else { if(Objects.isNull(assets.getField(name))) { log.warn("No field descriptor found for field name {} in factory: {}", name,assets.getType()); } return getFieldname(assets.getField(name), UseCase.Suggest, searchContext); } }) .filter(Objects::nonNull) .toArray(String[]::new)); } else { DescriptorSuggestionSearch s = (DescriptorSuggestionSearch) search; query.setParam("suggestion.field", s.getSuggestionFields() .stream() .map(descriptor -> getFieldname(descriptor, UseCase.Suggest, searchContext)) .filter(Objects::nonNull) .toArray(String[]::new)); } query.setParam("q", search.getInput()); query.setParam("suggestion.df", SUGGESTION_DF_FIELD);//TODO: somehow this is still needed here, it should by configuration query.setParam("suggestion.limit", String.valueOf(search.getLimit())); String parentTypeFilter = "_type_:" + assets.getType(); if(Objects.nonNull(childFactory)) { parentTypeFilter ="("+parentTypeFilter+" OR _type_:" + childFactory.getType() + ")"; } query.add(CommonParams.FQ, parentTypeFilter); search.getFulltextTerm().ifPresent(fulltextTerm -> query.add(CommonParams.FQ, fulltextTerm.getFulltextSearchTerm())); //filters if(search.hasFilter()) { SolrUtils.Query.buildFilterString(search.getFilter(), assets,childFactory,query, searchContext, false); } // suggestion deep search if(Objects.nonNull(childFactory)) { if(search.hasFilter()){ //TODO clean up! final String parentFilterQuery = "(" + String.join(" AND ", query.getFilterQueries()) + ")"; final String childrenFilterQuery = new ChildrenFilterSerializer(assets, childFactory, searchContext, false, true) .serialize(search.getFilter()); final String childrenBJQ = "{!child of=\"_type_:"+assets.getType()+"\" v="+"$childrenFilterQuery"+"}"; query.set("childrenFilterQuery", childrenFilterQuery); query.set(CommonParams.FQ, String.join(" OR ", parentFilterQuery, childrenBJQ)); } } return query; } @Override public <T> BeanGetResult<T> execute(RealTimeGet search, Class<T> c) { DocumentFactory documentFactory = AnnotationUtil.createDocumentFactory(c); final GetResult result = this.execute(search, documentFactory); return result.toPojoResult(result,c); } @Override public GetResult execute(RealTimeGet search, DocumentFactory assets) { SolrQuery query = buildSolrQuery(search, assets); try { log.debug(">>> query({})", query.toString()); QueryResponse response = solrClient.query(query, REQUEST_METHOD); if(response!=null){ return SolrUtils.Result.buildRealTimeGetResult(response, search, assets); }else { log.error("Null result from SolrClient"); throw new SolrServerException("Null result from SolrClient"); } } catch (SolrServerException | IOException e) { log.error("Cannot execute realTime get query"); throw new SearchServerException("Cannot execute realTime get query", e); } } @Override public InverseSearchResult execute(InverseSearch inverseSearch, DocumentFactory factory) { throw new NotImplementedException("This feature is not supported in the current Vind version"); } @Override public IndexResult addInverseSearchQuery(InverseSearchQuery query) { throw new NotImplementedException("This feature is not supported in the current Vind version"); } @Override public void clearIndex() { try { solrClientLogger.debug(">>> clear complete index"); solrClient.deleteByQuery("*:*"); } catch (SolrServerException | IOException e) { log.error("Cannot clear index", e); throw new SearchServerException("Cannot clear index", e); } } protected SolrQuery buildSolrQuery(RealTimeGet search, DocumentFactory assets) { SolrQuery query = new SolrQuery(); query.setRequestHandler("/get"); search.getValues().forEach(v -> query.add("id" , v.toString())); return query; } @Override public void close() { if (solrClient != null) try { solrClient.close(); } catch (IOException e) { log.error("Cannot close search server", e); throw new SearchServerException("Cannot close search server", e); } } protected static SolrServerProvider getSolrServerProvider() { String providerClassName = SearchConfiguration.get(SearchConfiguration.SERVER_PROVIDER, null); //Backwards compatibility needed final String solrProviderClassName = SearchConfiguration.get(SearchConfiguration.SERVER_SOLR_PROVIDER, null); if (providerClassName == null && solrProviderClassName != null) { providerClassName = solrProviderClassName; } final ServiceLoader<SolrServerProvider> loader = ServiceLoader.load(SolrServerProvider.class); final Iterator<SolrServerProvider> it = loader.iterator(); SolrServerProvider serverProvider = null; if(providerClassName == null) { if (!it.hasNext()) { log.error("No SolrServerProvider in classpath"); throw new SearchServerProviderLoaderException( "No SolrServerProvider in classpath", serverProvider.getClass()); } else { serverProvider = it.next(); } } else { try { final Class<?> providerClass = Class.forName(providerClassName); if (SolrServerProvider.class.isAssignableFrom(providerClass)) { while (it.hasNext()) { final SolrServerProvider p = it.next(); if (providerClass.isAssignableFrom(p.getClass())) { serverProvider = p; break; } } if (Objects.isNull(serverProvider)) { log.debug("No Solr server provider of type class {} found in classpath for server {}", providerClassName, SolrSearchServer.class.getCanonicalName()); //throw new RuntimeException("No server provider found for class " + providerClassName); } } else { log.debug("Search server provider class {} configured is not assignable to {}", providerClassName, SolrServerProvider.class.getCanonicalName()); throw new SearchServerProviderLoaderException( String.format("Search server provider class %s configured is not assignable to %s",providerClassName, SolrServerProvider.class.getCanonicalName()), SolrServerProvider.class ); } } catch (ClassNotFoundException e) { log.warn("Specified class {} is not in classpath",providerClassName, e); throw new SearchServerProviderLoaderException( String.format("Specified class %s is not in classpath",providerClassName), SolrServerProvider.class ); } } return serverProvider; } @Override public Class<? extends ServiceProvider> getServiceProviderClass() { return serviceProviderClass!=null? serviceProviderClass.getClass() : null; } @Override public void closeCursor(String cursor) { throw new NotImplementedException("Solr backend does not support cursor search"); } }
48.040799
249
0.586824
5362a8d88e53dc6742f73abdd5c90dd879407ab3
1,510
package com.example.redis.config; import com.example.redis.entity.User; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration @EnableRedisRepositories public class RedisConfig { @Autowired private RedisTemplate redisTemplate; @Bean public HashOperations<String, byte[], byte[]> hashOperations() { return redisTemplate.opsForHash(); } @Autowired private ObjectMapper objectMapper; @Bean public HashOperations<Object, String, Object> jacksonHashOperations() { RedisTemplate redisTemplate = new RedisTemplate(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); serializer.setObjectMapper(objectMapper); redisTemplate.setHashValueSerializer(serializer); return redisTemplate.opsForHash(); } }
36.829268
95
0.792715