text
stringlengths
10
2.72M
package br.com.wasys.gfin.cheqfast.cliente.endpoint; import br.com.wasys.gfin.cheqfast.cliente.model.ContaBancoModel; import br.com.wasys.gfin.cheqfast.cliente.model.TransferenciaModel; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; /** * Created by pascke on 02/08/16. */ public interface TransferenciaEndpoint { @GET("transferencia/obter/{id}") Call<TransferenciaModel> obter(@Path("id") Long id); }
package be.mxs.common.model.vo; import java.io.Serializable; /** * Created by IntelliJ IDEA. * User: MichaŽl * Date: 09-juil.-2003 * Time: 11:37:33 * To change this template use Options | File Templates. */ public class ValueObjectContainer implements Serializable{ private String valueObjectPath; private Object valueObject; public ValueObjectContainer(String valueObjectPath, Object valueObject) { this.valueObjectPath = valueObjectPath; this.valueObject = valueObject; } public String getValueObjectPath() { return valueObjectPath; } public void setValueObjectPath(String valueObjectPath) { this.valueObjectPath = valueObjectPath; } public Object getValueObject() { return valueObject; } public void setValueObject(Object valueObject) { this.valueObject = valueObject; } }
package com.bs.guestbook.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service("factory") //@Component("factory") public class Factory { @Resource(name = "topicService") private TopicDao topicDAO; @Resource(name ="UserRegistrationService") private UserRegistrationDao userRegistrationDao; @Resource(name="UserRoleService") private UserRoleDao userRoleDao; @Resource(name="UserDao") private UserDao userDao; @Resource(name="SectionsDao") private SectionsDao sectionsDao; @Resource(name="OrderDao") private OrderDao orderDao; @Resource(name="CustomerDao") private CustomerDao customerDao; @Resource(name="ProductPositionDao") private ProductPositionDao productPositionDao; public Factory() { } public TopicDao getTopicDAO() { return topicDAO; } public UserRegistrationDao getUserRegistrationDao() { return userRegistrationDao; } public UserRoleDao getUserRoleDao() { return userRoleDao; } public UserDao getUserDao() { return userDao; } public SectionsDao getSectionsDao() { return sectionsDao; } public OrderDao getOrderDao() { return orderDao; } public CustomerDao getCustomerDao() { return customerDao; } public ProductPositionDao getProductPositionDao() { return productPositionDao; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.util; import java.io.ByteArrayOutputStream; import java.nio.charset.Charset; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; import java.util.StringJoiner; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.stream.Collectors; import org.springframework.lang.Nullable; /** * Miscellaneous {@link String} utility methods. * * <p>Mainly for internal use within the framework; consider * <a href="https://commons.apache.org/proper/commons-lang/">Apache's Commons Lang</a> * for a more comprehensive suite of {@code String} utilities. * * <p>This class delivers some simple functionality that should really be * provided by the core Java {@link String} and {@link StringBuilder} * classes. It also provides easy-to-use methods to convert between * delimited strings, such as CSV strings, and collections and arrays. * * @author Rod Johnson * @author Juergen Hoeller * @author Keith Donald * @author Rob Harrop * @author Rick Evans * @author Arjen Poutsma * @author Sam Brannen * @author Brian Clozel * @since 16 April 2001 */ public abstract class StringUtils { private static final String[] EMPTY_STRING_ARRAY = {}; private static final String FOLDER_SEPARATOR = "/"; private static final char FOLDER_SEPARATOR_CHAR = '/'; private static final String WINDOWS_FOLDER_SEPARATOR = "\\"; private static final String TOP_PATH = ".."; private static final String CURRENT_PATH = "."; private static final char EXTENSION_SEPARATOR = '.'; private static final int DEFAULT_TRUNCATION_THRESHOLD = 100; private static final String TRUNCATION_SUFFIX = " (truncated)..."; //--------------------------------------------------------------------- // General convenience methods for working with Strings //--------------------------------------------------------------------- /** * Check whether the given object (possibly a {@code String}) is empty. * This is effectively a shortcut for {@code !hasLength(String)}. * <p>This method accepts any Object as an argument, comparing it to * {@code null} and the empty String. As a consequence, this method * will never return {@code true} for a non-null non-String object. * <p>The Object signature is useful for general attribute handling code * that commonly deals with Strings but generally has to iterate over * Objects since attributes may e.g. be primitive value objects as well. * <p><b>Note: If the object is typed to {@code String} upfront, prefer * {@link #hasLength(String)} or {@link #hasText(String)} instead.</b> * @param str the candidate object (possibly a {@code String}) * @since 3.2.1 * @deprecated as of 5.3, in favor of {@link #hasLength(String)} and * {@link #hasText(String)} (or {@link ObjectUtils#isEmpty(Object)}) */ @Deprecated public static boolean isEmpty(@Nullable Object str) { return (str == null || "".equals(str)); } /** * Check that the given {@code CharSequence} is neither {@code null} nor * of length 0. * <p>Note: this method returns {@code true} for a {@code CharSequence} * that purely consists of whitespace. * <p><pre class="code"> * StringUtils.hasLength(null) = false * StringUtils.hasLength("") = false * StringUtils.hasLength(" ") = true * StringUtils.hasLength("Hello") = true * </pre> * @param str the {@code CharSequence} to check (may be {@code null}) * @return {@code true} if the {@code CharSequence} is not {@code null} and has length * @see #hasLength(String) * @see #hasText(CharSequence) */ public static boolean hasLength(@Nullable CharSequence str) { return (str != null && str.length() > 0); } /** * Check that the given {@code String} is neither {@code null} nor of length 0. * <p>Note: this method returns {@code true} for a {@code String} that * purely consists of whitespace. * @param str the {@code String} to check (may be {@code null}) * @return {@code true} if the {@code String} is not {@code null} and has length * @see #hasLength(CharSequence) * @see #hasText(String) */ public static boolean hasLength(@Nullable String str) { return (str != null && !str.isEmpty()); } /** * Check whether the given {@code CharSequence} contains actual <em>text</em>. * <p>More specifically, this method returns {@code true} if the * {@code CharSequence} is not {@code null}, its length is greater than * 0, and it contains at least one non-whitespace character. * <p><pre class="code"> * StringUtils.hasText(null) = false * StringUtils.hasText("") = false * StringUtils.hasText(" ") = false * StringUtils.hasText("12345") = true * StringUtils.hasText(" 12345 ") = true * </pre> * @param str the {@code CharSequence} to check (may be {@code null}) * @return {@code true} if the {@code CharSequence} is not {@code null}, * its length is greater than 0, and it does not contain whitespace only * @see #hasText(String) * @see #hasLength(CharSequence) * @see Character#isWhitespace */ public static boolean hasText(@Nullable CharSequence str) { if (str == null) { return false; } int strLen = str.length(); if (strLen == 0) { return false; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * Check whether the given {@code String} contains actual <em>text</em>. * <p>More specifically, this method returns {@code true} if the * {@code String} is not {@code null}, its length is greater than 0, * and it contains at least one non-whitespace character. * @param str the {@code String} to check (may be {@code null}) * @return {@code true} if the {@code String} is not {@code null}, its * length is greater than 0, and it does not contain whitespace only * @see #hasText(CharSequence) * @see #hasLength(String) * @see Character#isWhitespace */ public static boolean hasText(@Nullable String str) { return (str != null && !str.isBlank()); } /** * Check whether the given {@code CharSequence} contains any whitespace characters. * @param str the {@code CharSequence} to check (may be {@code null}) * @return {@code true} if the {@code CharSequence} is not empty and * contains at least 1 whitespace character * @see Character#isWhitespace */ public static boolean containsWhitespace(@Nullable CharSequence str) { if (!hasLength(str)) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * Check whether the given {@code String} contains any whitespace characters. * @param str the {@code String} to check (may be {@code null}) * @return {@code true} if the {@code String} is not empty and * contains at least 1 whitespace character * @see #containsWhitespace(CharSequence) */ public static boolean containsWhitespace(@Nullable String str) { return containsWhitespace((CharSequence) str); } /** * Trim leading and trailing whitespace from the given {@code String}. * @param str the {@code String} to check * @return the trimmed {@code String} * @see java.lang.Character#isWhitespace * @deprecated since 6.0, in favor of {@link String#strip()} */ @Deprecated(since = "6.0") public static String trimWhitespace(String str) { if (!hasLength(str)) { return str; } return str.strip(); } /** * Trim <em>all</em> whitespace from the given {@code CharSequence}: * leading, trailing, and in between characters. * @param str the {@code CharSequence} to check * @return the trimmed {@code CharSequence} * @since 5.3.22 * @see #trimAllWhitespace(String) * @see java.lang.Character#isWhitespace */ public static CharSequence trimAllWhitespace(CharSequence str) { if (!hasLength(str)) { return str; } int len = str.length(); StringBuilder sb = new StringBuilder(str.length()); for (int i = 0; i < len; i++) { char c = str.charAt(i); if (!Character.isWhitespace(c)) { sb.append(c); } } return sb; } /** * Trim <em>all</em> whitespace from the given {@code String}: * leading, trailing, and in between characters. * @param str the {@code String} to check * @return the trimmed {@code String} * @see #trimAllWhitespace(CharSequence) * @see java.lang.Character#isWhitespace */ public static String trimAllWhitespace(String str) { if (!hasLength(str)) { return str; } return trimAllWhitespace((CharSequence) str).toString(); } /** * Trim leading whitespace from the given {@code String}. * @param str the {@code String} to check * @return the trimmed {@code String} * @see java.lang.Character#isWhitespace * @deprecated since 6.0, in favor of {@link String#stripLeading()} */ @Deprecated(since = "6.0") public static String trimLeadingWhitespace(String str) { if (!hasLength(str)) { return str; } return str.stripLeading(); } /** * Trim trailing whitespace from the given {@code String}. * @param str the {@code String} to check * @return the trimmed {@code String} * @see java.lang.Character#isWhitespace * @deprecated since 6.0, in favor of {@link String#stripTrailing()} */ @Deprecated(since = "6.0") public static String trimTrailingWhitespace(String str) { if (!hasLength(str)) { return str; } return str.stripTrailing(); } /** * Trim all occurrences of the supplied leading character from the given {@code String}. * @param str the {@code String} to check * @param leadingCharacter the leading character to be trimmed * @return the trimmed {@code String} */ public static String trimLeadingCharacter(String str, char leadingCharacter) { if (!hasLength(str)) { return str; } int beginIdx = 0; while (beginIdx < str.length() && leadingCharacter == str.charAt(beginIdx)) { beginIdx++; } return str.substring(beginIdx); } /** * Trim all occurrences of the supplied trailing character from the given {@code String}. * @param str the {@code String} to check * @param trailingCharacter the trailing character to be trimmed * @return the trimmed {@code String} */ public static String trimTrailingCharacter(String str, char trailingCharacter) { if (!hasLength(str)) { return str; } int endIdx = str.length() - 1; while (endIdx >= 0 && trailingCharacter == str.charAt(endIdx)) { endIdx--; } return str.substring(0, endIdx + 1); } /** * Test if the given {@code String} matches the given single character. * @param str the {@code String} to check * @param singleCharacter the character to compare to * @since 5.2.9 */ public static boolean matchesCharacter(@Nullable String str, char singleCharacter) { return (str != null && str.length() == 1 && str.charAt(0) == singleCharacter); } /** * Test if the given {@code String} starts with the specified prefix, * ignoring upper/lower case. * @param str the {@code String} to check * @param prefix the prefix to look for * @see java.lang.String#startsWith */ public static boolean startsWithIgnoreCase(@Nullable String str, @Nullable String prefix) { return (str != null && prefix != null && str.length() >= prefix.length() && str.regionMatches(true, 0, prefix, 0, prefix.length())); } /** * Test if the given {@code String} ends with the specified suffix, * ignoring upper/lower case. * @param str the {@code String} to check * @param suffix the suffix to look for * @see java.lang.String#endsWith */ public static boolean endsWithIgnoreCase(@Nullable String str, @Nullable String suffix) { return (str != null && suffix != null && str.length() >= suffix.length() && str.regionMatches(true, str.length() - suffix.length(), suffix, 0, suffix.length())); } /** * Test whether the given string matches the given substring * at the given index. * @param str the original string (or StringBuilder) * @param index the index in the original string to start matching against * @param substring the substring to match at the given index */ public static boolean substringMatch(CharSequence str, int index, CharSequence substring) { if (index + substring.length() > str.length()) { return false; } for (int i = 0; i < substring.length(); i++) { if (str.charAt(index + i) != substring.charAt(i)) { return false; } } return true; } /** * Count the occurrences of the substring {@code sub} in string {@code str}. * @param str string to search in * @param sub string to search for */ public static int countOccurrencesOf(String str, String sub) { if (!hasLength(str) || !hasLength(sub)) { return 0; } int count = 0; int pos = 0; int idx; while ((idx = str.indexOf(sub, pos)) != -1) { ++count; pos = idx + sub.length(); } return count; } /** * Replace all occurrences of a substring within a string with another string. * @param inString {@code String} to examine * @param oldPattern {@code String} to replace * @param newPattern {@code String} to insert * @return a {@code String} with the replacements */ public static String replace(String inString, String oldPattern, @Nullable String newPattern) { if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) { return inString; } int index = inString.indexOf(oldPattern); if (index == -1) { // no occurrence -> can return input as-is return inString; } int capacity = inString.length(); if (newPattern.length() > oldPattern.length()) { capacity += 16; } StringBuilder sb = new StringBuilder(capacity); int pos = 0; // our position in the old string int patLen = oldPattern.length(); while (index >= 0) { sb.append(inString, pos, index); sb.append(newPattern); pos = index + patLen; index = inString.indexOf(oldPattern, pos); } // append any characters to the right of a match sb.append(inString, pos, inString.length()); return sb.toString(); } /** * Delete all occurrences of the given substring. * @param inString the original {@code String} * @param pattern the pattern to delete all occurrences of * @return the resulting {@code String} */ public static String delete(String inString, String pattern) { return replace(inString, pattern, ""); } /** * Delete any character in a given {@code String}. * @param inString the original {@code String} * @param charsToDelete a set of characters to delete. * E.g. "az\n" will delete 'a's, 'z's and new lines. * @return the resulting {@code String} */ public static String deleteAny(String inString, @Nullable String charsToDelete) { if (!hasLength(inString) || !hasLength(charsToDelete)) { return inString; } int lastCharIndex = 0; char[] result = new char[inString.length()]; for (int i = 0; i < inString.length(); i++) { char c = inString.charAt(i); if (charsToDelete.indexOf(c) == -1) { result[lastCharIndex++] = c; } } if (lastCharIndex == inString.length()) { return inString; } return new String(result, 0, lastCharIndex); } //--------------------------------------------------------------------- // Convenience methods for working with formatted Strings //--------------------------------------------------------------------- /** * Quote the given {@code String} with single quotes. * @param str the input {@code String} (e.g. "myString") * @return the quoted {@code String} (e.g. "'myString'"), * or {@code null} if the input was {@code null} */ @Nullable public static String quote(@Nullable String str) { return (str != null ? "'" + str + "'" : null); } /** * Turn the given Object into a {@code String} with single quotes * if it is a {@code String}; keeping the Object as-is else. * @param obj the input Object (e.g. "myString") * @return the quoted {@code String} (e.g. "'myString'"), * or the input object as-is if not a {@code String} */ @Nullable public static Object quoteIfString(@Nullable Object obj) { return (obj instanceof String str ? quote(str) : obj); } /** * Unqualify a string qualified by a '.' dot character. For example, * "this.name.is.qualified", returns "qualified". * @param qualifiedName the qualified name */ public static String unqualify(String qualifiedName) { return unqualify(qualifiedName, '.'); } /** * Unqualify a string qualified by a separator character. For example, * "this:name:is:qualified" returns "qualified" if using a ':' separator. * @param qualifiedName the qualified name * @param separator the separator */ public static String unqualify(String qualifiedName, char separator) { return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1); } /** * Capitalize a {@code String}, changing the first letter to * upper case as per {@link Character#toUpperCase(char)}. * No other letters are changed. * @param str the {@code String} to capitalize * @return the capitalized {@code String} */ public static String capitalize(String str) { return changeFirstCharacterCase(str, true); } /** * Uncapitalize a {@code String}, changing the first letter to * lower case as per {@link Character#toLowerCase(char)}. * No other letters are changed. * @param str the {@code String} to uncapitalize * @return the uncapitalized {@code String} */ public static String uncapitalize(String str) { return changeFirstCharacterCase(str, false); } /** * Uncapitalize a {@code String} in JavaBeans property format, * changing the first letter to lower case as per * {@link Character#toLowerCase(char)}, unless the initial two * letters are upper case in direct succession. * @param str the {@code String} to uncapitalize * @return the uncapitalized {@code String} * @since 6.0 * @see java.beans.Introspector#decapitalize(String) */ public static String uncapitalizeAsProperty(String str) { if (!hasLength(str) || (str.length() > 1 && Character.isUpperCase(str.charAt(0)) && Character.isUpperCase(str.charAt(1)))) { return str; } return changeFirstCharacterCase(str, false); } private static String changeFirstCharacterCase(String str, boolean capitalize) { if (!hasLength(str)) { return str; } char baseChar = str.charAt(0); char updatedChar; if (capitalize) { updatedChar = Character.toUpperCase(baseChar); } else { updatedChar = Character.toLowerCase(baseChar); } if (baseChar == updatedChar) { return str; } char[] chars = str.toCharArray(); chars[0] = updatedChar; return new String(chars); } /** * Extract the filename from the given Java resource path, * e.g. {@code "mypath/myfile.txt" &rarr; "myfile.txt"}. * @param path the file path (may be {@code null}) * @return the extracted filename, or {@code null} if none */ @Nullable public static String getFilename(@Nullable String path) { if (path == null) { return null; } int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR_CHAR); return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path); } /** * Extract the filename extension from the given Java resource path, * e.g. "mypath/myfile.txt" &rarr; "txt". * @param path the file path (may be {@code null}) * @return the extracted filename extension, or {@code null} if none */ @Nullable public static String getFilenameExtension(@Nullable String path) { if (path == null) { return null; } int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); if (extIndex == -1) { return null; } int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR_CHAR); if (folderIndex > extIndex) { return null; } return path.substring(extIndex + 1); } /** * Strip the filename extension from the given Java resource path, * e.g. "mypath/myfile.txt" &rarr; "mypath/myfile". * @param path the file path * @return the path with stripped filename extension */ public static String stripFilenameExtension(String path) { int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); if (extIndex == -1) { return path; } int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR_CHAR); if (folderIndex > extIndex) { return path; } return path.substring(0, extIndex); } /** * Apply the given relative path to the given Java resource path, * assuming standard Java folder separation (i.e. "/" separators). * @param path the path to start from (usually a full file path) * @param relativePath the relative path to apply * (relative to the full file path above) * @return the full file path that results from applying the relative path */ public static String applyRelativePath(String path, String relativePath) { int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR_CHAR); if (separatorIndex != -1) { String newPath = path.substring(0, separatorIndex); if (!relativePath.startsWith(FOLDER_SEPARATOR)) { newPath += FOLDER_SEPARATOR_CHAR; } return newPath + relativePath; } else { return relativePath; } } /** * Normalize the path by suppressing sequences like "path/.." and * inner simple dots. * <p>The result is convenient for path comparison. For other uses, * notice that Windows separators ("\") are replaced by simple slashes. * <p><strong>NOTE</strong> that {@code cleanPath} should not be depended * upon in a security context. Other mechanisms should be used to prevent * path-traversal issues. * @param path the original path * @return the normalized path */ public static String cleanPath(String path) { if (!hasLength(path)) { return path; } String normalizedPath = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); String pathToUse = normalizedPath; // Shortcut if there is no work to do if (pathToUse.indexOf('.') == -1) { return pathToUse; } // Strip prefix from path to analyze, to not treat it as part of the // first path element. This is necessary to correctly parse paths like // "file:core/../core/io/Resource.class", where the ".." should just // strip the first "core" directory while keeping the "file:" prefix. int prefixIndex = pathToUse.indexOf(':'); String prefix = ""; if (prefixIndex != -1) { prefix = pathToUse.substring(0, prefixIndex + 1); if (prefix.contains(FOLDER_SEPARATOR)) { prefix = ""; } else { pathToUse = pathToUse.substring(prefixIndex + 1); } } if (pathToUse.startsWith(FOLDER_SEPARATOR)) { prefix = prefix + FOLDER_SEPARATOR; pathToUse = pathToUse.substring(1); } String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR); // we never require more elements than pathArray and in the common case the same number Deque<String> pathElements = new ArrayDeque<>(pathArray.length); int tops = 0; for (int i = pathArray.length - 1; i >= 0; i--) { String element = pathArray[i]; if (CURRENT_PATH.equals(element)) { // Points to current directory - drop it. } else if (TOP_PATH.equals(element)) { // Registering top path found. tops++; } else { if (tops > 0) { // Merging path element with element corresponding to top path. tops--; } else { // Normal path element found. pathElements.addFirst(element); } } } // All path elements stayed the same - shortcut if (pathArray.length == pathElements.size()) { return normalizedPath; } // Remaining top paths need to be retained. for (int i = 0; i < tops; i++) { pathElements.addFirst(TOP_PATH); } // If nothing else left, at least explicitly point to current path. if (pathElements.size() == 1 && pathElements.getLast().isEmpty() && !prefix.endsWith(FOLDER_SEPARATOR)) { pathElements.addFirst(CURRENT_PATH); } final String joined = collectionToDelimitedString(pathElements, FOLDER_SEPARATOR); // avoid string concatenation with empty prefix return prefix.isEmpty() ? joined : prefix + joined; } /** * Compare two paths after normalization of them. * @param path1 first path for comparison * @param path2 second path for comparison * @return whether the two paths are equivalent after normalization */ public static boolean pathEquals(String path1, String path2) { return cleanPath(path1).equals(cleanPath(path2)); } /** * Decode the given encoded URI component value. Based on the following rules: * <ul> * <li>Alphanumeric characters {@code "a"} through {@code "z"}, {@code "A"} through {@code "Z"}, * and {@code "0"} through {@code "9"} stay the same.</li> * <li>Special characters {@code "-"}, {@code "_"}, {@code "."}, and {@code "*"} stay the same.</li> * <li>A sequence "{@code %<i>xy</i>}" is interpreted as a hexadecimal representation of the character.</li> * </ul> * @param source the encoded String * @param charset the character set * @return the decoded value * @throws IllegalArgumentException when the given source contains invalid encoded sequences * @since 5.0 * @see java.net.URLDecoder#decode(String, String) */ public static String uriDecode(String source, Charset charset) { int length = source.length(); if (length == 0) { return source; } Assert.notNull(charset, "Charset must not be null"); ByteArrayOutputStream baos = new ByteArrayOutputStream(length); boolean changed = false; for (int i = 0; i < length; i++) { int ch = source.charAt(i); if (ch == '%') { if (i + 2 < length) { char hex1 = source.charAt(i + 1); char hex2 = source.charAt(i + 2); int u = Character.digit(hex1, 16); int l = Character.digit(hex2, 16); if (u == -1 || l == -1) { throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); } baos.write((char) ((u << 4) + l)); i += 2; changed = true; } else { throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); } } else { baos.write(ch); } } return (changed ? StreamUtils.copyToString(baos, charset) : source); } /** * Parse the given {@code String} value into a {@link Locale}, accepting * the {@link Locale#toString} format as well as BCP 47 language tags as * specified by {@link Locale#forLanguageTag}. * @param localeValue the locale value: following either {@code Locale's} * {@code toString()} format ("en", "en_UK", etc), also accepting spaces as * separators (as an alternative to underscores), or BCP 47 (e.g. "en-UK") * @return a corresponding {@code Locale} instance, or {@code null} if none * @throws IllegalArgumentException in case of an invalid locale specification * @since 5.0.4 * @see #parseLocaleString * @see Locale#forLanguageTag */ @Nullable public static Locale parseLocale(String localeValue) { if (!localeValue.contains("_") && !localeValue.contains(" ")) { validateLocalePart(localeValue); Locale resolved = Locale.forLanguageTag(localeValue); if (resolved.getLanguage().length() > 0) { return resolved; } } return parseLocaleString(localeValue); } /** * Parse the given {@code String} representation into a {@link Locale}. * <p>For many parsing scenarios, this is an inverse operation of * {@link Locale#toString Locale's toString}, in a lenient sense. * This method does not aim for strict {@code Locale} design compliance; * it is rather specifically tailored for typical Spring parsing needs. * <p><b>Note: This delegate does not accept the BCP 47 language tag format. * Please use {@link #parseLocale} for lenient parsing of both formats.</b> * @param localeString the locale {@code String}: following {@code Locale's} * {@code toString()} format ("en", "en_UK", etc), also accepting spaces as * separators (as an alternative to underscores) * @return a corresponding {@code Locale} instance, or {@code null} if none * @throws IllegalArgumentException in case of an invalid locale specification */ @SuppressWarnings("deprecation") // for Locale constructors on JDK 19 @Nullable public static Locale parseLocaleString(String localeString) { if (localeString.equals("")) { return null; } String delimiter = "_"; if (!localeString.contains("_") && localeString.contains(" ")) { delimiter = " "; } String[] tokens = localeString.split(delimiter, -1); if (tokens.length == 1) { String language = tokens[0]; validateLocalePart(language); return new Locale(language); } else if (tokens.length == 2) { String language = tokens[0]; validateLocalePart(language); String country = tokens[1]; validateLocalePart(country); return new Locale(language, country); } else if (tokens.length > 2) { String language = tokens[0]; validateLocalePart(language); String country = tokens[1]; validateLocalePart(country); String variant = Arrays.stream(tokens).skip(2).collect(Collectors.joining(delimiter)); return new Locale(language, country, variant); } throw new IllegalArgumentException("Invalid locale format: '" + localeString + "'"); } private static void validateLocalePart(String localePart) { for (int i = 0; i < localePart.length(); i++) { char ch = localePart.charAt(i); if (ch != ' ' && ch != '_' && ch != '-' && ch != '#' && !Character.isLetterOrDigit(ch)) { throw new IllegalArgumentException( "Locale part \"" + localePart + "\" contains invalid characters"); } } } /** * Parse the given {@code timeZoneString} value into a {@link TimeZone}. * @param timeZoneString the time zone {@code String}, following {@link TimeZone#getTimeZone(String)} * but throwing {@link IllegalArgumentException} in case of an invalid time zone specification * @return a corresponding {@link TimeZone} instance * @throws IllegalArgumentException in case of an invalid time zone specification */ public static TimeZone parseTimeZoneString(String timeZoneString) { TimeZone timeZone = TimeZone.getTimeZone(timeZoneString); if ("GMT".equals(timeZone.getID()) && !timeZoneString.startsWith("GMT")) { // We don't want that GMT fallback... throw new IllegalArgumentException("Invalid time zone specification '" + timeZoneString + "'"); } return timeZone; } //--------------------------------------------------------------------- // Convenience methods for working with String arrays //--------------------------------------------------------------------- /** * Copy the given {@link Collection} into a {@code String} array. * <p>The {@code Collection} must contain {@code String} elements only. * @param collection the {@code Collection} to copy * (potentially {@code null} or empty) * @return the resulting {@code String} array */ public static String[] toStringArray(@Nullable Collection<String> collection) { return (!CollectionUtils.isEmpty(collection) ? collection.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY); } /** * Copy the given {@link Enumeration} into a {@code String} array. * <p>The {@code Enumeration} must contain {@code String} elements only. * @param enumeration the {@code Enumeration} to copy * (potentially {@code null} or empty) * @return the resulting {@code String} array */ public static String[] toStringArray(@Nullable Enumeration<String> enumeration) { return (enumeration != null ? toStringArray(Collections.list(enumeration)) : EMPTY_STRING_ARRAY); } /** * Append the given {@code String} to the given {@code String} array, * returning a new array consisting of the input array contents plus * the given {@code String}. * @param array the array to append to (can be {@code null}) * @param str the {@code String} to append * @return the new array (never {@code null}) */ public static String[] addStringToArray(@Nullable String[] array, String str) { if (ObjectUtils.isEmpty(array)) { return new String[] {str}; } String[] newArr = new String[array.length + 1]; System.arraycopy(array, 0, newArr, 0, array.length); newArr[array.length] = str; return newArr; } /** * Concatenate the given {@code String} arrays into one, * with overlapping array elements included twice. * <p>The order of elements in the original arrays is preserved. * @param array1 the first array (can be {@code null}) * @param array2 the second array (can be {@code null}) * @return the new array ({@code null} if both given arrays were {@code null}) */ @Nullable public static String[] concatenateStringArrays(@Nullable String[] array1, @Nullable String[] array2) { if (ObjectUtils.isEmpty(array1)) { return array2; } if (ObjectUtils.isEmpty(array2)) { return array1; } String[] newArr = new String[array1.length + array2.length]; System.arraycopy(array1, 0, newArr, 0, array1.length); System.arraycopy(array2, 0, newArr, array1.length, array2.length); return newArr; } /** * Sort the given {@code String} array if necessary. * @param array the original array (potentially empty) * @return the array in sorted form (never {@code null}) */ public static String[] sortStringArray(String[] array) { if (ObjectUtils.isEmpty(array)) { return array; } Arrays.sort(array); return array; } /** * Trim the elements of the given {@code String} array, calling * {@code String.trim()} on each non-null element. * @param array the original {@code String} array (potentially empty) * @return the resulting array (of the same size) with trimmed elements */ public static String[] trimArrayElements(String[] array) { if (ObjectUtils.isEmpty(array)) { return array; } String[] result = new String[array.length]; for (int i = 0; i < array.length; i++) { String element = array[i]; result[i] = (element != null ? element.trim() : null); } return result; } /** * Remove duplicate strings from the given array. * <p>As of 4.2, it preserves the original order, as it uses a {@link LinkedHashSet}. * @param array the {@code String} array (potentially empty) * @return an array without duplicates, in natural sort order */ public static String[] removeDuplicateStrings(String[] array) { if (ObjectUtils.isEmpty(array)) { return array; } Set<String> set = new LinkedHashSet<>(Arrays.asList(array)); return toStringArray(set); } /** * Split a {@code String} at the first occurrence of the delimiter. * Does not include the delimiter in the result. * @param toSplit the string to split (potentially {@code null} or empty) * @param delimiter to split the string up with (potentially {@code null} or empty) * @return a two element array with index 0 being before the delimiter, and * index 1 being after the delimiter (neither element includes the delimiter); * or {@code null} if the delimiter wasn't found in the given input {@code String} */ @Nullable public static String[] split(@Nullable String toSplit, @Nullable String delimiter) { if (!hasLength(toSplit) || !hasLength(delimiter)) { return null; } int offset = toSplit.indexOf(delimiter); if (offset < 0) { return null; } String beforeDelimiter = toSplit.substring(0, offset); String afterDelimiter = toSplit.substring(offset + delimiter.length()); return new String[] {beforeDelimiter, afterDelimiter}; } /** * Take an array of strings and split each element based on the given delimiter. * A {@code Properties} instance is then generated, with the left of the delimiter * providing the key, and the right of the delimiter providing the value. * <p>Will trim both the key and value before adding them to the {@code Properties}. * @param array the array to process * @param delimiter to split each element using (typically the equals symbol) * @return a {@code Properties} instance representing the array contents, * or {@code null} if the array to process was {@code null} or empty */ @Nullable public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) { return splitArrayElementsIntoProperties(array, delimiter, null); } /** * Take an array of strings and split each element based on the given delimiter. * A {@code Properties} instance is then generated, with the left of the * delimiter providing the key, and the right of the delimiter providing the value. * <p>Will trim both the key and value before adding them to the * {@code Properties} instance. * @param array the array to process * @param delimiter to split each element using (typically the equals symbol) * @param charsToDelete one or more characters to remove from each element * prior to attempting the split operation (typically the quotation mark * symbol), or {@code null} if no removal should occur * @return a {@code Properties} instance representing the array contents, * or {@code null} if the array to process was {@code null} or empty */ @Nullable public static Properties splitArrayElementsIntoProperties( String[] array, String delimiter, @Nullable String charsToDelete) { if (ObjectUtils.isEmpty(array)) { return null; } Properties result = new Properties(); for (String element : array) { if (charsToDelete != null) { element = deleteAny(element, charsToDelete); } String[] splittedElement = split(element, delimiter); if (splittedElement == null) { continue; } result.setProperty(splittedElement[0].trim(), splittedElement[1].trim()); } return result; } /** * Tokenize the given {@code String} into a {@code String} array via a * {@link StringTokenizer}. * <p>Trims tokens and omits empty tokens. * <p>The given {@code delimiters} string can consist of any number of * delimiter characters. Each of those characters can be used to separate * tokens. A delimiter is always a single character; for multi-character * delimiters, consider using {@link #delimitedListToStringArray}. * @param str the {@code String} to tokenize (potentially {@code null} or empty) * @param delimiters the delimiter characters, assembled as a {@code String} * (each of the characters is individually considered as a delimiter) * @return an array of the tokens * @see java.util.StringTokenizer * @see String#trim() * @see #delimitedListToStringArray */ public static String[] tokenizeToStringArray(@Nullable String str, String delimiters) { return tokenizeToStringArray(str, delimiters, true, true); } /** * Tokenize the given {@code String} into a {@code String} array via a * {@link StringTokenizer}. * <p>The given {@code delimiters} string can consist of any number of * delimiter characters. Each of those characters can be used to separate * tokens. A delimiter is always a single character; for multi-character * delimiters, consider using {@link #delimitedListToStringArray}. * @param str the {@code String} to tokenize (potentially {@code null} or empty) * @param delimiters the delimiter characters, assembled as a {@code String} * (each of the characters is individually considered as a delimiter) * @param trimTokens trim the tokens via {@link String#trim()} * @param ignoreEmptyTokens omit empty tokens from the result array * (only applies to tokens that are empty after trimming; StringTokenizer * will not consider subsequent delimiters as token in the first place). * @return an array of the tokens * @see java.util.StringTokenizer * @see String#trim() * @see #delimitedListToStringArray */ public static String[] tokenizeToStringArray( @Nullable String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if (str == null) { return EMPTY_STRING_ARRAY; } StringTokenizer st = new StringTokenizer(str, delimiters); List<String> tokens = new ArrayList<>(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (trimTokens) { token = token.trim(); } if (!ignoreEmptyTokens || token.length() > 0) { tokens.add(token); } } return toStringArray(tokens); } /** * Take a {@code String} that is a delimited list and convert it into a * {@code String} array. * <p>A single {@code delimiter} may consist of more than one character, * but it will still be considered as a single delimiter string, rather * than as a bunch of potential delimiter characters, in contrast to * {@link #tokenizeToStringArray}. * @param str the input {@code String} (potentially {@code null} or empty) * @param delimiter the delimiter between elements (this is a single delimiter, * rather than a bunch individual delimiter characters) * @return an array of the tokens in the list * @see #tokenizeToStringArray */ public static String[] delimitedListToStringArray(@Nullable String str, @Nullable String delimiter) { return delimitedListToStringArray(str, delimiter, null); } /** * Take a {@code String} that is a delimited list and convert it into * a {@code String} array. * <p>A single {@code delimiter} may consist of more than one character, * but it will still be considered as a single delimiter string, rather * than as a bunch of potential delimiter characters, in contrast to * {@link #tokenizeToStringArray}. * @param str the input {@code String} (potentially {@code null} or empty) * @param delimiter the delimiter between elements (this is a single delimiter, * rather than a bunch individual delimiter characters) * @param charsToDelete a set of characters to delete; useful for deleting unwanted * line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a {@code String} * @return an array of the tokens in the list * @see #tokenizeToStringArray */ public static String[] delimitedListToStringArray( @Nullable String str, @Nullable String delimiter, @Nullable String charsToDelete) { if (str == null) { return EMPTY_STRING_ARRAY; } if (delimiter == null) { return new String[] {str}; } List<String> result = new ArrayList<>(); if (delimiter.isEmpty()) { for (int i = 0; i < str.length(); i++) { result.add(deleteAny(str.substring(i, i + 1), charsToDelete)); } } else { int pos = 0; int delPos; while ((delPos = str.indexOf(delimiter, pos)) != -1) { result.add(deleteAny(str.substring(pos, delPos), charsToDelete)); pos = delPos + delimiter.length(); } if (str.length() > 0 && pos <= str.length()) { // Add rest of String, but not in case of empty input. result.add(deleteAny(str.substring(pos), charsToDelete)); } } return toStringArray(result); } /** * Convert a comma delimited list (e.g., a row from a CSV file) into an * array of strings. * @param str the input {@code String} (potentially {@code null} or empty) * @return an array of strings, or the empty array in case of empty input */ public static String[] commaDelimitedListToStringArray(@Nullable String str) { return delimitedListToStringArray(str, ","); } /** * Convert a comma delimited list (e.g., a row from a CSV file) into a set. * <p>Note that this will suppress duplicates, and as of 4.2, the elements in * the returned set will preserve the original order in a {@link LinkedHashSet}. * @param str the input {@code String} (potentially {@code null} or empty) * @return a set of {@code String} entries in the list * @see #removeDuplicateStrings(String[]) */ public static Set<String> commaDelimitedListToSet(@Nullable String str) { String[] tokens = commaDelimitedListToStringArray(str); return new LinkedHashSet<>(Arrays.asList(tokens)); } /** * Convert a {@link Collection} to a delimited {@code String} (e.g. CSV). * <p>Useful for {@code toString()} implementations. * @param coll the {@code Collection} to convert (potentially {@code null} or empty) * @param delim the delimiter to use (typically a ",") * @param prefix the {@code String} to start each element with * @param suffix the {@code String} to end each element with * @return the delimited {@code String} */ public static String collectionToDelimitedString( @Nullable Collection<?> coll, String delim, String prefix, String suffix) { if (CollectionUtils.isEmpty(coll)) { return ""; } int totalLength = coll.size() * (prefix.length() + suffix.length()) + (coll.size() - 1) * delim.length(); for (Object element : coll) { totalLength += String.valueOf(element).length(); } StringBuilder sb = new StringBuilder(totalLength); Iterator<?> it = coll.iterator(); while (it.hasNext()) { sb.append(prefix).append(it.next()).append(suffix); if (it.hasNext()) { sb.append(delim); } } return sb.toString(); } /** * Convert a {@code Collection} into a delimited {@code String} (e.g. CSV). * <p>Useful for {@code toString()} implementations. * @param coll the {@code Collection} to convert (potentially {@code null} or empty) * @param delim the delimiter to use (typically a ",") * @return the delimited {@code String} */ public static String collectionToDelimitedString(@Nullable Collection<?> coll, String delim) { return collectionToDelimitedString(coll, delim, "", ""); } /** * Convert a {@code Collection} into a delimited {@code String} (e.g., CSV). * <p>Useful for {@code toString()} implementations. * @param coll the {@code Collection} to convert (potentially {@code null} or empty) * @return the delimited {@code String} */ public static String collectionToCommaDelimitedString(@Nullable Collection<?> coll) { return collectionToDelimitedString(coll, ","); } /** * Convert a {@code String} array into a delimited {@code String} (e.g. CSV). * <p>Useful for {@code toString()} implementations. * @param arr the array to display (potentially {@code null} or empty) * @param delim the delimiter to use (typically a ",") * @return the delimited {@code String} */ public static String arrayToDelimitedString(@Nullable Object[] arr, String delim) { if (ObjectUtils.isEmpty(arr)) { return ""; } if (arr.length == 1) { return ObjectUtils.nullSafeToString(arr[0]); } StringJoiner sj = new StringJoiner(delim); for (Object elem : arr) { sj.add(String.valueOf(elem)); } return sj.toString(); } /** * Convert a {@code String} array into a comma delimited {@code String} * (i.e., CSV). * <p>Useful for {@code toString()} implementations. * @param arr the array to display (potentially {@code null} or empty) * @return the delimited {@code String} */ public static String arrayToCommaDelimitedString(@Nullable Object[] arr) { return arrayToDelimitedString(arr, ","); } /** * Truncate the supplied {@link CharSequence}. * <p>Delegates to {@link #truncate(CharSequence, int)}, supplying {@code 100} * as the threshold. * @param charSequence the {@code CharSequence} to truncate * @return a truncated string, or a string representation of the original * {@code CharSequence} if its length does not exceed the threshold * @since 5.3.27 */ public static String truncate(CharSequence charSequence) { return truncate(charSequence, DEFAULT_TRUNCATION_THRESHOLD); } /** * Truncate the supplied {@link CharSequence}. * <p>If the length of the {@code CharSequence} is greater than the threshold, * this method returns a {@linkplain CharSequence#subSequence(int, int) * subsequence} of the {@code CharSequence} (up to the threshold) appended * with the suffix {@code " (truncated)..."}. Otherwise, this method returns * {@code charSequence.toString()}. * @param charSequence the {@code CharSequence} to truncate * @param threshold the maximum length after which to truncate; must be a * positive number * @return a truncated string, or a string representation of the original * {@code CharSequence} if its length does not exceed the threshold * @since 5.3.27 */ public static String truncate(CharSequence charSequence, int threshold) { Assert.isTrue(threshold > 0, () -> "Truncation threshold must be a positive number: " + threshold); if (charSequence.length() > threshold) { return charSequence.subSequence(0, threshold) + TRUNCATION_SUFFIX; } return charSequence.toString(); } }
package com.training.advancedlab.repository; import com.training.advancedlab.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> { }
package com.fju.Hello; public class Student { String name = "mg"; int english; int math; int avg; public void print() { System.out.println(name + "\t" + english + "\t" + math + "\t" + avg); } } /*«Øºc¤l*/
package Panels.Blocks; import Frames.CharacterEditWindow; import Frames.PersonPanel; import Managers.TreeKeeper; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /* A visual representation of a person. For simplicity only shows the name and then gives a button to open the person editing window. Also has a delete button for removing a person from the project. */ public class PersonBlock extends JPanel implements PropertyChangeListener { private final TreeKeeper keeper; private JLabel name_label; public final PersonBlock self; public final int id; /* This assembles the panel using a gridbag layout. */ public PersonBlock(int id, TreeKeeper keeper, PersonPanel parent) { this.keeper = keeper; this.self = this; this.id = id; String name = keeper.getCharacterName(id); keeper.getPerson(id).addListener(this); setBackground(Color.WHITE); setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); setBorder(BorderFactory.createBevelBorder(1)); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 1; constraints.fill = GridBagConstraints.BOTH; constraints.gridwidth = 1; String actual = name.substring(0); if (name.length() > 20) { actual = name.substring(0, 17) + "... "; } if (name.length() < 20) { actual = name + " ".repeat(20 - name.length()); } name_label = new JLabel(actual); name_label.setPreferredSize(new Dimension(100, 30)); add(name_label, constraints); JButton button = new JButton("M"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JDialog dialog = new CharacterEditWindow(id, keeper); dialog.pack(); dialog.setVisible(true); } }); constraints.gridx = 1; constraints.anchor = GridBagConstraints.EAST; button.setPreferredSize(new Dimension(30, 30)); add(button, constraints); constraints.gridx = 2; button = new JButton("X"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { parent.remove_character(self); } }); button.setPreferredSize(new Dimension(30, 30)); add(button, constraints); } @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("name_change")) { name_label.setText((String) evt.getNewValue()); } } }
package com.zantong.mobilecttx.user.dto; /** * 退出实体 * @author Sandy * create at 16/6/8 下午11:48 */ public class LogoutDTO { private String usrid; //用户id public String getUsrid() { return usrid; } public void setUsrid(String usrid) { this.usrid = usrid; } }
package algorithms.kd; import lombok.Getter; import lombok.Setter; @Getter @Setter public class Entry<T> { private Point key; private T value; public Entry(Point key, T value) { this.key = key; this.value = value; } @Override public String toString() { return key.toString() + ":" + value; } }
package quiz.honeywell.com.fitnessapp.settings; import quiz.honeywell.com.fitnessapp.network.BaseRequest; /** * Created by ADMIN on 1/6/2018. */ public class SettingsRequest extends BaseRequest { }
package de.ing.mws.refapp.war.init; import de.ing.mws.refapp.common.LoadableModule; import java.util.HashMap; import java.util.Map; import java.util.ServiceLoader; public class ModuleLoader { private static ModuleLoader instance; private ServiceLoader<LoadableModule> serviceLoader; private ModuleLoader() { serviceLoader = ServiceLoader.load(LoadableModule.class); } public static ModuleLoader getInstance() { if (instance == null) { instance = new ModuleLoader(); } return instance; } public Map<String, LoadableModule> getModules() { Map<String, LoadableModule> modules = new HashMap<>(); serviceLoader.forEach(module -> { System.out.println("Registering module: " + module.getModuleName()); modules.put(module.getClass().getName(), module); }); return modules; } }
package com.shopxx.shopxxhr.service.impl; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; import com.querydsl.jpa.JPAExpressions; import com.shopxx.shopxxhr.entity.Employee; import com.shopxx.shopxxhr.entity.QEmployee; import com.shopxx.shopxxhr.entity.RespPageBean; import com.shopxx.shopxxhr.repository.EmployeeRepository; import com.shopxx.shopxxhr.service.EmployeeService; import org.apache.commons.collections4.IterableUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired EmployeeRepository employeeRepository; SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy"); SimpleDateFormat monthFormat = new SimpleDateFormat("MM"); DecimalFormat decimalFormat = new DecimalFormat("##.00"); @Override public RespPageBean getEmployeeByPage(Integer page, Integer size, Predicate predicate, Date[] beginDateScope) { QEmployee qEmployee = QEmployee.employee; RespPageBean respPageBean = new RespPageBean(); Pageable pageable = null; BooleanBuilder booleanBuilder = new BooleanBuilder(predicate); if (beginDateScope != null) { booleanBuilder.and(qEmployee.beginDate.after(beginDateScope[0]).and(qEmployee.beginDate.before(beginDateScope[1]))); } if (page != null && size != null) { pageable = PageRequest.of(page - 1, size); Page<Employee> all = employeeRepository.findAll(booleanBuilder, pageable); long totalSize = all.getTotalElements(); List<Employee> employees = all.getContent(); respPageBean.setData(employees); respPageBean.setTotal(totalSize); return respPageBean; } List<Employee> employeeList = IterableUtils.toList(employeeRepository.findAll(booleanBuilder)); respPageBean.setData(employeeList); respPageBean.setTotal(employeeList.size()); return respPageBean; } @Override @Transactional public Employee saveOrUpdateEmp(Employee employee) { Date beginContract = employee.getBeginContract(); Date endContract = employee.getEndContract(); double month = (Double.parseDouble(yearFormat.format(endContract)) - Double.parseDouble(yearFormat.format(beginContract))) * 12 + (Double.parseDouble(monthFormat.format(endContract)) - Double.parseDouble(monthFormat.format(beginContract))); employee.setContractTerm(Double.parseDouble(decimalFormat.format(month / 12))); return employeeRepository.save(employee); } @Override public Integer maxWorkID() { QEmployee qEmployee = QEmployee.employee; Employee employee = employeeRepository.findOne(qEmployee.workId.eq(JPAExpressions.select(qEmployee.workId.max()).from(qEmployee))).orElse(null); if (employee != null) { return employee.getWorkId(); } return 0; } @Override @Transactional public void deleteEmpById(Integer id) { employeeRepository.deleteById(id); } @Override @Transactional public void addEmps(List<Employee> employees) { employeeRepository.saveAll(employees); } }
package main.user; import main.entity.Id; import main.entity.implement.BlockId; import main.entity.implement.FileId; import main.repository.BlockRepo.Block; import main.repository.BlockRepo.BlockManager; import main.repository.BlockRepo.implement.BlockImpl; import main.repository.BlockRepo.implement.BlockManagerImpl; import main.repository.FileRepo.File; import main.repository.FileRepo.FileManager; import main.repository.FileRepo.implement.FileImpl; import main.repository.FileRepo.implement.FileManagerImpl; import main.utility.ErrorCode; import main.utility.FileUtil; import java.io.*; import java.util.ArrayList; import java.util.Map; import java.util.Scanner; /** * @param : * @author : Jiang Erling * @date : created in 2019/10/16 * @return : * @description : */ public class alpha_sys { private ArrayList<FileManager> fileManagers = new ArrayList<>(); static BlockManager bm1 = new BlockManagerImpl(); static BlockManager bm2 = new BlockManagerImpl(); static BlockManager bm3 = new BlockManagerImpl(); static FileManager fm1 = new FileManagerImpl(); static FileManager fm2 = new FileManagerImpl(); static FileManager fm3 = new FileManagerImpl(); FileUtil fileUtil = new FileUtil(); //直接读取文件中的内容 public void alpha_cat(String fileName){ byte[] answer = null; File file = FileManagerImpl.getFileByName(fileName); file.move(0,File.MOVE_HEAD); if(file.size() <Integer.MAX_VALUE) { try { System.out.print(new String(file.read((int)file.size()),"ascii")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { long size = file.size(), hasRead = 0; while (size - hasRead > Integer.MAX_VALUE) { try { System.out.print(new String(file.read((int) (size - hasRead)), "ascii")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } file.move(hasRead, File.MOVE_HEAD); hasRead += Integer.MAX_VALUE; } } System.out.print("\n"); } //直接从block的信息,读取block中的内容; //并且以十六进制的形式输出 //每16个十六进制的值输出一行 public void alpha_hex(String bmId,String bId){ byte[] answer = null; java.io.File blockContent = new java.io.File(bmId+"\\"+bId); answer = fileUtil.getContentsByFile(blockContent); String hex_str = bytesToHexString(answer); for (int i = 0; i < hex_str.length(); i+=32) { System.out.println(hex_str.substring(i,32+i)); } } //在文件的point处写入文件fileName中 //写入的内容为写在 控制台中的内容 public void alpha_write(String fileName,int point) { File file = FileManagerImpl.getFileByName(fileName); file.move(point, File.MOVE_HEAD); Scanner input = new Scanner(System.in); String in = ""; String temp = ""; while (!"end".equals(temp = input.nextLine())){ in += temp; } if(!in.isEmpty()) file.write(in.getBytes()); } //将文件from中的内容写入到文件to中 //这里是通过直接修改fileMeta中的内容实现的 public void alpha_copy(String from,String to){ File fromFile = FileManagerImpl.getFileByName(from); File toFile = FileManagerImpl.getFileByName(to); BufferedReader reader; FileOutputStream fos; try { java.io.File fromMetaFile = ((FileImpl)fromFile).getFileMeta(); java.io.File toMetaFile = ((FileImpl)toFile).getFileMeta(); reader = new BufferedReader(new FileReader(fromMetaFile)); fos = new FileOutputStream(toMetaFile); String content; while ((content = reader.readLine()) != null) fos.write((content+"\n").getBytes()); fos.close(); }catch (IOException e){ e.printStackTrace(); } } //工具方法 //将字节数组以十六进制的字符串形式输出 private String bytesToHexString(byte[] bytes){ StringBuilder result = new StringBuilder(""); int length = bytes.length; for (int i = 0; i < length; i++) { int hex = bytes[i]&0xFF; String hv = Integer.toHexString(hex); if(hv.length() < 2) result.append(0); result.append(hv); } return new String(result); } //将字节数组以字节的形式输出到控制台(目前的代码中没有使用到) private void printByteArray(byte[] array){ for (byte b : array) { System.out.print(b); } } public static void main(String[] args){ alpha_sys sys = new alpha_sys(); Id fId1 = new FileId("happy2"); Id fId2 = new FileId("no"); File f2 = fm2.newFile(fId2); File f1 = fm1.newFile(fId1); sys.alpha_write("happy2",0); sys.alpha_cat("happy2"); // sys.alpha_write("happy2",4); // f1.move(3,File.MOVE_TAIL); // f1.setSize(8); // f1.setSize(13); // sys.alpha_hex("bm-2","7.data"); // sys.alpha_cat("happy2"); // sys.alpha_copy("happy2","no"); // sys.alpha_cat("no"); // sys.alpha_write("no",8); } }
package com.example.demo.dao; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.web.bind.annotation.CrossOrigin; import com.example.demo.metier.Produit; @RepositoryRestResource @CrossOrigin(origins="http://localhost:4200") public interface ProduitRepository extends JpaRepository<Produit, Long> { @RestResource(path = "/byDesignation") public List<Produit> findByDesignationContains(@Param("mc") String des); @RestResource(path = "/byDesignationPage") public Page<Produit> findByDesignationContains(@Param("mc") String des,Pageable pageable); }
package com.developworks.jvmcode; /** * <p>Title: lookupsiwth</p> * <p>Description: 根据键值在跳转表中寻找匹配的分支然后进行跳转</p> * <p>Author: ouyp </p> * <p>Date: 2018-05-20 15:21</p> */ public class lookupsiwth { public void lookupswith(int i) { switch (i) { case -10 : break; case 0 : break; case 10 : break; default: } } } /** * public void lookupswith(int); * Code: * 0: iload_1 * 1: lookupswitch { // 3 * -10: 36 * 0: 39 * 10: 42 * default: 45 * } * 36: goto 45 * 39: goto 45 * 42: goto 45 * 45: return * } */
package Problem_17779; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { static int N; static int[][] arr; static int[][] data; static int[][] pos = new int[4][2]; static int min_value = Integer.MAX_VALUE; public static void answer() { // 가장많은 선거구 - 가장 적은 선거구 최솟값 for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) { for (int d1 = 1; d1 < N; d1++) { for (int d2 = 1; d2 < N; d2++) { if (CanMakeLine(x, y, d1, d2)) { int a = x - 1; int b = y - 1; pos[0][0] = a; pos[0][1] = b; pos[1][0] = a + d1; pos[1][1] = b - d1; pos[2][0] = a + d2; pos[2][1] = b + d2; pos[3][0] = a + d1 + d2; pos[3][1] = b - d1 + d2; calc(x, y, d1, d2); } } } } } } public static boolean CanMakeLine(int x, int y, int d1, int d2) { int a = x - 1; int b = y - 1; if (a + d1 >= N || b - d1 < 0) return false; if (a + d2 >= N || b + d2 >= N) return false; if (a + d1 + d2 >= N || b - d1 + d2 >= N) return false; if (a + d1 + d2 >= N || b + d2 - d1 < 0) return false; return true; } public static void calc(int x, int y, int d1, int d2) { int[] group = new int[6]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { data[i][j] = 5; } } int SubArea = 0; for (int i = 0; i < pos[1][0]; i++) { if (i >= pos[0][0]) SubArea++; for (int j = 0; j <= pos[0][1] - SubArea; j++) { data[i][j] = 1; } } int PlusArea = 0; for (int i = 0; i <= pos[2][0]; i++) { if (i > pos[0][0]) PlusArea++; for (int j = pos[0][1] + 1 + PlusArea; j < N; j++) { data[i][j] = 2; } } SubArea = 0; for (int i = N - 1; i >= pos[1][0]; i--) { if (i < pos[3][0]) SubArea++; for (int j = 0; j < pos[3][1] - SubArea; j++) { data[i][j] = 3; } } PlusArea = 0; for (int i = N - 1; i > pos[2][0]; i--) { if (i <= pos[3][0]) PlusArea++; for (int j = pos[3][1] + PlusArea; j < N; j++) { data[i][j] = 4; } } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { group[data[i][j]] = group[data[i][j]] + arr[i][j]; } } int maxIndex = 0; int minIndex = 1; for (int i = 1; i <= 5; i++) { if (group[maxIndex] < group[i]) { maxIndex = i; } if (group[minIndex] > group[i]) { minIndex = i; } } int value = group[maxIndex] - group[minIndex]; min_value = min_value > value ? value : min_value; } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); arr = new int[N][N]; data = new int[N][N]; String str; for (int i = 0; i < N; i++) { str = br.readLine(); for (int j = 0; j < N; j++) { arr[i][j] = Integer.parseInt(str.split(" ")[j]); } } answer(); System.out.println(min_value); } }
package com.share.dao; import org.hibernate.Session; import org.hibernate.Transaction; import com.share.bean.StudentHeader; import com.share.bean.StudentPlayer; import com.share.bean.SystemInfo; import com.share.bean.Teacher; import com.share.sessionFactory.SessionFactory; public class RegionDao { public boolean GroupRegion(StudentHeader header,StudentPlayer player1,StudentPlayer player2,Teacher teacher,SystemInfo systemInfo){ Session session = null; Transaction tr = null; try { session = SessionFactory.getSession(); tr = session.beginTransaction(); /**队长*/ session.save(header); /**成员一*/ player1.setStudentHeader(header); session.save(player1); /**成员二*/ player2.setStudentHeader(header); session.save(player2); /**指导教师*/ teacher.setStudentHeader(header); session.save(teacher); /**登录信息*/ systemInfo.setHeader(header); session.save(systemInfo); tr.commit(); return true; } catch (Exception e) { tr.rollback(); return false; }finally{ session.close(); } } public boolean GroupRegion(StudentHeader header, Teacher teacher,SystemInfo systemInfo,StudentPlayer... player){ Session session = null; Transaction tr = null; try { session = SessionFactory.getSession(); tr = session.beginTransaction(); /**队长*/ session.save(header); /**成员*/ for (StudentPlayer studentPlayer : player) { if(studentPlayer == null || studentPlayer.getName() == null || "".equals(studentPlayer.getName())){ continue; } studentPlayer.setStudentHeader(header); session.save(studentPlayer); } /**指导教师*/ teacher.setStudentHeader(header); session.save(teacher); /**登录信息*/ systemInfo.setHeader(header); session.save(systemInfo); tr.commit(); return true; } catch (Exception e) { tr.rollback(); return false; }finally{ session.close(); } } public boolean personRegion(StudentHeader header,Teacher teacher,SystemInfo systemInfo){ Session session = null; Transaction tr = null; try { session = SessionFactory.getSession(); tr = session.beginTransaction(); /**队长*/ session.save(header); /**指导教师*/ teacher.setStudentHeader(header); session.save(teacher); /**登录信息*/ systemInfo.setHeader(header); session.save(systemInfo); tr.commit(); return true; } catch (Exception e) { e.printStackTrace(); tr.rollback(); return false; }finally{ session.close(); } } public boolean personAdd(StudentHeader header,StudentPlayer studentPlayer){ Session session = null; Transaction tr = null; try { session = SessionFactory.getSession(); tr = session.beginTransaction(); if(studentPlayer == null || studentPlayer.getName() == null || "".equals(studentPlayer.getName())){ return false; } studentPlayer.setStudentHeader(header); session.save(studentPlayer); tr.commit(); return true; } catch (Exception e) { e.printStackTrace(); tr.rollback(); return false; }finally{ session.close(); } } public boolean update(StudentHeader header){ Session session = null; Transaction tr = null; try { session = SessionFactory.getSession(); tr = session.beginTransaction(); session.update(header); tr.commit(); return true; } catch (Exception e) { e.printStackTrace(); tr.rollback(); return false; }finally{ session.close(); } } public boolean update(StudentPlayer player){ Session session = null; Transaction tr = null; try { session = SessionFactory.getSession(); tr = session.beginTransaction(); session.merge(player); tr.commit(); return true; } catch (Exception e) { e.printStackTrace(); tr.rollback(); return false; }finally{ session.close(); } } public boolean update(Teacher teacher){ Session session = null; Transaction tr = null; try { session = SessionFactory.getSession(); tr = session.beginTransaction(); session.merge(teacher); tr.commit(); return true; } catch (Exception e) { e.printStackTrace(); tr.rollback(); return false; }finally{ session.close(); } } }
package com.lemo.cmx.shengchanxiaofei; /**产品 * Created by 罗选通 on 2017/9/14. */ public class Product { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; public Product(Integer id, String name) { this.id = id; this.name = name; } }
package com.example.android.beatmymovies; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by Admin on 04-01-2016. */ public class MovieGridAdapter extends ArrayAdapter<MovieForGrid> { public MovieGridAdapter(Context context, int resource, ArrayList<MovieForGrid> movieList) { super(context, resource, movieList); } @Override public View getView(int position, View convertView, ViewGroup parent) { MovieForGrid movieItem = getItem(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate( R.layout.movie_grid_item, parent, false); } ImageView poster = (ImageView)convertView.findViewById(R.id.movie_grid_item_image); //poster.setImageResource(R.mipmap.interstellar); //Log.v(LOG_TAG, "Poster path: " + movieItem.poster_path); String realPath = "http://image.tmdb.org/t/p/w185" + movieItem.poster_path; Picasso.with(getContext()).load(realPath).into(poster); return convertView; } }
package cn.com.finn.util; /** * * @author Finn Zhao * @version 2017年2月25日 */ public class DateUtils { private DateUtils() { } }
package main.java.model; import java.util.List; public class PieceDAO extends CsvDAO { private ModelManager modelManager; public PieceDAO(String id, ModelManager modelManager) { super ("res/pieces-" + id + ".csv"); this.modelManager = modelManager; } public Piece[] getPieces() { List<String[]> lines = this.getLinesFromFile(); Piece[] pieces = new Piece[lines.size()]; String[] values; int id; Face[] faces; for (int i = 0; i < lines.size(); i++) { faces = new Face[4]; values = lines.get(i); id = new Integer(values[1]); faces[0] = this.modelManager.getFace(new Integer(values[2])); faces[1] = this.modelManager.getFace(new Integer(values[3])); faces[2] = this.modelManager.getFace(new Integer(values[4])); faces[3] = this.modelManager.getFace(new Integer(values[5])); pieces[i] = new Piece(id, faces, 0, 0, 0); } return pieces; } }
package sort.linearsort; /** * Created by orca on 2018/12/20. * * 基数排序。 * 元:把数据分割成多位,对每一位做计数排序。 * */ public class RadixSort { public static void main(String args[]){ int[] a = {6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 12, 2}; sort(a); for (int i = 0; i < a.length; i++) { System.out.print(a[i]+" "); } } public static void sort(int[] o){ } }
package bangmyung; import java.util.ArrayList; import java.util.List; /* 데이터를 다루는 클래스는 독립시켜서 만드는 경향이 강하다. ( 별도의 클래스 ) A 는 데이터베이스와 관련된 기능 구현 B 는 웹 프로그래밍과 관련된 기능 구현 원래대로라면 A 끝나고 결과코드를 B 에 넘겨주고 B 는 그걸 받아서 일한다. 비효율적이다 : 동시에 얼마든지 일 할 수 있는데 .... BangMyungDAO - 방명록에 필요한 데이터 입출력 기능을 모아서 추상화 했다. :: add , findAll BangMyungDAO_KaraImpl : DB 연동을 비슷하게 흉내내준다. add 를 이용해서 레코드를 쌓고 , findAll 로 쌓인 레코드를 출력하고 ... B 는 BangMyungDAO_KaraImpl 을 이용하여 작업에 착수한다. A 는 BangMyungDAO_OracleImpl 을 구현한다 ( jdbc 코드 작성 ) 양쪽이 다 테스트가 끝나서 통합에 들어간다. BangMyungDAO_KaraImpl 을 BangMyungDAO_OracleImpl 바꾸기만 하면 된다. "데이터를 다루는 코드를 독립된 클래스로 만들되 그 작업들을 추상화 한 인터페이스를 기반으로 만드는 설계 기법을 DAO ( Data Access Object ) Pattern 이라고 한다." */ public class BangMyungDAO_KaraImpl implements BangMyungDAO { private static List<BangMyungVO> data = new ArrayList<BangMyungVO>(); private static int no = 0; @Override public void add(BangMyungVO vo) throws Exception { vo.setNo( no++ ); vo.setTheTime( "1999-12-12 12:00:00" ); data.add( vo ); } @Override public List<BangMyungVO> findAll() throws Exception { return data; } }
package com.example.demo; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component; @Component public class AppConfig { public MongoClient mongoClient() { return MongoClients.create("mongodb://localhost:27017"); } public @Bean MongoTemplate mongoTemplate() { return new MongoTemplate(mongoClient(), "libraryDB"); } }
/** * Package for Profession task. * * @author Goureev Ilya (mailto:ill-jah@yandex.ru) * @version 1 * @since 2017-04-22 */ package ru.job4j.task4;
package com.company; import lombok.Getter; import lombok.Setter; public class MobilePhone { private @Setter @Getter String m_brand; private @Setter @Getter String m_model; private @Setter @Getter int m_price; private @Setter @Getter double m_size; private @Setter @Getter String m_color; public MobilePhone(String m_brand, String m_model, int m_price, double m_size) { this.m_brand = m_brand; this.m_model = m_model; this.m_price = m_price; this.m_size = m_size; } public MobilePhone(String m_brand, String m_model, int m_price) { this(m_brand, m_model, m_price, 5.4); } public MobilePhone(String m_brand, String m_model) { this(m_brand, m_model, 54); } public MobilePhone () { this("ferrari", "testa rocca", 50, 5.4); } }
package au.gov.dva.digitize.batch; import java.util.Date; import javax.batch.api.AbstractBatchlet; import javax.batch.api.BatchProperty; import javax.inject.Inject; public class LoadMailData extends AbstractBatchlet { @Inject @BatchProperty(name = "runAt") Date runAt; /** * @see AbstractBatchlet#AbstractBatchlet() */ public LoadMailData() { super(); // TODO Auto-generated constructor stub } /** * @see AbstractBatchlet#process() */ public String process() { return null; } @Override public void stop() throws Exception { // TODO Auto-generated method stub super.stop(); } }
package artgallery; import java.util.List; import java.util.PriorityQueue; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Stack; import java.util.stream.Collectors; import artgallery.dataStructures.AVLTree; import artgallery.geometricalElements.Edge; import artgallery.geometricalElements.Hole; import artgallery.geometricalElements.Polygon; import artgallery.geometricalElements.Vertex; public final class GeometricAlgorithms { public ArrayList<Edge> trapezoidalEdges = new ArrayList<Edge>(); public GeometricAlgorithms() { } // Public method to trigger the triangulation of a complex polygon through // the method proposed by Seidel here: http://gamma.cs.unc.edu/SEIDEL/#FIG // (Input) Complex Polygon -> Trapezoidal Decomposition -> Monotone Polygons // -> (Output) Monotonic Triangulation. public ArrayList<Polygon> computeTriangulation(Polygon polygon) { // Create a deep copy of the polygon object to avoid modifying the // original gallery. Polygon polygonCopy = polygon.clone(); // Decompose the complex (copied) gallery polygon into trapezoids. ArrayList<Polygon> trapezoids = trapezoidalDecomposition(polygonCopy); // Obtain a set of monotone polygons out of said trapezoids. ArrayList<Polygon> monotonePolygons = monotonePolygonization(trapezoids); // Triangulate each of said monotone polygons. ArrayList<Polygon> triangulation = new ArrayList<Polygon>(); for (Polygon mp : monotonePolygons) { triangulation.addAll(triangulateMonotonePolygon(mp)); } // Finally return the list containing a triangle (Polygon) for each // triangle in the triangulation. return triangulation; } // Not fully implemented - for now simply setting the global list of // trapezoidal edges // for display debugging purposes. public ArrayList<Polygon> trapezoidalDecomposition(Polygon fullPolygon) { ArrayList<Polygon> trapezoids = new ArrayList<Polygon>(); ArrayList<Vertex> polygonVertices = fullPolygon.getVerticesAndHoles(); ArrayList<Edge> polygonEdges = fullPolygon.getEdgesAndHoles(); // ArrayList<Edge> trapezoidalEdges = new ArrayList<Edge>(); // Get all vertices and sort in descending Y-order. polygonVertices.sort((v1, v2) -> Double.compare(v2.getY(), v1.getY())); // Make a huge sweepline (edge) to test for intersections. for (Vertex vertex : polygonVertices) { Edge sweepLine = new Edge(new Vertex((int) (-Math.floor(fullPolygon.getMaxDistance())), vertex.getY()), new Vertex((int) (Math.ceil(fullPolygon.getMaxDistance())), vertex.getY())); // Check for edge intersections PriorityQueue<Vertex> intersectionsLeft = new PriorityQueue<Vertex>( (v1, v2) -> Double.compare(computeDistance(vertex, v1), computeDistance(vertex, v2))); PriorityQueue<Vertex> intersectionsRight = new PriorityQueue<Vertex>( (v1, v2) -> Double.compare(computeDistance(vertex, v1), computeDistance(vertex, v2))); for (Edge edge : polygonEdges) { Vertex intersection = getIntersectionPoint(sweepLine, edge); // When a different, valid intersection occurs, store the // intersection point if (intersection != null && !intersection.equals(vertex)) { if (intersection.getX() < vertex.getX()) { intersectionsLeft.add(intersection); } else if (intersection.getX() > vertex.getX()) { intersectionsRight.add(intersection); } } } Vertex current = new Vertex(vertex.getX(), vertex.getY()); // Consider only the two closest ones, as the trapezoidal if (intersectionsLeft.size() > 0) { // Make a non-final edge to test whether it would be valid Vertex intersection = intersectionsLeft.poll(); Edge tempEdge = new Edge(intersection, current); // Check if the middlepoint of said edge is within the polygon if (insidePolygon(tempEdge.getMidpoint(), fullPolygon)) { intersection = fullPolygon.getMatchingVertex(intersection) == null ? intersection : fullPolygon.getMatchingVertex(intersection); // Check if the midpoint is inside the polygon if (!vertex.isNeighbor(intersection)) { if (!trapezoidalEdges.contains(tempEdge)) { trapezoidalEdges.add(tempEdge); } } } } if (intersectionsRight.size() > 0) { // Make a non-final edge to test whether it would be valid Vertex intersection = intersectionsRight.poll(); Edge tempEdge = new Edge(current, intersection); // Check if the middlepoint of said edge is within the polygon if (insidePolygon(tempEdge.getMidpoint(), fullPolygon)) { intersection = fullPolygon.getMatchingVertex(intersection) == null ? intersection : fullPolygon.getMatchingVertex(intersection); // Check if the midpoint is inside the polygon if (!vertex.isNeighbor(intersection)) { if (!trapezoidalEdges.contains(tempEdge)) { trapezoidalEdges.add(tempEdge); } } } } } trapezoids.add(fullPolygon); return trapezoids; } // Not implemented - for now simply returning an empty list private ArrayList<Polygon> monotonePolygonization(ArrayList<Polygon> trapezoid) { ArrayList<Polygon> monotonePolygons = new ArrayList<Polygon>(); return monotonePolygons; } /* * Implementation of "TriangulateMonotonePolygon(polygon P as DCEL)". From * the course slides "3 - Art Gallery Triangulation", page 158. Input: * Y-Monotone polygon "p". Output: ArrayList of triangular polygons. */ private ArrayList<Polygon> triangulateMonotonePolygon(Polygon monotonePolygon) { ArrayList<Vertex> triangulationVertices = monotonePolygon.getVertices(); ArrayList<Edge> triangulationEdges = monotonePolygon.getEdges(); // Sorts the vertices on Y-Descending order. Collections.sort(triangulationVertices, (v1, v2) -> Double.compare(v2.getY(), v1.getY())); monotonePolygon.constructChains(); // Implementation translation from the book. Stack<Vertex> s = new Stack<Vertex>(); s.push(triangulationVertices.get(0)); s.push(triangulationVertices.get(1)); // Begin generating the internal edges for (int j = 2; j < triangulationVertices.size() - 1; ++j) { Vertex uj = triangulationVertices.get(j); // HERE IS WHERE THE CHAIN CHECK SHOULD BE ADDED <--- if (!s.peek().isNeighbor(uj)) { while (s.size() > 1) { Vertex v = s.pop(); triangulationEdges.add(new Edge(uj, v)); } s.pop(); s.push(triangulationVertices.get(j - 1)); s.push(uj); } else { Vertex v = s.pop(); // Must implement "sees" while (s.size() > 0) { v = s.pop(); triangulationEdges.add(new Edge(uj, v)); } s.push(v); s.push(uj); } } s.pop(); while (s.size() > 1) { Vertex v = s.pop(); triangulationEdges.add(new Edge(triangulationVertices.get(triangulationVertices.size() - 1), v)); } // Finally convert the loose list of edges into solid triangular // polygons and return. ArrayList<Polygon> triangles = constructTriangles(triangulationEdges); return triangles; } // Iterates through all of the loose edges in the list and attempts to put // together triangles by matching their vertices. Unfortunately O(n^3) as // all edges have to be checked in each of the levels required (triangles = // 3 levels). Perhaps could be improved through filtering, a better // algorithm, or better usage of references later on. private ArrayList<Polygon> constructTriangles(ArrayList<Edge> edges) { ArrayList<Polygon> triangles = new ArrayList<Polygon>(); for (Edge firstEdge : edges) { Vertex firstVertex = firstEdge.getStartVertex(); for (Edge secondEdge : edges) { if (!secondEdge.equals(firstEdge) && secondEdge.containsVertex(firstVertex)) { Vertex secondVertex = secondEdge.getOtherVertex(firstVertex); for (Edge thirdEdge : edges) { if (!thirdEdge.equals(secondEdge) && !thirdEdge.equals(firstEdge) && thirdEdge.containsVertex(secondVertex)) { if (thirdEdge.containsVertex(firstEdge.getOtherVertex(firstVertex))) { ArrayList<Edge> triangleEdges = new ArrayList<Edge>(); triangleEdges.add(firstEdge); triangleEdges.add(secondEdge); triangleEdges.add(thirdEdge); Polygon triangle = new Polygon(triangleEdges); if (!triangles.stream().anyMatch(t -> t.equals(triangle))) { System.out.println("Adding triangle: " + firstEdge.toString() + " - " + secondEdge.toString() + " - " + thirdEdge.toString()); triangles.add(triangle); } } } } } } } return triangles; } // Simple visibility algorithm based on testing each vertex around the viewpoint. // Not finished and somewhat buggy on edge-cases. public ArrayList<Polygon> computeVisibilityPolygon(Vertex viewPoint, Polygon p) { // Array of triangles comprising the visibility polygon ArrayList<Polygon> visiblePolygons = new ArrayList<Polygon>(); // Array containing all points in the scene but the view point, and // sorted on angle+proximity. ArrayList<Vertex> visibleVertices = p.getVerticesAndHoles(); visibleVertices.remove(viewPoint); visibleVertices.sort((v1, v2) -> compareAngleAndProximity(viewPoint, v1, v2)); // Extend sightlines (edges) from the viewpoint into each of the scene // vertices. ArrayList<Edge> sightLines = new ArrayList<Edge>(); for (Vertex w : visibleVertices) { double angle = computeCCWAngle(w, viewPoint); int endX = (int) (viewPoint.getX() + (Math.cos(Math.toRadians(angle)) * p.getMaxDistance())); int endY = (int) (viewPoint.getY() + (Math.sin(Math.toRadians(angle)) * p.getMaxDistance())); Vertex endOfLine = new Vertex(endX, endY); sightLines.add(new Edge(viewPoint, endOfLine)); System.out.println(w.getId() + " - " + angle); } ArrayList<Edge> obstacles = p.getEdgesAndHoles(); ArrayList<Vertex> visibilityPolygonVertices = new ArrayList<Vertex>(); for (Edge sightLine : sightLines) { PriorityQueue<Vertex> queue = new PriorityQueue<Vertex>( (v1, v2) -> Double.compare(computeDistance(viewPoint, v1), computeDistance(viewPoint, v2))); for (Edge obstacle : obstacles) { Vertex intersection = getIntersectionPoint(sightLine, obstacle); if (intersection != null) { visibilityPolygonVertices.add(intersection); } } } for (int i = 0; i < visibilityPolygonVertices.size() - 1; ++i) { ArrayList<Vertex> visTriangleVertices = new ArrayList<Vertex>(); visTriangleVertices.add(viewPoint); visTriangleVertices.add(visibilityPolygonVertices.get(i)); visTriangleVertices.add(visibilityPolygonVertices.get((i + 1))); Polygon visibleTriangle = new Polygon(visTriangleVertices); visiblePolygons.add(visibleTriangle); } return visiblePolygons; } /* * Implementation of "VisibleVertices(P, S)". From the book * "Computational Geometry: Algorithms and Applications - Third Edition" by * M. Berg , page 328. Input: Point P, set of polygonal obstacles S. Output: * The set of visible vertices from P. */ // Not currently working and the subroutine wasn't implemented. private ArrayList<Vertex> visibleVertices(Vertex v, Polygon p) { // 1) Sort the obstacle vertices according to the clockwise angle that // the half-line from p to each vertex makes with the positive x-axis. ArrayList<Vertex> obstacleVertices = p.getVerticesAndHoles(); obstacleVertices.sort((v1, v2) -> compareAngleAndProximity(v, v1, v2)); // Find the obstacle edges that are properly intersected by p parallel // to the x-axis and store them in a // balanced search tree in the order they intersect p. AVLTree<Edge> tree = new AVLTree<Edge>(); Edge sweepLine = new Edge(v, new Vertex((int) (Math.ceil(p.getMaxDistance())), v.getY())); ArrayList<Edge> intersectedEdges = new ArrayList<Edge>(); for (Edge obstacleEdge : p.getEdges()) { if (getIntersectionPoint(sweepLine, obstacleEdge) != null) { intersectedEdges.add(obstacleEdge); } } intersectedEdges.sort((e1, e2) -> compareIntersectionDistance(v, sweepLine, e1, e2)); for (Edge edge : intersectedEdges) { tree.insert(edge); } ArrayList<Vertex> visibleVertices = new ArrayList<Vertex>(); for (int i = 0; i < obstacleVertices.size(); ++i) { Vertex vi = obstacleVertices.get(i); if (isVisible(obstacleVertices, i)) { visibleVertices.add(vi); List<Edge> incidentEdges = (List<Edge>) intersectedEdges.stream().filter(e -> e.containsVertex(vi)) .collect(Collectors.toList()); for (Edge e : incidentEdges) { // Get the other vertex (not "vi") of the incident edge Vertex otherVertex = e.getOtherVertex(vi); // If the orientation if clockwise w.r.t. the sweepline, add // the edge to the tree. if (orientation(v, vi, otherVertex) == 1) { tree.insert(e); } // If the orientation if counter-clockwise w.r.t. the // sweepline, remove the edge to the tree. if (orientation(v, vi, otherVertex) == 2) { tree.remove(e); } } } } return visibleVertices; } /* * Implementation of "Visible(W)" subroutine. From the book * "Computational Geometry: Algorithms and Applications - Third Edition" by * M. Berg , page 329. Input: Point W. Output: The set of visible vertices * from P. */ private boolean isVisible(ArrayList<Vertex> w, int i) { //Not currently implemented as I switched to a simpler algorithm. return true; } // Computes simple euclidian distance between two vertices. private double computeDistance(Vertex v1, Vertex v2) { return Math.sqrt(Math.pow(v1.getY() - v2.getY(), 2) + Math.pow((v1.getX() - v2.getX()), 2)); } // Computes the CounterClockWise angle with respect to the X-Axis between two vertices. private double computeCCWAngle(Vertex v, Vertex reference) { double deltaX = v.getX() - reference.getX(); double deltaY = v.getY() - reference.getY(); double angle = Math.toDegrees(Math.atan2(deltaY, deltaX)); if (angle < 0) angle += 360; return angle; } // Comparison based on the angle // If the angles match (colinear) then prioritize the vertex closer to the // reference. public int compareAngleAndProximity(Vertex reference, Vertex v1, Vertex v2) { int result = Double.compare(computeCCWAngle(v1, reference), computeCCWAngle(v2, reference)); if (result == 0) { Double d1 = computeDistance(v1, reference); Double d2 = computeDistance(v2, reference); return d1 > d2 ? 1 : -1; } return result; } // Finds the intersection point between two edges (or null if there is none) //and returns it as a new Vertex. private Vertex getIntersectionPoint(Edge e1, Edge e2) { double x1 = e1.getStartVertex().getX(); double y1 = e1.getStartVertex().getY(); double x2 = e1.getEndVertex().getX(); double y2 = e1.getEndVertex().getY(); double x3 = e2.getStartVertex().getX(); double y3 = e2.getStartVertex().getY(); double x4 = e2.getEndVertex().getX(); double y4 = e2.getEndVertex().getY(); double ax = x2 - x1; double ay = y2 - y1; double bx = x4 - x3; double by = y4 - y3; double denominator = ax * by - ay * bx; if (denominator == 0) if (e1.getStartVertex().equals(e2.getStartVertex()) || e1.getStartVertex().equals(e2.getEndVertex())) { return e1.getStartVertex(); } else if (e1.getEndVertex().equals(e2.getStartVertex()) || e1.getEndVertex().equals(e2.getEndVertex())) { return e1.getEndVertex(); } else { return null; } double cx = x3 - x1; double cy = y3 - y1; double t = (cx * by - cy * bx) / (denominator); if (t < 0 || t > 1) return null; double u = (cx * ay - cy * ax) / (denominator); if (u < 0 || u > 1) return null; Vertex intersection = new Vertex((x1 + t * ax), (y1 + t * ay)); return intersection; } // Computes the distance between a vertex "v" and the intersection point of two edges "e1" and "e2". // Useful to discern what intersections in a sweep-line are closed to the origin point. private double getIntersectionDistance(Vertex v, Edge e1, Edge e2) { double x1, x2, x3, x4, y1, y2, y3, y4; x1 = e1.getStartVertex().getX(); y1 = e1.getStartVertex().getY(); x2 = e1.getEndVertex().getX(); y2 = e1.getEndVertex().getY(); x3 = e2.getStartVertex().getX(); y3 = e2.getStartVertex().getY(); x4 = e2.getEndVertex().getX(); y4 = e2.getEndVertex().getY(); double x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)); double y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)); return Math.sqrt(Math.pow(y - v.getY(), 2) + Math.pow((x - v.getX()), 2)); } // Given an origin point "v" and a segment "e" coming out of it, compare the distance from said point // to the intersection points of two other segments with said segment. private int compareIntersectionDistance(Vertex v, Edge e, Edge e1, Edge e2) { return Double.compare(getIntersectionDistance(v, e, e1), getIntersectionDistance(v, e, e2)); } // Computes a bounding box - Not currently used but might be useful at some point. private Polygon computeBoundingBox(Polygon p) { double minX, minY, maxX, maxY; minX = minY = Integer.MAX_VALUE; maxX = maxY = Integer.MIN_VALUE; for (Vertex v : p.getVertices()) { if (v.getX() > maxX) maxX = v.getX(); if (v.getX() < minX) minX = v.getX(); if (v.getY() > maxY) maxY = v.getY(); if (v.getY() < minY) minY = v.getY(); } ArrayList<Vertex> vertices = new ArrayList<Vertex>(); vertices.add(new Vertex(maxX, maxY)); vertices.add(new Vertex(maxX, minY)); vertices.add(new Vertex(minX, minY)); vertices.add(new Vertex(minX, maxY)); Polygon boundingBox = new Polygon(vertices); return boundingBox; } // Uses the Java AWT.Polygon class to check whether a point falls within a polygon. // First considers the bounding polygon, and subsequently checks for each hole polygon. private boolean insidePolygon(Vertex v, Polygon p) { java.awt.Polygon polygon = new java.awt.Polygon(); p.getVertices().forEach(i -> polygon.addPoint((int) (i.getX()), (int) (i.getY()))); // Construct the "hole" polygons. ArrayList<java.awt.Polygon> holes = new ArrayList<java.awt.Polygon>(); for (Hole h : p.getHoles()) { java.awt.Polygon hole = new java.awt.Polygon(); h.getVertices().forEach(i -> hole.addPoint((int) (i.getX()), (int) (i.getY()))); holes.add(hole); } boolean inHole = holes.stream().anyMatch(h -> h.contains(v.getX(), v.getY())); // If the point is inside the main polygon, and inside no hole, then return true. return polygon.contains((v.getX()), (v.getY())) && !inHole; } private boolean areColinear(Vertex v1, Vertex v2, Vertex v3) { double area = v1.getX() * (v2.getY() - v3.getY()) + v2.getX() * (v3.getY() - v1.getY()) + v3.getX() * (v1.getY() - v2.getY()); return (area == 0); } private int orientation(Vertex p, Vertex q, Vertex r) { double val = (q.getY() - p.getY()) * (r.getX() - q.getX()) - (q.getX() - p.getX()) * (r.getY() - q.getY()); if (val < 0) { return 0; // colinear } else { return (val > 0) ? 1 : 2; // clock or counterclock wise } } }
/* * Copyright 2019 The Kathra 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. * * Contributors: * * IRT SystemX (https://www.kathra.org/) * */ package {{package}}.dao; import com.arangodb.springframework.core.ArangoOperations; import {{coreModelPackage}}.{{clazz}}; import org.kathra.resourcemanager.resource.dao.AbstractResourceDao; import org.kathra.resourcemanager.resource.utils.LeanResourceDbUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.kathra.resourcemanager.resource.utils.EdgeUtils; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import fr.xebia.extras.selma.Selma; import java.util.stream.Stream; {{imports}} /** * Abtrasct dao service to manage {{clazz}} using {{clazz}}Db with ArangoRepository * * Auto-generated by {{generatorSignature}} * @author {{author}} */ public abstract class Abstract{{clazz}}Dao extends AbstractResourceDao<{{clazz}}, {{clazz}}Db, String> { {{fields}} public Abstract{{clazz}}Dao(@Autowired {{clazz}}Repository repository, @Autowired ArangoOperations operations){ super(repository, operations); } @PostConstruct public void initCollectionIfNotExist(){ if(repository.count() == 0) { try { operations.insert(new {{clazz}}Db("init")); repository.deleteById("init"); } catch (Exception e) { e.printStackTrace(); } } {{initCollectionIfNotExistOverride}} } @Override public void create({{clazz}} object, String author) throws Exception { super.create(object, author); updateReferences(object); } @Override public void update({{clazz}} object, String author) throws Exception { super.update(object, author); updateReferences(object); } @Override public void delete({{clazz}} object, String author) throws Exception { super.delete(object, author); updateReferences(object); } private void updateReferences({{clazz}} object) throws Exception { {{clazz}}Db resourceDb = this.convertResourceToResourceDb(object); {{updateOverride}} } {{clazz}}Mapper mapper = Selma.mapper({{clazz}}Mapper.class); public {{clazz}}Db convertResourceToResourceDb({{clazz}} object) { return mapper.as{{clazz}}Db(object); } public {{clazz}} convertResourceDbToResource({{clazz}}Db object) { LeanResourceDbUtils leanResourceDbUtils = new LeanResourceDbUtils(); return mapper.as{{clazz}}(({{clazz}}Db) leanResourceDbUtils.leanResourceDb(object)); } public Stream<{{clazz}}> convertResourceDbToResource(Stream<{{clazz}}Db> objectsStream){ LeanResourceDbUtils leanUtils = new LeanResourceDbUtils(); return objectsStream.map(i -> ({{clazz}}Db) leanUtils.leanResourceDb(i)) .collect(Collectors.toList()) .parallelStream() .map(i -> mapper.as{{clazz}}(i)); } }
package jkstudiogroup.template; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Texture; import jkstudiogroup.template.Objects.LoadCard; import jkstudiogroup.template.scenes.GameScene; public class PostScratch extends Game { public static AssetManager assetManager; public static float SW = 540; public static float SH = 960; @Override public void create () { assetManager = new AssetManager(); LoadAssets(); assetManager.finishLoading(); LoadCard.InitAssets(); setScreen(new GameScene(this)); } private void LoadAssets() { assetManager.load("badlogic.jpg", Texture.class); assetManager.load("Card.png", Texture.class); } }
package liu.lang.reflect.Method; import java.lang.reflect.Method; /**Method类的常用方法: * getDeclaringClass() * 返回该方法对象表示的方法所在类的Class对象 * @author LIU * */ public class About_getDeclaringClass { public void test() {} public static void main(String[] args) throws Exception { Method method = About_getDeclaringClass.class.getDeclaredMethod("test"); Class<?> declaringClass = method.getDeclaringClass(); // class liu.lang.reflect.Method.About_getDeclaringClass System.out.println(declaringClass); //返回该方法对象表示的方法所在类的Class对象 } }
package com.springcloud.demo.config.error; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class MyAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { AppResult appResult = AppResult.errorReturn(401, accessDeniedException.getMessage(),accessDeniedException.getLocalizedMessage()); MyAuthenticationEntryPoint.writer(request,response,appResult); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.scope; import java.lang.reflect.Executable; import java.util.function.Predicate; import javax.lang.model.element.Modifier; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.aot.generate.GeneratedMethod; import org.springframework.aot.generate.GenerationContext; import org.springframework.beans.factory.aot.BeanRegistrationAotContribution; import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor; import org.springframework.beans.factory.aot.BeanRegistrationCode; import org.springframework.beans.factory.aot.BeanRegistrationCodeFragments; import org.springframework.beans.factory.aot.BeanRegistrationCodeFragmentsDecorator; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.support.InstanceSupplier; import org.springframework.beans.factory.support.RegisteredBean; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.ResolvableType; import org.springframework.javapoet.ClassName; import org.springframework.javapoet.CodeBlock; import org.springframework.lang.Nullable; /** * {@link BeanRegistrationAotProcessor} for {@link ScopedProxyFactoryBean}. * * @author Stephane Nicoll * @author Phillip Webb * @since 6.0 */ class ScopedProxyBeanRegistrationAotProcessor implements BeanRegistrationAotProcessor { private static final Log logger = LogFactory.getLog(ScopedProxyBeanRegistrationAotProcessor.class); @Override public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) { Class<?> beanClass = registeredBean.getBeanClass(); if (beanClass.equals(ScopedProxyFactoryBean.class)) { String targetBeanName = getTargetBeanName(registeredBean.getMergedBeanDefinition()); BeanDefinition targetBeanDefinition = getTargetBeanDefinition(registeredBean.getBeanFactory(), targetBeanName); if (targetBeanDefinition == null) { logger.warn("Could not handle " + ScopedProxyFactoryBean.class.getSimpleName() + ": no target bean definition found with name " + targetBeanName); return null; } return BeanRegistrationAotContribution.withCustomCodeFragments(codeFragments -> new ScopedProxyBeanRegistrationCodeFragments(codeFragments, registeredBean, targetBeanName, targetBeanDefinition)); } return null; } @Nullable private String getTargetBeanName(BeanDefinition beanDefinition) { Object value = beanDefinition.getPropertyValues().get("targetBeanName"); return (value instanceof String targetBeanName ? targetBeanName : null); } @Nullable private BeanDefinition getTargetBeanDefinition(ConfigurableBeanFactory beanFactory, @Nullable String targetBeanName) { if (targetBeanName != null && beanFactory.containsBean(targetBeanName)) { return beanFactory.getMergedBeanDefinition(targetBeanName); } return null; } private static class ScopedProxyBeanRegistrationCodeFragments extends BeanRegistrationCodeFragmentsDecorator { private static final String REGISTERED_BEAN_PARAMETER_NAME = "registeredBean"; private final RegisteredBean registeredBean; private final String targetBeanName; private final BeanDefinition targetBeanDefinition; ScopedProxyBeanRegistrationCodeFragments(BeanRegistrationCodeFragments delegate, RegisteredBean registeredBean, String targetBeanName, BeanDefinition targetBeanDefinition) { super(delegate); this.registeredBean = registeredBean; this.targetBeanName = targetBeanName; this.targetBeanDefinition = targetBeanDefinition; } @Override public ClassName getTarget(RegisteredBean registeredBean, Executable constructorOrFactoryMethod) { return ClassName.get(this.targetBeanDefinition.getResolvableType().toClass()); } @Override public CodeBlock generateNewBeanDefinitionCode(GenerationContext generationContext, ResolvableType beanType, BeanRegistrationCode beanRegistrationCode) { return super.generateNewBeanDefinitionCode(generationContext, this.targetBeanDefinition.getResolvableType(), beanRegistrationCode); } @Override public CodeBlock generateSetBeanDefinitionPropertiesCode( GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode, RootBeanDefinition beanDefinition, Predicate<String> attributeFilter) { RootBeanDefinition processedBeanDefinition = new RootBeanDefinition( beanDefinition); processedBeanDefinition .setTargetType(this.targetBeanDefinition.getResolvableType()); processedBeanDefinition.getPropertyValues() .removePropertyValue("targetBeanName"); return super.generateSetBeanDefinitionPropertiesCode(generationContext, beanRegistrationCode, processedBeanDefinition, attributeFilter); } @Override public CodeBlock generateInstanceSupplierCode(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode, Executable constructorOrFactoryMethod, boolean allowDirectSupplierShortcut) { GeneratedMethod generatedMethod = beanRegistrationCode.getMethods() .add("getScopedProxyInstance", method -> { method.addJavadoc( "Create the scoped proxy bean instance for '$L'.", this.registeredBean.getBeanName()); method.addModifiers(Modifier.PRIVATE, Modifier.STATIC); method.returns(ScopedProxyFactoryBean.class); method.addParameter(RegisteredBean.class, REGISTERED_BEAN_PARAMETER_NAME); method.addStatement("$T factory = new $T()", ScopedProxyFactoryBean.class, ScopedProxyFactoryBean.class); method.addStatement("factory.setTargetBeanName($S)", this.targetBeanName); method.addStatement( "factory.setBeanFactory($L.getBeanFactory())", REGISTERED_BEAN_PARAMETER_NAME); method.addStatement("return factory"); }); return CodeBlock.of("$T.of($L)", InstanceSupplier.class, generatedMethod.toMethodReference().toCodeBlock()); } } }
package com.mf.controlacceso.dao; import java.util.List; public interface UsuarioDAO extends GenericDAO { }
package com.git.cloud.common.interceptor; import java.util.List; public class ModuleModel { private String clazz; // 业务模块的实现类路径 private String moduleName; // 模块名称 private String moduleCode; // 模块编码 private List<OperateModel> operateList; // 业务方法拦截的操作 public ModuleModel() { } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public String getModuleCode() { return moduleCode; } public void setModuleCode(String moduleCode) { this.moduleCode = moduleCode; } public List<OperateModel> getOperateList() { return operateList; } public void setOperateList(List<OperateModel> operateList) { this.operateList = operateList; } }
package com.tcl.multiuserlauncher; import android.app.ActivityManager; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.LauncherActivityInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.UserHandle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; public class AppsFragment extends Fragment { private final static String TAG = "AppsFragment"; private List<LauncherActivityInfo> apps; //private int id = 0; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_apps, null); return view; } public void setApps(List<LauncherActivityInfo> apps) { this.apps = apps; } //public void setUser(UserHandle user) { // id = UserManagerCompat.getIdentifier(user); //} @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ListView listView = getView().findViewById(R.id.list_apps); AppsAdapter adapter = new AppsAdapter(getActivity(), apps); listView.setAdapter(adapter); adapter.notifyDataSetChanged(); } public class AppsAdapter extends BaseAdapter { private Context context; private List<LauncherActivityInfo> list; private int iconDpi; //private List<ApplicationInfo> applications; //private PackageManager mPm; public AppsAdapter(Context context, List<LauncherActivityInfo> list) { this.context = context; this.list = list; ActivityManager activityManager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE); iconDpi = activityManager.getLauncherLargeIconDensity(); /* mPm = context.getPackageManager(); try { Method getInstalledApplications = PackageManager.class.getMethod("getInstalledApplicationsAsUser", int.class, int.class); applications = (List<ApplicationInfo>) getInstalledApplications.invoke(mPm, PackageManager.GET_META_DATA, id); } catch ( NoSuchMethodException e ) { e.printStackTrace(); Log.e(TAG, "NoSuchMethodException,e=" + e); } catch (IllegalAccessException e) { e.printStackTrace(); Log.e(TAG, "IllegalAccessException,e=" + e); } catch (InvocationTargetException e) { e.printStackTrace(); Log.e(TAG, "InvocationTargetException,e=" + e); } */ } @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder vh; if (view == null) { vh = new ViewHolder(); view = LayoutInflater.from(context).inflate(R.layout.item_app, null); vh.icon = view.findViewById(R.id.icon); //vh.user = view.findViewById(R.id.user); vh.title = view.findViewById(R.id.title); vh.packageName = view.findViewById(R.id.package_name); view.setTag(vh); } else { vh = (ViewHolder) view.getTag(); } LauncherActivityInfo info = list.get(i); //for(ApplicationInfo application : applications) { // application.loadIcon(mPm); // //if(info.getBadgedIcon()) //} vh.icon.setImageDrawable(info.getBadgedIcon(iconDpi)); //vh.user.setImageResource(R.drawable.ic_user); vh.title.setText(info.getLabel()); vh.packageName.setText(info.getName()); //vh.user.setVisibility(id > 0 ? View.VISIBLE : View.GONE); return view; } public class ViewHolder { ImageView icon; //ImageView user; TextView title; TextView packageName; } } }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.network.codec.protobuf; import com.google.protobuf.MessageLite; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; import xyz.noark.core.exception.DataException; import xyz.noark.core.exception.UnrealizedException; import xyz.noark.core.lang.ByteArray; import xyz.noark.core.lang.ByteArrayOutputStream; import xyz.noark.core.lang.ImmutableByteArray; import xyz.noark.core.network.NetworkPacket; import xyz.noark.core.network.NetworkProtocol; import xyz.noark.core.util.MethodUtils; import xyz.noark.core.util.UnsignedUtils; import xyz.noark.network.codec.AbstractPacketCodec; import xyz.noark.network.codec.ByteBufWrapper; import xyz.noark.network.codec.DefaultNetworkPacket; import java.io.IOException; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; /** * ProtobufV3版本的编码解码器. * * @author 小流氓[176543888@qq.com] * @since 3.1 */ public class ProtobufCodec extends AbstractPacketCodec { private static final ConcurrentHashMap<Class<?>, Method> CACHES = new ConcurrentHashMap<>(1024); @Override @SuppressWarnings("unchecked") public <T> T decodeProtocol(ByteArray bytes, Class<T> klass) { Method method = CACHES.computeIfAbsent(klass, key -> MethodUtils.getMethod(key, "parseFrom", byte[].class)); return (T) MethodUtils.invoke(null, method, bytes.array()); } @Override public ByteArray encodePacket(NetworkProtocol networkProtocol) { final int opcode = (Integer) networkProtocol.getOpcode(); if (opcode > Short.MAX_VALUE) { throw new UnrealizedException("illegal opcode=" + opcode + ", max=65535"); } MessageLite message; if (networkProtocol.getProtocol() instanceof MessageLite) { message = (MessageLite) networkProtocol.getProtocol(); } else if (networkProtocol.getProtocol() instanceof MessageLite.Builder) { message = ((MessageLite.Builder) networkProtocol.getProtocol()).build(); } else { throw new UnrealizedException("illegal data type:" + networkProtocol.getProtocol().getClass()); } ImmutableByteArray byteArray = new ImmutableByteArray(message.getSerializedSize() + 2); try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(byteArray)) { // 写入Opcode byteArrayOutputStream.writeShortLE(opcode); // 写入协议内容 try { message.writeTo(byteArrayOutputStream); } catch (IOException e) { throw new DataException("PB writeTo exception", e); } return byteArray; } } @Override public MessageToByteEncoder<?> lengthEncoder() { return new ProtobufLengthEncoder(); } @Override public ByteToMessageDecoder lengthDecoder() { return new ProtobufLengthDecoder(this); } @Override public NetworkPacket decodePacket(ByteBuf byteBuf) { DefaultNetworkPacket packet = new DefaultNetworkPacket(); packet.setLength(byteBuf.readableBytes()); packet.setIncode(UnsignedUtils.toUnsigned(byteBuf.readShortLE())); packet.setChecksum(UnsignedUtils.toUnsigned(byteBuf.readShortLE())); packet.setOpcode(UnsignedUtils.toUnsigned(byteBuf.readShortLE())); packet.setBytes(new ByteBufWrapper(byteBuf)); return packet; } }
package servlet; import java.io.IOException; import javax.servlet.ServletException; import domain.Building; import domain.Room; import service.RoomService; public class StaffEditRoomCommand extends FrontCommand { @Override public void process() throws ServletException, IOException { String roomIdString = request.getParameter("roomId"); String name = request.getParameter("name"); String type = request.getParameter("type"); String price = request.getParameter("price"); String buildingId = request.getParameter("buildingId"); Room room = new Room(); room.setRoomId(Integer.parseInt(roomIdString)); room.setName(name); room.setPrice(Float.parseFloat(price)); room.setType(type); Building building = new Building(); building.setBuildingId(Integer.parseInt(buildingId)); room.setBuilding(building); RoomService rs = new RoomService(); boolean result = rs.updateRoom(room, request.getSession().getId()); if (result) { request.setAttribute("successReason", "updated the room information."); forward("/jsp/staff/staffSuccess.jsp"); } else { request.setAttribute("errorMsg", "Something going wrong when update the room, please try again later."); forward("/jsp/staff/staffError.jsp"); } } }
package org.example.limitchecker.model.limit; import org.example.limitchecker.model.Order; import org.example.limitchecker.repository.CheckedOrdersStorage; public interface Limit { boolean check(Order order, CheckedOrdersStorage storage); }
package com.tinyworld.jsf.action; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import javax.faces.event.AjaxBehaviorEvent; import javax.faces.event.ValueChangeEvent; import org.springframework.stereotype.Component; import com.tinyworld.hibernate.model.Permission; import com.tinyworld.hibernate.model.User; import com.tinyworld.spring.service.PermissionService; import com.tinyworld.spring.service.UserService; @SuppressWarnings("serial") @ManagedBean(name="userAction", eager=true) @RequestScoped @Component public class UserAction /*extends ActionBase*/ implements Serializable{ @ManagedProperty("#{userService}") private UserService userService; @ManagedProperty("#{permissionService}") private PermissionService permissionService; /*public UserAction(){ userService = (UserService)getBean(UserService.class); permissionService = (PermissionService)getBean(PermissionService.class); }*/ @ManagedProperty(value="#{user}") private User user; private ArrayList<User> users; private ArrayList<Permission> permissions; private int permissionId; private boolean isUpdate = false; private String loginMessage; public String login(){ System.out.println(">>>>>> Login function -> runs"); try{ User u = userService.login(this.user.getUserName(), this.user.getPassword()); if(u != null) { return "usermanagement"; } else { System.out.println("~~~~~> Login false"); this.loginMessage = "Login false"; } } catch (Exception ex){ return null; } return "login"; } public void addNewUser(AjaxBehaviorEvent aBEven){ System.out.println(">>>>>> Add new user:"); //this.user.setPermission((new PermissionManagement()).getDefaultPermissionForUser()); this.user.setDateSingUp(new Date()); userService.insertUser(this.user); return; } public void selectPermission(AjaxBehaviorEvent aBEven){ System.out.println("\n\n\n\n\t>>>>>> Selected permisison is:" + this.permissionId); return; } public void changePermission(ValueChangeEvent vcE){ this.permissionId = Integer.parseInt(vcE.getNewValue().toString()); System.out.println("\n\n\n\n>>>>>>>> permission's id" + this.permissionId); } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public ArrayList<User> getUsers() { users = new ArrayList<User>(); users.addAll((this.permissionId == 0)?userService.getAll():userService.getUserByPermissionID(this.permissionId)); return users; } public void setUsers(ArrayList<User> users) { this.users = users; } public String getLoginMessage() { return loginMessage; } public void setLoginMessage(String loginMessage) { this.loginMessage = loginMessage; } public ArrayList<Permission> getPermissions() { this.permissions = new ArrayList<Permission>(permissionService.getAll()); return permissions; } public void setPermissions(ArrayList<Permission> permissions) { this.permissions = permissions; } public int getPermissionId() { return permissionId; } public void setPermissionId(int permissionId) { this.permissionId = permissionId; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public PermissionService getPermissionService() { return permissionService; } public void setPermissionService(PermissionService permissionService) { this.permissionService = permissionService; } }
package nor; import java.awt.*; import java.awt.event.*; import javax.swing.*; /******************************************************************************/ public class LookAndFeelMenu { //Megváltoztatja a témát. public static void createLookAndFeelMenuItem(JMenu jmenu, Component cmp) { //Megnézzük milyen témák vannak fent a gépen. final UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels(); //Létrehozzuk a szükséges elemeket. JRadioButtonMenuItem rbm[] = new JRadioButtonMenuItem[infos.length]; ButtonGroup bg = new ButtonGroup(); JMenu tmp = new JMenu("Change Look and Feel"); tmp.setMnemonic('C'); //Majd a témákat végig iterálva elmentjük ezeket és még beállítjuk //a listenereket is minden menüpotra. for(int i = 0; i < infos.length; i++) { rbm[i] = new JRadioButtonMenuItem(infos[i].getName()); rbm[i].setMnemonic(infos[i].getName().charAt(0)); tmp.add(rbm[i]); bg.add(rbm[i]); rbm[i].addActionListener(new LookAndFeelMenuListener(infos[i].getClassName(), cmp)); } rbm[0].setSelected(true); jmenu.add(tmp); } } /******************************************************************************/ class LookAndFeelMenuListener implements ActionListener { //Kell, hogy milyen témát választott és, hogy milyen componenshez akarja //hozzá adni. String classname; Component jf; /******************************************************************************/ //Konstruktor. public LookAndFeelMenuListener(String cln, Component jf) { this.jf = jf; classname = new String(cln); } /******************************************************************************/ //Figyelő. public void actionPerformed(ActionEvent ev) { try { UIManager.setLookAndFeel(classname); SwingUtilities.updateComponentTreeUI(jf); } catch (Exception e){ System.out.println(e); } } /******************************************************************************/ }
package com.soul.demo01; public class SaleTicketSynchronizedDemo01 { public static void main(String[] args) { Ticket ticket = new Ticket(); new Thread(() -> { for (int i = 0; i < 60; i++) { ticket.sale(); } }, "A").start(); new Thread(() -> { for (int i = 0; i < 60; i++) { ticket.sale(); } }, "B").start(); new Thread(() -> { for (int i = 0; i < 60; i++) { ticket.sale(); } }, "C").start(); } } class Ticket { static int count = 50; // Lock锁 public synchronized void sale() { if (count > 0) { System.out.println(Thread.currentThread().getName() + "卖出了" + (count--) + "票,剩余: " + count); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package de.dotwee.rgb.canteen.view.dialogs; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatDialog; import android.widget.Button; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import de.dotwee.rgb.canteen.R; import timber.log.Timber; /** * Created by lukas on 30.12.2016. */ public class MessageDialog extends AppCompatDialog implements MessageView { private static final String TAG = MessageDialog.class.getSimpleName(); private final AppCompatActivity appCompatActivity; @BindView(R.id.textViewTitle) TextView textViewTitle; @BindView(R.id.textViewMessage) TextView textViewMessage; @BindView(R.id.buttonExit) Button buttonExit; @BindView(R.id.buttonRefresh) Button buttonRefresh; public MessageDialog(@NonNull AppCompatActivity appCompatActivity) { this(appCompatActivity, DialogMessage.ISSUE_UNKNOWN); } private MessageDialog(@NonNull AppCompatActivity appCompatActivity, @NonNull DialogMessage dialogMessage) { super(appCompatActivity, R.style.AppTheme_Dialog_Closed); this.appCompatActivity = appCompatActivity; setContentView(R.layout.dialog_closed); ButterKnife.bind(this, getWindow().getDecorView()); setDialogMessage(dialogMessage); } @Override public void setDialogMessage(@NonNull DialogMessage dialogMessage) { Timber.i("setDialogMessage=%s", dialogMessage.name()); textViewTitle.setText(dialogMessage.getTitleId()); textViewMessage.setText(dialogMessage.getMessageId()); } @OnClick(R.id.buttonRefresh) @Override public void recreateDialog() { appCompatActivity.recreate(); } @OnClick(R.id.buttonExit) @Override public void recreateAffinity() { appCompatActivity.finishAffinity(); } }
package employeeScheduler.model; import org.jacop.constraints.In; /** * Simple class with information about specific work shift. */ public class Shift { private DayTime startTime; private DayTime endTime; private Integer minEmployeesNumber; private Integer maxEmployeesNumber; public Shift(DayTime startTime, DayTime endTime, Integer minEmployeesNumber, Integer maxEmployeesNumber) { this.startTime = startTime; this.endTime = endTime; this.minEmployeesNumber = minEmployeesNumber; this.maxEmployeesNumber = maxEmployeesNumber; } public DayTime getStartTime() { return startTime; } public void setStartTime(DayTime startTime) { this.startTime = startTime; } public DayTime getEndTime() { return endTime; } public void setEndTime(DayTime endTime) { this.endTime = endTime; } public Integer getMinEmployeesNumber() { return minEmployeesNumber; } public void setMinEmployeesNumber(Integer minEmployeesNumber) { this.minEmployeesNumber = minEmployeesNumber; } public Integer getMaxEmployeesNumber() { return maxEmployeesNumber; } public void setMaxEmployeesNumber(Integer maxEmployeesNumber) { this.maxEmployeesNumber = maxEmployeesNumber; } public Integer getShiftTime(){ return endTime.getDifferenceInMinutes(startTime); } public Boolean isNightShift(){ Integer startTimeMinutes = startTime.getHour()*60+startTime.getMinute(); Integer endTimeMinutes = endTime.getHour()*60+endTime.getMinute(); if (endTimeMinutes<startTimeMinutes){ return true; } return false; } }
package com.example.adimn.myapplication; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Handler; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Filter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Otp extends AppCompatActivity { Button bt_confirmed; EditText et_otp_verify; ImageView img_logo; String mobile,otp; TextView tv_resend; SharedPreferences.Editor editor; public static final int REQUEST_ID_MULTIPLE_PERMISSIONS=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_otp); tv_resend=(TextView)findViewById(R.id.tv_resend); img_logo=(ImageView)findViewById(R.id.img_logo); img_logo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Otp.this ,CreateAccount.class); startActivity(i); } }); givepermissionaccess(); SharedPreferences pref = getApplicationContext().getSharedPreferences("mobiles",0); editor = pref.edit(); mobile = pref.getString("mobile",""); System.out.println("the mobile is "+mobile); et_otp_verify = (EditText)findViewById(R.id.et_otp_verify); bt_confirmed = (Button) findViewById(R.id.bt_confirmed); bt_confirmed.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (et_otp_verify.getText().toString().equals("")){ Validations.MyAlertBox(Otp.this,"Please enter OTP"); et_otp_verify.requestFocus(); }else{ // new Otp.otp(et_otp_verify.getText().toString()).execute(); otp=et_otp_verify.getText().toString(); otp(); } } }); tv_resend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // new Otp.Resendotp(mobile).execute(); resend(); } }); // Bundle bundle } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equalsIgnoreCase("otp")) { String msg = intent.getStringExtra("message"); String number = msg.replaceAll("\\D+",""); et_otp_verify.setText(number); otp(); } } }; @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED ) { //resume tasks needing this permission givepermissionaccess(); // Toast.makeText(getBaseContext(), "Resume Task needing this permission", Toast.LENGTH_SHORT).show(); } else { //finish(); Toast.makeText(getBaseContext(), "you can not use this application without givivng access to ur location Thanks!!", Toast.LENGTH_SHORT).show(); } } public void givepermissionaccess() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS,Manifest.permission.READ_PHONE_STATE}, 0); } else { Toast.makeText(getBaseContext(), "All permissions granted.", Toast.LENGTH_SHORT).show(); // givepermissionaccess(); } } @Override public void onResume() { LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp")); super.onResume(); } @Override public void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); } public void resend() { RequestQueue queue = Volley.newRequestQueue(Otp.this); String url = "https://www.nandikrushi.in/services/resendotp.php"; final StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject object = new JSONObject(response); JSONObject jsonObject=object.getJSONObject("otpstatus"); String status=jsonObject.getString("status"); if (status.contains("1")){ /* String farmerid; farmerid = jsonObject.getString("farmerid"); SharedPreferences sharedPreferences = getSharedPreferences("LoginForm", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("moble", ph); editor.putString("password", pass); editor.putString("farmerID", farmerid); editor.commit();*/ android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("OTP Sent Successfully"); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { /* startActivity(new Intent(LoginForm.this, Dashboard.class)); dialogInterface.dismiss();*/ /*Intent login = new Intent(LoginForm.this, Dashboard.class); startActivity(login); finish();*/ } }).show(); }else { android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("Entered Mobile was NOT Registered"); builder.setPositiveButton(R.string.ok, null).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //mprocessingdialog.dismiss(); // Snackbar.make(linear, "Error in Connection", Snackbar.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("mobile", mobile); // params.put("password",pass); // Log.d("mobile", ph); // Log.d("password", pass); return params; } }; int socketTimeout = 60000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); stringRequest.setRetryPolicy(policy); queue.add(stringRequest); } /* private class Resendotp extends AsyncTask<String, String,JSONObject> { private ArrayList<NameValuePair> nameValuePairs; private JSONObject json; String mobile; public Resendotp(String mobile){ this.mobile= mobile; } protected void onPreExecute() { super.onPreExecute(); } @Override protected JSONObject doInBackground(String... strings) { nameValuePairs = new ArrayList<NameValuePair>(); //System.out.println("mobile is "+mobile); nameValuePairs.add(new BasicNameValuePair("mobile", mobile)); json = JSONParser.makeServiceCall("https://www.nandikrushi.in/services/resendotp.php", 2, nameValuePairs); // System.out.println("return json object is "+json); return json; } @Override protected void onPostExecute(JSONObject jsonObject) { String status = "1"; // super.onPostExecute(jsonObject); // Toast.makeText(getBaseContext(),jsonObject.toString(), Toast.LENGTH_SHORT).show(); try { JSONArray jsonArray = new JSONArray(); JSONObject data = jsonObject.getJSONObject("otpstatus"); status = data.getString("status"); if (status.equalsIgnoreCase("1")) { // Toast.makeText(getBaseContext(),data.toString(), Toast.LENGTH_SHORT).show(); *//* Log.d("otp",data.getString("otp").toString()); Log.d("mobile",data.getString("mobile").toString());*//* *//*Intent signup = new Intent(Otp.this, Filter.class); startActivity(signup); finish();*//* overridePendingTransition(R.anim.animation_enter, R.anim.animation_leave); android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("OTP Sent Successfully"); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //startActivity(new Intent(Otp.this, PersonalDetails.class)); dialogInterface.dismiss(); } }).show(); } else if (status.equalsIgnoreCase("-1")){ android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("Incorrect OTP"); builder.setPositiveButton(R.string.ok, null).show(); // Validations.MyAlertBox(Signup.this,"User already exist"); } else { android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("Enter Valid OTP"); builder.setPositiveButton(R.string.ok, null).show(); } }catch (JSONException e){ e.printStackTrace(); } } }*/ public void otp() { RequestQueue queue = Volley.newRequestQueue(Otp.this); String url = "https://www.nandikrushi.in/services/verifyotp.php"; final StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONArray jsonArray = new JSONArray(); JSONObject object = new JSONObject(response); JSONObject jsonObject=object.getJSONObject("otpstatus"); String status=jsonObject.getString("status"); if (status.equalsIgnoreCase("1")){ android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("The Mobile Number Verified Successfully"); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { /* startActivity(new Intent(LoginForm.this, Dashboard.class)); dialogInterface.dismiss();*/ startActivity(new Intent(Otp.this, PersonalDetails.class)); dialogInterface.dismiss(); /*Intent login = new Intent(LoginForm.this, Dashboard.class); startActivity(login); finish();*/ } }).show(); } else if (status.equalsIgnoreCase("-1")){ android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("Incorrect OTP"); builder.setPositiveButton(R.string.ok, null).show(); // Validations.MyAlertBox(Signup.this,"User already exist"); } else { android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("Enter Valid OTP"); builder.setPositiveButton(R.string.ok, null).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //mprocessingdialog.dismiss(); // Snackbar.make(linear, "Error in Connection", Snackbar.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); // params.put("mobile", mobile); params.put("otp",otp); params.put("mobile",mobile); // params.put("password",pass); // Log.d("mobile", ph); // Log.d("password", pass); return params; } }; int socketTimeout = 60000; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); stringRequest.setRetryPolicy(policy); queue.add(stringRequest); } /* private class otp extends AsyncTask<String, String,JSONObject> { private ArrayList<NameValuePair> nameValuePairs; private JSONObject json; String otp; public otp(String otp){ this.otp= otp; } protected void onPreExecute() { super.onPreExecute(); } @Override protected JSONObject doInBackground(String... strings) { nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("otp", otp)); nameValuePairs.add(new BasicNameValuePair("mobile", mobile)); json = JSONParser.makeServiceCall("https://www.nandikrushi.in/services/verifyotp.php", 2, nameValuePairs); return json; } @Override protected void onPostExecute(JSONObject jsonObject) { String status = "1"; // super.onPostExecute(jsonObject); // Toast.makeText(getBaseContext(),jsonObject.toString(), Toast.LENGTH_SHORT).show(); try { JSONArray jsonArray = new JSONArray(); JSONObject data = jsonObject.getJSONObject("otpstatus"); status = data.getString("status"); if (status.equalsIgnoreCase("1")) { // Toast.makeText(getBaseContext(),data.toString(), Toast.LENGTH_SHORT).show(); *//* Log.d("otp",data.getString("otp").toString()); Log.d("mobile",data.getString("mobile").toString());*//* *//*Intent signup = new Intent(Otp.this, Filter.class); startActivity(signup); finish();*//* overridePendingTransition(R.anim.animation_enter, R.anim.animation_leave); android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("OTP Verified Successfully"); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(new Intent(Otp.this, PersonalDetails.class)); dialogInterface.dismiss(); } }).show(); } else if (status.equalsIgnoreCase("-1")){ android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("Incorrect OTP"); builder.setPositiveButton(R.string.ok, null).show(); // Validations.MyAlertBox(Signup.this,"User already exist"); } else { android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Otp.this); builder.setTitle("Nandi Krushi"); builder.setMessage("Enter Valid OTP"); builder.setPositiveButton(R.string.ok, null).show(); } }catch (JSONException e){ e.printStackTrace(); } } }*/ //******* HIDING KEYBOARD ********** @Override public boolean dispatchTouchEvent(MotionEvent ev) { View v = getCurrentFocus(); if (v != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && v instanceof EditText && !v.getClass().getName().startsWith("android.webkit.")) { int scrcoords[] = new int[2]; v.getLocationOnScreen(scrcoords); float x = ev.getRawX() + v.getLeft() - scrcoords[0]; float y = ev.getRawY() + v.getTop() - scrcoords[1]; if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) Validations.hideKeyboard(this); } return super.dispatchTouchEvent(ev); } boolean doubleBackToExitPressedOnce = false; @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce=false; } }, 2000); } }
package com.test; public class SolutionB { public static final int[] ARRAY = {5, 8, 4, 12, 32, -12, -43, 0, 9, 43, -23, 8, -4, 43, 5}; /** * .堆排序 */ public int[] sortHeap() { int[] temp = ARRAY.clone(); buildMaxHeap(temp); for (int i = temp.length - 1; i >= 1; i--) { exchangeElements(temp, 0, i); maxHeap(temp, i, 0); } return temp; } /** 创建 堆 */ private void buildMaxHeap(int[] array) { if (array == null || array.length <= 1) { return; } int half = array.length / 2; for (int i = half; i >= 0; i--) { maxHeap(array, array.length, i); } } /** maxHeap调整堆 */ private void maxHeap(int[] array, int heapSize, int index) { int left = index * 2 + 1; int right = index * 2 + 2; int largest = index; if (left < heapSize && array[left] > array[index]) { largest = left; } if (right < heapSize && array[right] > array[largest]) { largest = right; } if (index != largest) { exchangeElements(array, index, largest); maxHeap(array, heapSize, largest); } } /** 选择项,并与第0个元素交换 */ private void exchangeElements(int[] array, int index1, int index2) { int temp = array[index1]; array[index1] = array[index2]; array[index2] = temp; } }
/** * */ package com.android.aid; import android.database.ContentObserver; import android.os.Handler; import android.util.Log; /** * @author wangpeifeng * */ public class GUIContentObserver extends ContentObserver{ public GUIContentObserver(Handler handler) { super(handler); // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see android.database.ContentObserver#onChange(boolean) */ @Override public void onChange(boolean selfChange) { // TODO Auto-generated method stub //Log.i("test", "onChange!"); super.onChange(selfChange); } }
package com.weili.dao; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.shove.data.DataException; import com.shove.data.DataSet; import com.shove.util.BeanMapUtils; import com.weili.database.Dao; public class AttributeDao { public long addAttribute(Connection conn,String name,Long parentId,Integer sortIndex,Integer status,String productIds) throws SQLException{ Dao.Tables.t_attribute attribute = new Dao().new Tables().new t_attribute(); attribute._name.setValue(name); attribute.parentId.setValue(parentId); attribute.sortIndex.setValue(sortIndex); attribute.status.setValue(status); attribute.addTime.setValue(new Date()); attribute.productIds.setValue(productIds); return attribute.insert(conn); } public long updateAttribute(Connection conn,long id,String name,Long parentId,Integer sortIndex,Integer status,String productIds) throws SQLException{ Dao.Tables.t_attribute attribute = new Dao().new Tables().new t_attribute(); if(StringUtils.isNotBlank(name)){ attribute._name.setValue(name); } if(StringUtils.isNotBlank(productIds)){ attribute.productIds.setValue(productIds); } if(parentId != null){ attribute.parentId.setValue(parentId); } if(sortIndex != null&&sortIndex > 0){ attribute.sortIndex.setValue(sortIndex); } if(status != null&&status > 0){ attribute.status.setValue(status); } return attribute.update(conn, " id = "+id); } public long deleteAttribute(Connection conn,String ids) throws SQLException{ Dao.Tables.t_attribute attribute = new Dao().new Tables().new t_attribute(); return attribute.delete(conn, " id in("+ids+") "); } public Map<String,String> queryAttributeById(Connection conn,long id) throws SQLException, DataException{ Dao.Tables.t_attribute attribute = new Dao().new Tables().new t_attribute(); DataSet ds = attribute.open(conn, " ", " id = "+id, "", -1, -1); return BeanMapUtils.dataSetToMap(ds); } public List<Map<String, Object>> queryAttributeAll(Connection conn,String fieldList,String condition,String order)throws SQLException, DataException { Dao.Tables.t_attribute attribute = new Dao().new Tables().new t_attribute(); DataSet ds = attribute.open(conn, fieldList, condition,order, -1, -1); ds.tables.get(0).rows.genRowsMap(); return ds.tables.get(0).rows.rowsMap; } public List<Map<String,Object>> queryAttributeChild(Connection conn,String materialsIds,Integer status) throws Exception{ Dao.Views.v_t_attribute_materials attribute = new Dao().new Views().new v_t_attribute_materials(); StringBuffer condition = new StringBuffer(); condition.append("1=1"); if(StringUtils.isNotBlank(materialsIds)){ condition.append(" and materialsId in("+materialsIds+")"); } if(status != null&&status > 0){ condition.append(" and childStatus = "+status); } DataSet ds = attribute.open(conn, "materialsId,attributeId,childName,parentId", condition.toString(), "childIndex asc", -1, -1); ds.tables.get(0).rows.genRowsMap(); return ds.tables.get(0).rows.rowsMap; } public List<Map<String,Object>> queryAttributeParent(Connection conn,String materialsIds,Integer status) throws Exception{ Dao.Views.v_t_attribute_materials attribute = new Dao().new Views().new v_t_attribute_materials(); StringBuffer condition = new StringBuffer(); condition.append("1=1"); if(StringUtils.isNotBlank(materialsIds)){ condition.append(" and materialsId in("+materialsIds+")"); } if(status != null&&status > 0){ condition.append(" and parentStatus = "+status); } DataSet ds = attribute.open(conn, "materialsId,apId,parentName", condition.toString(), "parentIndex asc", -1, -1); ds.tables.get(0).rows.genRowsMap(); return ds.tables.get(0).rows.rowsMap; } public List<Map<String,Object>> queryMaterialsAttributes(Connection conn,String ids) throws SQLException, DataException{ Dao.Tables.t_attribute attribute = new Dao().new Tables().new t_attribute(); DataSet ds = attribute.open(conn, " ", " id not in("+ids+")", "sortIndex asc", -1, -1); ds.tables.get(0).rows.genRowsMap(); return ds.tables.get(0).rows.rowsMap; } public List<Map<String,Object>> queryAttributes(Connection conn,String ids) throws SQLException, DataException{ Dao.Tables.t_attribute attribute = new Dao().new Tables().new t_attribute(); DataSet ds = attribute.open(conn, " ", " id in("+ids+")", "sortIndex asc", -1, -1); ds.tables.get(0).rows.genRowsMap(); return ds.tables.get(0).rows.rowsMap; } public List<Map<String,Object>> queryAttributesByParentId(Connection conn,String ids) throws SQLException, DataException{ Dao.Tables.t_attribute attribute = new Dao().new Tables().new t_attribute(); DataSet ds = attribute.open(conn, " ", " (id in("+ids+")) or (parentId in ("+ids+"))", "", -1, -1); ds.tables.get(0).rows.genRowsMap(); return ds.tables.get(0).rows.rowsMap; } }
package com.codepath.instagram.networking; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import com.codepath.instagram.core.MainApplication; import com.codepath.instagram.helpers.Utils; import com.codepath.instagram.models.InstagramPost; import com.codepath.instagram.models.InstagramPosts; import com.codepath.instagram.persistence.InstagramClientDatabase; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.loopj.android.http.SyncHttpClient; import org.json.JSONObject; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; /** * Created by araiff on 11/3/15. */ public class NetworkService extends IntentService { private AsyncHttpClient aClient = new SyncHttpClient(); public static final String ACTION = "com.codepath.instagram.networking.NetworkService"; public NetworkService() { super("NetworkService"); } /** * Creates an IntentService. Invoked by your subclass's constructor. * * @param name Used to name the worker thread, important only for debugging. */ public NetworkService(String name) { super(name); } @Override protected void onHandleIntent(Intent intent) { final InstagramPosts posts = new InstagramPosts(); final Intent in = new Intent(ACTION); final InstagramClientDatabase database = InstagramClientDatabase.getInstance(this); if (!MainApplication.getRestClient().isNetworkAvailable(getApplicationContext())) { posts.posts = database.getAllInstagramPosts(); in.putExtra("posts", posts); LocalBroadcastManager.getInstance(NetworkService.this).sendBroadcast(in); } else { SyncHttpClient syncClient = new SyncHttpClient(); InstagramClient client = MainApplication.getRestClient(); RequestParams params = new RequestParams("access_token", client.checkAccessToken().getToken()); syncClient.get(this, InstagramClient.REST_URL + InstagramClient.SELF_FEED, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) { ArrayList<InstagramPost> newPosts = (ArrayList<InstagramPost>) Utils.decodePostsFromJsonResponse(responseBody); posts.posts = newPosts; database.emptyAllTables(); database.addInstagramPosts(newPosts); in.putExtra("posts", posts); LocalBroadcastManager.getInstance(NetworkService.this).sendBroadcast(in); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); } }); } } }
package adtpackage; /** * * @author Zbynda */ public enum ReturnCode { SUCCESS("The addition was successful."), FAILURE("The addition was unsuccessful."), SKIP("The addition was skipped."), OVERFLOW("The container overflowed during addition process."), UNDEFINED("The addition status is undefined."); private String description; private ReturnCode(String description) { this.description = description; } public String getDescription() { return description; } }
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; public class Login { WebDriver driver; WebElement username; WebElement password; WebElement loginButton; public Login(WebDriver driver) throws InterruptedException { this.driver = driver; String url = "http://hrm.seleniumminutes.com//symfony/web/index.php/auth/login"; driver.get(url); Thread.sleep(30); username = driver.findElement(By.id("txtUsername")); password = driver.findElement(By.id("txtPassword")); loginButton = driver.findElement(By.id("btnLogin")); } public void loginAsAdmin() { username.sendKeys("admin"); password.sendKeys("password"); loginButton.click(); new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.id("welcome"))); Assert.assertEquals("Welcome Admin", driver.findElement(By.id("welcome")).getText()); } }
package asia.wavelet.bigledger.core.domain; import javax.persistence.Entity; import javax.persistence.Table; import org.openkoala.koala.commons.domain.KoalaAbstractEntity; @Entity @Table(name = "PUBLISHERS") public class Publisher extends KoalaAbstractEntity { /** * */ private static final long serialVersionUID = -8223737935434243709L; private String addrress; @Override public String[] businessKeys() { return null; } public String getAddrress() { return addrress; } public void setAddrress(String addrress) { this.addrress = addrress; } }
package com.gsccs.sme.api.service; import java.util.List; import com.gsccs.sme.api.domain.site.Banner; /** * 首页Banner * @author ZhangTao * */ public interface BannerServiceI { /** * 热点列表 * @param banner * @param page * @param pagesize * @return */ public List<Banner> find(Banner banner,Integer page,Integer pagesize); }
package com.nsi.clonebin.util; import com.nsi.clonebin.model.enums.PasteExpiringEnum; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class DateTimeUtil { public static String formatLocalDateTime(LocalDateTime dateTime) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("LLL dd, yyyy"); return dateTime.toLocalDate().format(formatter); } public static String getExpiresAtTime(LocalDateTime expiresAt) { if (expiresAt == null) { return "Never"; } LocalDateTime now = LocalDateTime.now(); long diff; diff = ChronoUnit.YEARS.between(now, expiresAt); if (diff > 0) { return formatPeriod(diff, "Year"); } diff = ChronoUnit.MONTHS.between(now, expiresAt); if (diff > 0) { return formatPeriod(diff, "Month"); } diff = ChronoUnit.DAYS.between(now, expiresAt); if (diff > 0) { return formatPeriod(diff, "Day"); } diff = ChronoUnit.HOURS.between(now, expiresAt); if (diff > 0) { return formatPeriod(diff, "Hour"); } diff = ChronoUnit.MINUTES.between(now, expiresAt); if (diff > 0) { return formatPeriod(diff, "Minute"); } diff = ChronoUnit.SECONDS.between(now, expiresAt); if (diff > 0) { return formatPeriod(diff, "Second"); } return "Never"; } public static LocalDateTime calucateExpiresAt(PasteExpiringEnum pasteExpiringEnum) { LocalDateTime now = LocalDateTime.now(); LocalDateTime expiresAt = null; if (pasteExpiringEnum != PasteExpiringEnum.NEVER) { expiresAt = now.plus(pasteExpiringEnum.getValue(), pasteExpiringEnum.getChronoUnit()); } return expiresAt; } private static String formatPeriod(long diff, String period) { if (diff <= 1) { return diff + " " + period; } else { return diff + " " + period + "s"; } } }
/* Copyright (C) 2013-2014, Securifera, Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Securifera, Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ Pwnbrew is provided under the 3-clause BSD license above. The copyright on this package is held by Securifera, Inc */ /* * LogHandler.java * * Created on Nov 12, 2013, 9:12:31 PM */ package pwnbrew.log; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.*; /** * */ @SuppressWarnings("ucd") public class LogHandler extends FileHandler { private static final int DEFAULT_SizeLimit_Bytes = 300000; //300kB private static final int DEFAULT_FileLimit = 10; private static final String FORMAT_FileNameDate = "yyyy-MM-dd"; private static final String FORMAT_FileNameSuffix = "-%g.txt"; private LogFormatter theFormatter = null; private boolean publishToStdOut = false; // ========================================================================== /** * Constructor * */ LogHandler( File directory ) throws IOException, SecurityException { super( createLogFileNamePattern( directory ), DEFAULT_SizeLimit_Bytes, DEFAULT_FileLimit, true ); } // ========================================================================== /** * Creates the pattern for naming the log files. * * @param directory the directory in which the log files will be placed * * @return the pattern for naming the log files * * @throws IOException if the given {@code File} does not exist or is not a directory * @throws NullPointerException if the argument is null */ private static String createLogFileNamePattern( File directory ) throws IOException { if( directory.exists() == false ) throw new IOException( new StringBuilder( "The directory \"" ) .append( directory.getPath() ) .append( "\" does not exist." ).toString() ); if( directory.isDirectory() == false ) throw new IOException( new StringBuilder( "The file \"" ) .append( directory.getPath() ) .append( "\" is not a directory." ).toString() ); StringBuilder rtnBuilder = new StringBuilder(); rtnBuilder.append( directory.getPath() ) .append( File.separator ) .append( ( new SimpleDateFormat( FORMAT_FileNameDate ) ).format( new Date() ) ) .append( FORMAT_FileNameSuffix ); //NOTE: The "%g" in the log filename pattern marks the position of the generation // number. The file to which the new logs are written always has a generation // number of zero. Each time the current log file reaches its size limit, this // number will be incremented to 1 and a new file is created with a generation // number of zero. The generation number of all previously existing log files // is also incremented. // For example, when the first log file reaches the limit, its generation number // is incremented to 1 and a new file, with a generation number of zero, is created. // When the new file reaches the limit, 1 is incremented to 2, 0 is incremented // to 1, and a new file (again with a generation number of zero) is created. return rtnBuilder.toString(); }/* END createLogFileNamePattern( String ) */ // ========================================================================== /** * Sets the {@link LogFormatter}. * <p> * If the argument is null this method does nothing. * * @param formatter the {@code LogFormatter} */ public synchronized void setLogFormatter( LogFormatter formatter ) { if( formatter == null ) return; //Do nothing theFormatter = formatter; super.setFormatter( formatter ); }/* END setLogFormatter( LogFormatter ) */ // ========================================================================== /** * Sets whether the log messages will be published to the stdout stream. * * @param publish */ public synchronized void setPublishToStdOut( boolean publish ) { publishToStdOut = publish; }/* END setPublishToStdOut( boolean ) */ // ========================================================================== /** * Determines if the given {@link LogRecord} should be logged. * <p> * If a {@link Filter} has been set, this method returns the value returned by * the {@code Filter}'s isLoggable(). If no {@code Filter} is set, this method * will always return <tt>true</tt>. * * @param logRecord * * @return <tt>true</tt> if the given {@code LogRecord} should be logged, <tt>false</tt> * otherwise */ @Override public boolean isLoggable( LogRecord logRecord ) { boolean rtnBool = true; Filter filter = getFilter(); if( filter != null ) { //If there is a Filter... rtnBool = filter.isLoggable( logRecord ); //Have the filter determine if the LogRecord is loggable } return rtnBool; }/* END isLoggable( LogRecord ) */ // ========================================================================== /** * Publishes the given {@link LogRecord}'s message to the log file and stdout. * <p> * If the given {@code LogRecord} is null this method does nothing. * * @param logRecord the {@code LogRecord} to publish */ @Override public synchronized void publish( LogRecord logRecord ) { if( logRecord == null ) //If the given LogRecord is null... return; //Do nothing if( isLoggable( logRecord ) ) { //If the LogRecord is loggable... //Publish the LogRecord... super.publish( logRecord ); //Publish the log to the file //NOTE: The above call to super.publish(.) will eventually call the same isLoggable(.) // in the condition of this if-block. It was simpler to allow the call to // be repeated than to replicate the file-related logic and components // from the super classes in this class. ( Also, the call is only repeated // when isLoggable(.) returns true, otherwise this block is skipped. ) if( publishToStdOut && theFormatter != null ) System.out.print( theFormatter.getLastLogMessage() ); //Publish the log to stdout } } }
package narif.personal.work.fnutils.test.datastructures; import narif.personal.work.fnutils.datastructures.Tuple; import static org.assertj.core.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @DisplayName("Tuple Specs:") class TupleSpecs { private Tuple<String, Integer> stringIntegerTuple; @BeforeEach private void init(){ stringIntegerTuple = new Tuple<>("One",1); } @Test @DisplayName("The first argument in the tuple constructor gets assigned to the first value.") void testFirstValue(){ assertThat(stringIntegerTuple.getFirst()).isNotEmpty().isEqualTo("One"); } @Test @DisplayName("The second argument in the tuple constructor gets assigned to the second value.") void testSecondValue(){ assertThat(stringIntegerTuple.getSecond()).isGreaterThan(0).isEqualTo(1); } @Test @DisplayName("A tuple creation should throw a null pointer exception if any parameter is null.") void testTupleCreationWithNullValue(){ assertThatNullPointerException().isThrownBy(()->new Tuple<>("1", null)); assertThatNullPointerException().isThrownBy(()->new Tuple<>(null, 1)); assertThatNullPointerException().isThrownBy(()->new Tuple<>(null, null)); assertThat(stringIntegerTuple).isNotNull(); } }
package com.shiroproject.shirogateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ShirogatewayApplication { public static void main(String[] args) { SpringApplication.run(ShirogatewayApplication.class, args); } }
package org.giddap.dreamfactory.leetcode.onlinejudge; import org.giddap.dreamfactory.leetcode.onlinejudge.implementations.RomanToIntegerImpl; import org.junit.Test; import static org.junit.Assert.assertTrue; public class RomanToIntegerTest { private RomanToInteger solution = new RomanToIntegerImpl(); @Test public void small01() { assertTrue(25 == solution.romanToInt("XXV")); } @Test public void small02() { assertTrue(2307 == solution.romanToInt("MMCCCVII")); } @Test public void small03() { assertTrue(1996 == solution.romanToInt("MCMXCVI")); } @Test public void small04() { assertTrue(2425 == solution.romanToInt("MMCDXXV")); } } /* Test cases Input Output Expected "DCXXI" 621 621 "MCMXCVI" 1996 1996 "MDCCCLXXXIV" 1884 1884 "MCDLXXVI" 1476 1476 "MMCCCXCIX" 2399 2399 "MMCDXXV" 2425 2425 "MDLXX" 1570 1570 "MMMDCCLXV" 3765 3765 "MMCCCVII" 2307 2307 */
package com.example.shoji.bakingapp.backgroundtask; import android.content.Context; import android.os.Bundle; import com.example.shoji.bakingapp.pojo.Recipe; import com.example.shoji.bakingapp.utils.NetworkUtils; import com.example.shoji.bakingapp.utils.RecipeJsonUtils; import com.example.shoji.bakingapp.utils.RecipeProviderUtils; import java.util.ArrayList; public class FetchRecipesListener implements LoaderCallBacksListenersInterface<Void> { //private static String RECIPES_URL = "http://go.udacity.com/android-baking-app-json"; private static String RECIPES_URL = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json"; private OnLoadFinishedListener mOnLoadFinishedHandler; /* Enable a listener to process the result. */ public interface OnLoadFinishedListener { void onFetchRecipesFinished(); } public FetchRecipesListener(OnLoadFinishedListener onLoadFinishedHandler) { mOnLoadFinishedHandler = onLoadFinishedHandler; } @Override public void onStartLoading(Context context) { } @Override public Void onLoadInBackground(Context context, Bundle args) { String jsonString = NetworkUtils.getDataFromUrlString(RECIPES_URL); //Timber.d("FetchRecipesListener -- got json: %s", result); if(jsonString != null) { RecipeJsonUtils.listRecipes(context, jsonString); } return null; } @Override public void onLoadFinished(Context context, Void o) { /* The listener will process the result here. */ mOnLoadFinishedHandler.onFetchRecipesFinished(); } }
package com.tickets.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import com.tickets.entity.User; /** * <h1>This repository class is used for user entity related interactions</h1> * @author Joby Chacko * @version 1.0 * @since 2020-04-04 */ public interface UserRepository extends JpaRepository<User, Integer> { Optional<User> findByUserName(String userName); }
package pt.utl.ist.bw.elements; public class DataModelInstanceID { private String instanceID; public DataModelInstanceID(String instanceID) { this.instanceID = instanceID; } @Override public String toString() { return this.instanceID; } @Override public boolean equals(Object anObject) { if(!(anObject instanceof DataModelInstanceID)) { return false; } return ((DataModelInstanceID)anObject).toString().equals(this.instanceID); } @Override public int hashCode() { int hash = 1; hash = hash * 31 + instanceID.hashCode(); hash = hash * 31; return hash; } }
public class Solution{ //common iterative solution public static void shuffle(int[] array){ if(array==null||array.length<2){return;} for(int i=0;i<array.length;i++){ int index = (int)(Math.random()*(i+1)); //generate a rondom number ranged from 0 to i(inclusive) swap(array,i,index); } } private static void swap(int[] array,int i,int j){ int temp = array[i]; array[i] = array[j]; array[j] = temp; } //recursive solution public static void shuffleRecursive(int[] array){ if(array==null||array.length<2){return;} shuffleRecursive(array,array.length-1); } private static void shuffleRecursive(int[] array,int index){ if(index==0){return;} shuffleRecursive(array,index-1); int r = (int)Math.random()*(index+1); swap(array,index,r); } }
package com.project.slider; import java.awt.image.BufferedImage; import java.util.Observable; import java.util.Observer; import com.project.EntityID; import com.project.Handleable; import com.project.ImageHandler; import com.project.battle.BattleScreen; public class VerticalSliderHandle extends Observable{ private int x,y,startX,startY; private int stepLen; private int maxStep; // 0 based indexing private int curStep; private Observer obs; private SliderID id; private ImageHandler handleImg; private int mouseOffset= 0; /** curStep & maxStep use 0-based indexing */ public VerticalSliderHandle(int x, int y, int stepLen, int maxStep, int curStep, BufferedImage handleImg, Observer obs,SliderID id) { this.x = x; this.startX = x; this.y = y; this.startY = y; this.obs = obs; this.id = id; this.stepLen = stepLen; this.maxStep = maxStep; this.curStep = curStep; this.handleImg = new ImageHandler(x, y, handleImg, true, EntityID.UI); } public int getStep() { return curStep; } public boolean isInside(int x2, int y2) { return (x2>x && x2<x+handleImg.getWidth()) && (y2>y && y2<y+handleImg.getHeight()) ; } public void drag(int x2, int y2) { y2+=mouseOffset; if(y2 > startY && y2 < startY + (maxStep * stepLen)){ handleImg.setyCoordinate(y2); y=y2; } } public void grabbed(int x, int y){ this.mouseOffset = this.y-y; } public void setX(int x) { this.x = x; this.startX = x; this.handleImg.setxCoordinate(x); } public void setStartX(int x) { this.startX = x; } public void setY(int y) { this.y = y; this.handleImg.setyCoordinate(y); } public void setStartY(int y2) { this.startY = y; } public static void delete(VerticalSliderHandle handle) { ImageHandler.delete(BattleScreen.handler, handle.handleImg); handle = null; } public Handleable getImg() { return handleImg; } public void drop() { int middle =(y + handleImg.getHeight()/2) - startY; int step = middle / stepLen; moveTo(step); } public void moveTo(int step) { if(step>=0 && step<maxStep+1){ // update Y pos of handle setY(startY + (stepLen*step)); obs.update(this, id); } } }
package com.pattern.observe.p2pcase.rebuild; public interface RegObserver { void handRegSuccess(long userId); }
package com.revolut.moneytransfer.entity; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; public class Account { @JsonIgnore private long accountNo; @JsonProperty(required = true) private long accountNumber; @JsonProperty(required = true) private String phoneNumber; @JsonProperty(required = true) private BigDecimal balance; @JsonProperty(required = true) private String currencyCode; public Account() { } public Account(long accountNo, long accountNumber, String phoneNumber, BigDecimal balance, String currencyCode) { this.accountNo = accountNo; this.accountNumber = accountNumber; this.phoneNumber = phoneNumber; this.balance = balance; this.currencyCode = currencyCode; } public Account(long accountNumber, String phoneNumber, BigDecimal balance, String currencyCode) { this.accountNumber = accountNumber; this.phoneNumber = phoneNumber; this.balance = balance; this.currencyCode = currencyCode; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public long getAccountNumber() { return accountNumber; } public void setAccountNumber(long accountNumber) { this.accountNumber = accountNumber; } public long getAccountNo() { return accountNo; } public void setAccountNo(long accountNo) { this.accountNo = accountNo; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Account [accountNo="); builder.append(accountNo); builder.append(", accountNumber="); builder.append(accountNumber); builder.append(", phoneNumber="); builder.append(phoneNumber); builder.append(", balance="); builder.append(balance); builder.append(", currencyCode="); builder.append(currencyCode); builder.append("]"); return builder.toString(); } }
package com.web.common; import com.web.framework.util.StringUtil; /** * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class CodeParam { protected String systemcode=""; protected String type=""; protected String name=""; protected String selected=""; protected String event=""; protected String first=""; protected String etc=""; protected String style=""; protected String styleClass=""; /** * */ public CodeParam() { super(); // TODO Auto-generated constructor stub } /** * @return Returns the styleClass. */ public String getStyleClass() { return styleClass; } /** * @param styleClass The styleClass to set. */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } /** * @return Returns the style. */ public String getStyle() { return style; } /** * @param style The style to set. */ public void setStyle(String style) { this.style = style; } /** * @return Returns the event. */ public String getEvent() { return event; } /** * @param event The event to set. */ public void setEvent(String event) { this.event = event; } /** * @return Returns the first. */ public String getFirst() { return first; } /** * @param first The first to set. */ public void setFirst(String first) { this.first = first; } /** * @return Returns the name. */ public String getName() { return name; } /** * @param name The name to set. */ public void setName(String name) { this.name = StringUtil.outDataConverter(name); } /** * @return Returns the selected. */ public String getSelected() { return selected; } /** * @param selected The selected to set. */ public void setSelected(String selected) { this.selected = selected; } /** * @return Returns the systemcode. */ public String getSystemcode() { return systemcode; } /** * @param systemcode The systemcode to set. */ public void setSystemcode(String systemcode) { this.systemcode = systemcode; } /** * @return Returns the type. */ public String getType() { return type; } /** * @param type The type to set. */ public void setType(String type) { this.type = type; } /** * @return Returns the etc. */ public String getEtc() { return etc; } /** * @param etc The etc to set. */ public void setEtc(String etc) { this.etc = etc; } }
package application; import controller.Controller; import model.GameEngineImpl; import view.AppFrame; import view.GameEngineCallbackGUI; import view.GameEngineCallbackImpl; import view.model.PlayerStates; public class Driver { public static void main(String[] args) { GameEngineImpl gei = new GameEngineImpl(); AppFrame af = new AppFrame(); PlayerStates ps = new PlayerStates(gei, af); GameEngineCallbackGUI gecbg = new GameEngineCallbackGUI(af, ps); gei.addGameEngineCallback(new GameEngineCallbackImpl()); gei.addGameEngineCallback(gecbg); Controller cont = new Controller(gei, af, ps); cont.start(); } }
package com.sourceit.maps.ui; import android.view.View; /** * Created by User on 14.03.2016. */ public abstract class OnItemClickWatcher<T> { public abstract void onItemClick(View v, int position, T item); }
package com.tauros; public class Starter { public static IShoppingMall getShoppingMallHandler() { IShoppingMall shopping_mall = null; shopping_mall = (IShoppingMall)new ShoppingMall(); return shopping_mall; } }
package com.xwj.dao; import com.xwj.entity.Role; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface RoleDao { int insertRole(Role role); int updateRole(int i); Role getRole(int id); int deleteRole(int id,int nomean); List<Role> getRoles(@Param("ids") List<Integer> ids); }
import java.util.Random; import java.util.concurrent.TimeUnit; public class TeamLeader extends Employee{ private int teamNumber; private int teamMemberNumber; private long lunchTime; private Developer[] team; protected Runnable goToLunch; protected Runnable endOfDayLeave; protected Runnable standUpMeeting; protected Runnable teamSchedulingMeeting; protected void initRunnables() { // TODO Auto-generated method stub goToLunch = new Runnable() { public void run() { try { System.out.println("Team Leader " + teamNumber + teamMemberNumber + " is going to lunch."); Thread.sleep(lunchTime); System.out.println("Team Leader " + teamNumber + teamMemberNumber + " has returned from lunch." ); } catch (InterruptedException e) { } } }; endOfDayLeave = new Runnable() { public void run() { System.out.println("Team Leader " + teamNumber + teamMemberNumber + " is leaving work."); //Throw an interrupt which states that this team leader thread can now be terminated //as the developer has now left. interrupt(); } }; teamSchedulingMeeting = new Runnable() { public void run() { System.out.println("Team Leader " + teamNumber + teamMemberNumber + " had the scheduling meeting."); //conferenceRoom.enterRoom() } }; standUpMeeting = new Runnable() { public void run() { ((Manager)getSupervisor()).getOffice().enterRoom(); } }; } public TeamLeader(Scheduler scheduler, Manager manager, int teamNumber, int teamMemberNumber) { super(scheduler, manager); this.teamNumber = teamNumber; this.teamMemberNumber = teamMemberNumber; this.setName("" + teamNumber + teamMemberNumber); this.teamMemberNumber = teamMemberNumber; this.teamNumber = teamNumber; initRunnables(); registerDaysEvents(scheduler); } public void assignTeam(Developer[] team){ this.team = team; } @Override protected void registerDaysEvents(Scheduler scheduler) { long endofDayMeeting = TimeUnit.NANOSECONDS.convert(4800, TimeUnit.MILLISECONDS); Random randomGen = new Random(); //Randomly generating a time to go to lunch //It randomly selects a time between the hours of 12 and 1 in minutes. long randomlunchTime = randomGen.nextInt(3000 - 2400 + 1) + 2400; long devLunchStart = TimeUnit.NANOSECONDS.convert(randomlunchTime, TimeUnit.MILLISECONDS); lunchTime = randomGen.nextInt(600 - 300 + 1) + 300; lunchTime = TimeUnit.NANOSECONDS.convert(lunchTime, TimeUnit.MILLISECONDS); long leaveTime = 4800 + lunchTime; leaveTime = TimeUnit.NANOSECONDS.convert(leaveTime, TimeUnit.MILLISECONDS); scheduler.registerEvent(endOfDayLeave, this, leaveTime, true); scheduler.registerEvent(goToLunch, this, devLunchStart, false); scheduler.registerEvent(standUpMeeting, this, 0, false); scheduler.registerEvent(teamSchedulingMeeting, this, endofDayMeeting, false); //scheduler.registerEvent(teamSchedulingMeeting, this, 4800000000L); //can ask up to 3 questions a day int numQuestions = (int)(3 * Math.random()); for (int i = 0; i < numQuestions; i++){ scheduler.registerEvent(askQuestion, this, (long)(Math.random() * leaveTime), false); } } @Override protected void onQuestionAsked(Employee askedTo) { System.out.println("Team Leader " + this.getName() + " asked " + askedTo.getName() + "a question."); } @Override protected void onAnswerReceived(Employee receivedFrom) { System.out.println("Team Leader " + this.getName() + " received an answer from " + receivedFrom.getName() + "."); } @Override protected void onQuestionCancelled(Employee notAvailable) { System.out.println("Team Leader "+this.getName()+"'s question was " + "cancelled, "+notAvailable.getName()+" is not available"); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aot.hint; import java.util.List; import javax.lang.model.SourceVersion; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * A {@link TypeReference} based on fully qualified name. * * @author Stephane Nicoll * @since 6.0 */ final class SimpleTypeReference extends AbstractTypeReference { private static final List<String> PRIMITIVE_NAMES = List.of("boolean", "byte", "short", "int", "long", "char", "float", "double", "void"); @Nullable private String canonicalName; SimpleTypeReference(String packageName, String simpleName, @Nullable TypeReference enclosingType) { super(packageName, simpleName, enclosingType); } static SimpleTypeReference of(String className) { Assert.notNull(className, "'className' must not be null"); if (!isValidClassName(className)) { throw new IllegalStateException("Invalid class name '" + className + "'"); } if (!className.contains("$")) { return createTypeReference(className); } String[] elements = className.split("(?<!\\$)\\$(?!\\$)"); SimpleTypeReference typeReference = createTypeReference(elements[0]); for (int i = 1; i < elements.length; i++) { typeReference = new SimpleTypeReference(typeReference.getPackageName(), elements[i], typeReference); } return typeReference; } private static boolean isValidClassName(String className) { for (String s : className.split("\\.", -1)) { String candidate = s.replace("[", "").replace("]", ""); if (!SourceVersion.isIdentifier(candidate)) { return false; } } return true; } private static SimpleTypeReference createTypeReference(String className) { int i = className.lastIndexOf('.'); if (i != -1) { return new SimpleTypeReference(className.substring(0, i), className.substring(i + 1), null); } else { String packageName = (isPrimitive(className) ? "java.lang" : ""); return new SimpleTypeReference(packageName, className, null); } } @Override public String getCanonicalName() { if (this.canonicalName == null) { StringBuilder names = new StringBuilder(); buildName(this, names); this.canonicalName = addPackageIfNecessary(names.toString()); } return this.canonicalName; } @Override protected boolean isPrimitive() { return isPrimitive(getSimpleName()); } private static boolean isPrimitive(String name) { return PRIMITIVE_NAMES.stream().anyMatch(name::startsWith); } private static void buildName(@Nullable TypeReference type, StringBuilder sb) { if (type == null) { return; } String typeName = (type.getEnclosingType() != null ? "." + type.getSimpleName() : type.getSimpleName()); sb.insert(0, typeName); buildName(type.getEnclosingType(), sb); } }
package net.voldrich.graal.async.script; import lombok.extern.slf4j.Slf4j; import net.voldrich.graal.async.ScriptTestUtils; import net.voldrich.graal.async.api.MockedHttpClient; import net.voldrich.graal.async.api.ScriptMockedHttpResponse; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.time.Duration; import java.util.function.Consumer; @Slf4j class AsyncScriptExecutorTest { private AsyncScriptExecutor executor; private MockedHttpClient mockedHttpClient; @BeforeEach void setUp() { executor = new AsyncScriptExecutor.Builder().build(); mockedHttpClient = new MockedHttpClient(); } @AfterEach void tearDown() { executor.getScriptSchedulers().dispose(); } @Test void executeScript() { Mono<String> scriptMono = executeScript("scripts/test-script-timeout.js"); StepVerifier.create(scriptMono) .expectNext("[{\"id\":1,\"name\":\"Steve Jobs\"},{\"id\":2,\"name\":\"Bob Balmer\"}]") .expectComplete() .verify(); } @Test void executeScriptCancel() throws InterruptedException { Mono<String> scriptMono = executeScript("scripts/test-script-timeout.js"); StepVerifier.create(scriptMono) .thenRequest(1) .thenAwait(Duration.ofMillis(50)) .thenCancel() .verify(); } private Mono<String> executeScript(String scriptResource) { return executeScript(scriptResource, null); } private Mono<String> executeScript(String scriptResource, MockedHttpClient mockedHttpClient) { return executor.executeScript(new TestScriptHandler(scriptResource, mockedHttpClient)); } @Test void testScriptErrorSyntax() { Mono<String> stringMono = executeScript("scripts/test-script-error-syntax.js"); StepVerifier.create(stringMono) .expectErrorSatisfies(verifyScriptException( Matchers.startsWith("org.graalvm.polyglot.PolyglotException: SyntaxError: script:2:30 Expected"), null)) .verify(); } @Test void testScriptErrorEval() { Mono<String> stringMono = executeScript("scripts/test-script-error-eval.js"); StepVerifier.create(stringMono) .expectErrorSatisfies(verifyScriptException( Matchers.startsWith("org.graalvm.polyglot.PolyglotException: ReferenceError: company is not defined"), null)) .verify(); } @Test void testScriptWithUsingClient() { mockedHttpClient.addResponse("/company/info", new ScriptMockedHttpResponse(200, "json/company-info.json", 50)); mockedHttpClient.addResponse("/company/ceo", new ScriptMockedHttpResponse(200, "json/ceo-list.json", 100)); Mono<String> stringMono = executeScript("scripts/test-http-get.js", mockedHttpClient); StepVerifier.create(stringMono) .consumeNextWith(verifyJsonMatchesResource("json/expected-response-client.json")) .verifyComplete(); } @Test void testScriptWithUsingClientParralel() { mockedHttpClient.addResponse("/company/info", new ScriptMockedHttpResponse(200, "json/company-info.json", 100)); Mono<String> stringMono = executeScript("scripts/test-http-get-parralel.js", mockedHttpClient); StepVerifier.create(stringMono) .consumeNextWith(verifyJsonMatchesResource("json/expected-response-parralel.json")) .verifyComplete(); } @Test void testScriptWithUsingClientException() { mockedHttpClient.addResponse("/company/info", new ScriptMockedHttpResponse(200, "json/company-info.json", 50)); Mono<String> stringMono = executeScript("scripts/test-http-get.js", mockedHttpClient); StepVerifier.create(stringMono) .expectErrorSatisfies(verifyScriptException( Matchers.startsWith("java.lang.RuntimeException: 404 NOT FOUND"), Matchers.startsWith("Status for company info: 200"))) .verify(); } private Consumer<String> verifyJsonMatchesResource(String resourceName) { return json -> { log.debug("Received next: {}", json); try { JSONAssert.assertEquals(ScriptTestUtils.stringFromResource(resourceName), json, false); } catch (Exception exception) { throw new AssertionError(exception); } }; } private Consumer<Throwable> verifyScriptException(Matcher<String> messageMatcher, Matcher<String> outputMatcher) { return exception -> { if (!(exception instanceof ScriptExecutionException)) { throw new AssertionError("ScriptExecutionException expected"); } ScriptExecutionException scriptException = (ScriptExecutionException) exception; if (!messageMatcher.matches(scriptException.getMessage())) { throw new AssertionError("Message matcher " + messageMatcher.toString() + " failed to match '" + scriptException.getMessage() + "'"); } if (outputMatcher != null) { if (!outputMatcher.matches(scriptException.getScriptOutput())) { throw new AssertionError("Output matcher " + outputMatcher.toString() + " failed to match '" + scriptException.getScriptOutput() + "'"); } } }; } }
package annotation; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class UserCaseTracker { public static void tracker(List<Integer> userCaseIds, Class<?> cl){ Method[] methods = cl.getDeclaredMethods(); for (Method method : methods){ UserCase userCase = method.getAnnotation(UserCase.class); if (userCase == null){ continue; } System.out.println("userCase.id:"+userCase.id()+ ", userCase.description:"+userCase.description()); userCaseIds.remove(new Integer(userCase.id())); System.out.println(userCaseIds); } System.out.println(userCaseIds); } public static void main(String[] args){ List<Integer> ids = new ArrayList<>(); Collections.addAll(ids,1,2,3,4); tracker(ids, PasswordUtils.class); Collections.reverse(ids); } }
package lotro.sk; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import lotro.models.Character; import file.FileUtils; public class RiftPlayer implements Comparable<RiftPlayer> { public static final Map<String, RiftPlayer> PLAYERS = new HashMap<String, RiftPlayer>(); private static final String HOME = System.getProperty ("user.home"); public static final String SK_LIST = HOME + "/My Documents/My Dropbox/Public/Palantiri/sk"; private static DecimalFormat df = new DecimalFormat ("000"); private String name; private int order; public RiftPlayer (final String name) { setName (name); setOrder (PLAYERS.size() + 1); } public String getName() { return name; } public void setName (final String name) { this.name = name; } public int getOrder() { return order; } public void setOrder (final int order) { this.order = order; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append (df.format (order)); sb.append (" - "); sb.append (name); Queue<Character> characters = new LinkedList<Character>(); for (Character ch : Character.getCharacters()) if (ch.getPlayer().getName().equals (name)) characters.add (ch); if (!characters.isEmpty()) { sb.append (" ("); sb.append (characters.poll()); while (!characters.isEmpty()) sb.append (", " + characters.poll()); sb.append (")"); } return sb.toString(); } public int compareTo (final RiftPlayer o) { int compare = getOrder() - o.getOrder(); if (compare == 0) compare = getName().compareTo (o.getName()); return compare; } public static void load() { List<String> lines = FileUtils.getList (SK_LIST, FileUtils.UTF8, true); for (String line : lines) { RiftPlayer player = new RiftPlayer (line); PLAYERS.put (player.getName(), player); } } public static void publish (final Collection<RiftPlayer> players) { List<String> lines = new ArrayList<String>(); for (RiftPlayer player : players) lines.add (player.getName()); FileUtils.writeList (lines, SK_LIST, false); } }
package gov.nih.nci.ctrp.importtrials.util; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.junit.Test; import gov.nih.nci.ctrp.importtrials.dto.PlannedEligibilityCriterionDTO; import gov.nih.nci.ctrp.importtrials.dto.ctgov.EligibilityStruct; import gov.nih.nci.ctrp.importtrials.dto.ctgov.TextblockStruct; public class ExtractInlusionExclusionCriteriaTest { @Test public void testExtractInlusionExclusionCriteria() throws Exception { String xmlStr = new String(Files.readAllBytes(Paths.get("src/test/resources/eligibility_samples.xml")), "UTF-8"); Samples samples = ImportTrialUtils.unmarshallXML(xmlStr, Samples.class); for(Sample sample : samples.getSample()) { String nctId = sample.getNctId(); TextblockStruct mockText = mock(TextblockStruct.class); when(mockText.getTextblock()).thenReturn(sample.getEligibility()); EligibilityStruct mockElig = mock(EligibilityStruct.class); when(mockElig.getCriteria()).thenReturn(mockText); List<PlannedEligibilityCriterionDTO> list = ClinicalStudyConverter.extractInlusionExclusionCriteria(mockElig); long inclusionCount = list.stream().filter(dto -> dto.isInclusionIndicator()).count(); long exclusionCount = list.stream().filter(dto -> !dto.isInclusionIndicator()).count(); assertEquals(nctId + " inclusion count", sample.getInclusions(), inclusionCount); assertEquals(nctId + " exclusion count", sample.getExclusions(), exclusionCount); } } @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "samples") public static class Samples { @XmlElement(name = "sample") public List<Sample> samples; public List<Sample> getSample() { return samples; } public void setSample(List<Sample> samples) { this.samples = samples; } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "sample_struct") public static class Sample { @XmlElement(name = "nct_id") public String nctId; @XmlElement(name = "inclusions") public int inclusions; @XmlElement(name = "exclusions") public int exclusions; @XmlElement(name = "eligibility") public String eligibility; public String getNctId() { return nctId; } public void setNctId(String nctId) { this.nctId = nctId; } public int getInclusions() { return inclusions; } public void setInclusions(int inclusions) { this.inclusions = inclusions; } public int getExclusions() { return exclusions; } public void setExclusions(int exclusions) { this.exclusions = exclusions; } public String getEligibility() { return eligibility; } public void setEligibility(String eligibility) { this.eligibility = eligibility; } } }
package pl.edu.pjatk.System.zarzadzania.zamowieniami.model; import java.time.LocalDate; import java.util.List; import javax.persistence.*; @Entity @Table(name = "constructionSite") public class ConstructionSite { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; @OneToMany(mappedBy = "constructionSite", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH }) private List<ServiceOrder> serviceOrderList; @OneToMany(mappedBy = "constructionSite", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH }) private List<Employee> employeeList; @Column(name = "name") private String name; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "addressId") private Address adress; @Column(name = "budget") private double budget; @Column(name = "startDate") private LocalDate startDate; @Column(name = "endDate") private LocalDate endDate; public ConstructionSite() {}; public ConstructionSite(String name, Address adress, double budget, LocalDate startDate, LocalDate endDate) { this.name = name; this.adress = adress; this.budget = budget; this.startDate = startDate; this.endDate = endDate; } public int getId() { return id; } public void setId(int id) { this.id = id; } public List<ServiceOrder> getOrderList() { return serviceOrderList; } public void setOrderList(List<ServiceOrder> serviceOrderList) { this.serviceOrderList = serviceOrderList; } // public List<Employee> getEmployeeList() { // return employeeList; // } // // public void setEmployeeList(List<Employee> employeeList) { // this.employeeList = employeeList; // } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAdress() { return adress; } public void setAdress(Address adress) { this.adress = adress; } public double getBudget() { return budget; } public void setBudget(double budget) { this.budget = budget; } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } }
package com.robin.springboot.demo.mongodb; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.MongoRepository; public abstract class MongoSuperServiceImpl< R extends MongoRepository, T extends Object, ID> implements MongoSuperService { // 能使用 JPA mongodb 操作的优先使用,jpa mongodb 操作, 不能满足,再使用 mongoTemplate 作为补充 @Autowired protected R mongoRepository; @Autowired protected MongoTemplate mongoTemplate; }
package com.lab.shopCart.shopcartms.application.internal.service; import com.lab.shopCart.shopcartms.domain.model.GoodEntity; import com.lab.shopCart.shopcartms.domain.model.ShopCartEntity; import com.lab.shopCart.shopcartms.infrastructure.repository.GoodRepository; import com.lab.shopCart.shopcartms.infrastructure.repository.ShopCartRepository; import com.lab.shopCart.shopcartms.interfaces.rest.dto.goods.GoodResDto; import com.lab.shopCart.shopcartms.interfaces.rest.dto.order.OrderReqDto; import com.lab.shopCart.shopcartms.interfaces.rest.dto.order.OrderResDto; import com.lab.shopCart.shopcartms.interfaces.rest.dto.shopcart.ShopCartReqDto; import com.lab.shopCart.shopcartms.interfaces.rest.dto.shopcart.ShopCartResDto; import com.lab.shopCart.shopcartms.interfaces.rest.vo.goods.GoodVo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.ArrayList; import java.util.List; @Slf4j @Service @Transactional public class ShopCartService { @Autowired ShopCartRepository shopCartRepository; @Autowired GoodRepository goodRepository; @Autowired GoodService goodService; public ShopCartResDto createShopCart(ShopCartReqDto shopCartReqDto) { ShopCartEntity shopCartEntity = new ShopCartEntity(); shopCartEntity.setCustomerName(shopCartReqDto.getCustomerName()); shopCartRepository.save(shopCartEntity); return ShopCartResDto.addByRes(shopCartReqDto); } public void updateTotalAmount(Integer cartId){ ShopCartEntity shopCartEntity = shopCartRepository.getById(cartId); List<GoodEntity> goodEntities = goodRepository.findByCartId(cartId); Integer totalAmount = 0; Integer increaseAmount = goodEntities.stream().mapToInt(x -> x.getUnitPrice() * x.getCount()).sum(); log.info("Goods amount is : {} in this time",increaseAmount); totalAmount+=increaseAmount; log.info("Total Amount is {}",totalAmount); shopCartEntity.setTotalAmount(totalAmount); shopCartRepository.saveAndFlush(shopCartEntity); } /** 取得購物車 * * @param cartId 購物車編號 * @return */ public ShopCartEntity getShopCartEntityByCartId(Integer cartId){ return shopCartRepository.getById(cartId); } /** 建立訂單 * * @param cartId 購物車編號 * @return */ @Transactional(rollbackOn = Exception.class) public OrderResDto createOrder(Integer cartId) { ShopCartEntity shopCartEntity = shopCartRepository.getById(cartId); OrderResDto orderResDto = null; try { orderResDto = goodService.createOrder(shopCartEntity); List<GoodVo> goods = orderResDto.getGoods(); goods.stream().forEach(good ->{ String goodId = good.getGoodsId(); try { goodService.updateInventory(goodId); goodService.deleteGood(goodId); updateTotalAmount(cartId); } catch (Exception e) { log.error("update inventory error...{}",e.getMessage()); } }); } catch (Exception e) { log.error("create order error...{}",e.getMessage()); } return orderResDto; } }
package com.ray.utils.iputil; /** * Created by Administrator on 2016/1/28. */ public class AAA { public void Url(String str){ System.out.println("a0"); } }
package cqut.syntaxAnalyzer; import java.util.ArrayList; import java.util.List; import java.util.Map; import cqut.util.SystemProperty; import cqut.util.entity.Syntax; public class SyntaxServiceImpl implements SyntaxService { public static Map<String, String> syntaxes; private static SyntaxService syntaxService; public static SyntaxService getInstance() { if (syntaxes == null) { syntaxes = SystemProperty.readProperties("src/syntax.properties"); syntaxService = new SyntaxServiceImpl(); } return syntaxService; } @Override public int size() { return syntaxes.size(); } @Override public Syntax getSyntax(String starting) { Syntax syntax = new Syntax(); syntax.setStarting(starting); List<String> pros = new ArrayList<String>(); String[] str = syntaxes.get(starting).split("|"); for (String s : str) { pros.add(s); } syntax.setProduction(pros); return syntax; } @Override public List<String> getNonTerminalStarting(String starting) { return null; } @Override public List<String> getNonTerminalStarting(String starting, int index) { return null; } @Override public List<String> getTerminalSymbol(String starting) { return null; } @Override public List<String> getTerminalSymbol(String starting, int index) { return null; } @Override public List<Syntax> getSyntax() { return null; } }
package com.fest.pecfestBackend.repository; import com.fest.pecfestBackend.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserRepo extends JpaRepository<User, Long>, JpaSpecificationExecutor<User>{ User findByEmail(String email); User findByEmailAndPassword(String email,String password); List<User> findByRequireAccommodationTrue(); User findBySessionId(String sessionId); boolean existsByPecFestIdAndIsVerified(String pecFestId,boolean isVerified); User findByPecFestId(String pecFestId); User findByIdAndOtpForPasswordReset(Long id,String otpForPasswordReset); }
public class BinaryTree<K extends Comparable<K>> { private BinaryTreeNode<K> root; public void add(K key) { this.root = this.addRecursively(root, key); } // recursive function to add nodes private BinaryTreeNode<K> addRecursively(BinaryTreeNode<K> current, K key) { if (current == null) return new BinaryTreeNode<>(key); int compareResult = key.compareTo(current.key); if (compareResult == 0) return current; if (compareResult < 0) { current.left = addRecursively(current.left, key); } else current.right = addRecursively(current.right, key); return current; } public int getSize() { return this.getSizeRecursively(root); } private int getSizeRecursively(BinaryTreeNode<K> currentNode) { return currentNode == null ? 0 : 1 + this.getSizeRecursively(currentNode.left) + this.getSizeRecursively(currentNode.right); } // recursive function to add nodes private boolean searchRecursively(BinaryTreeNode<K> current, K key) { if (current == null) return false; int compareResult = key.compareTo(current.key); if (compareResult == 0) return true; if (compareResult < 0) { return searchRecursively(current.left, key); } else return searchRecursively(current.right, key); } // search a node for a given key value public boolean search(K key) { boolean isPresent = searchRecursively(this.root,key); return isPresent; } }
package net.kemitix.dependency.digraph.maven.plugin.stubs; /** * Project list for the source and test project. * * @author pcampbell */ public class DigraphSrcOnlyProjectList extends AbstractProjectsList { /** * Default constructor. */ public DigraphSrcOnlyProjectList() { super(new DigraphProjectStub("/src/test/projects/src-only")); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package vista; import javax.swing.JFrame; import modelo.AdminBD; import modelo.Catalogo; import modelo.Pelicula; /** * * @author Jhon Nash */ public class InfoPelicula extends JFrame { Catalogo catalogo; Pelicula pelicula; AdminBD adminBD; /** * Creates new form InfoPelicula */ public InfoPelicula() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { panel1 = new java.awt.Panel(); lbTitulo = new javax.swing.JLabel(); lbActor = new javax.swing.JLabel(); lbGenero = new javax.swing.JLabel(); txtTitulo = new javax.swing.JTextField(); txtActor = new javax.swing.JTextField(); txtGenero = new javax.swing.JTextField(); lbPrecio = new javax.swing.JLabel(); txtPrecio = new javax.swing.JTextField(); btnGuardar = new javax.swing.JButton(); btnDescartar = new javax.swing.JButton(); lbTitulo.setText("Titulo"); lbActor.setText("Actor Prinipal"); lbGenero.setText("Genero"); lbPrecio.setText("Precio"); btnGuardar.setText("Guardar"); btnGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGuardarActionPerformed(evt); } }); btnDescartar.setText("Descartar"); btnDescartar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDescartarActionPerformed(evt); } }); javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1); panel1.setLayout(panel1Layout); panel1Layout.setHorizontalGroup( panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup() .addGap(55, 55, 55) .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(lbPrecio, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbGenero, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbTitulo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbActor, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE) .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtPrecio, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE) .addComponent(txtGenero, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtActor, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtTitulo, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(118, 118, 118)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnDescartar) .addGap(50, 50, 50) .addComponent(btnGuardar) .addGap(40, 40, 40)) ); panel1Layout.setVerticalGroup( panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel1Layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbTitulo) .addComponent(txtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbActor) .addComponent(txtActor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbGenero) .addComponent(txtGenero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbPrecio) .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 95, Short.MAX_VALUE) .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnGuardar) .addComponent(btnDescartar)) .addGap(27, 27, 27)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnDescartarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDescartarActionPerformed // TODO add your handling code here: this.dispose(); }//GEN-LAST:event_btnDescartarActionPerformed private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed // TODO add your handling code here: catalogo = new Catalogo(); pelicula = new Pelicula(); adminBD = new AdminBD(); catalogo.adicionarPelicula(catalogo.generaCodigodeBarras(),this.txtTitulo.getText(), this.txtActor.getText(),this.txtGenero.getText(),this.txtPrecio.getText()); pelicula = catalogo.getPelicula(); adminBD.insertarPelicula(pelicula); pelicula.toString(); this.dispose(); }//GEN-LAST:event_btnGuardarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(InfoPelicula.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(InfoPelicula.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(InfoPelicula.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(InfoPelicula.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new InfoPelicula().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnDescartar; private javax.swing.JButton btnGuardar; private javax.swing.JLabel lbActor; private javax.swing.JLabel lbGenero; private javax.swing.JLabel lbPrecio; private javax.swing.JLabel lbTitulo; private java.awt.Panel panel1; private javax.swing.JTextField txtActor; private javax.swing.JTextField txtGenero; private javax.swing.JTextField txtPrecio; private javax.swing.JTextField txtTitulo; // End of variables declaration//GEN-END:variables }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class RemoteHeadServer { /** * @param args */ final static int port = 10657; public static void main(String[] args) { System.out.println("Buonsalve. Server avviato."); ServerSocket srvsocket; //////////////////////////////////////////////////////// Creazione socket try { srvsocket = new ServerSocket(port); /////////////////////////////////////////////////////// Main Loop while(true){ Socket socket = srvsocket.accept(); System.out.println("Accettato."); BufferedReader networkIn = new BufferedReader( new InputStreamReader(socket.getInputStream(), "UTF-8")); BufferedWriter networkOut = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); String line; line = networkIn.readLine(); System.out.println("Richiesta: " + line); File tempFile = new File(line); boolean exists = tempFile.exists(); if(exists){ System.out.println("Il file ESISTE."); BufferedReader reader = new BufferedReader(new FileReader(line)); networkOut.write(reader.readLine());networkOut.newLine(); networkOut.write(reader.readLine());networkOut.newLine(); networkOut.write(reader.readLine());networkOut.newLine(); networkOut.write(reader.readLine());networkOut.newLine(); networkOut.write(reader.readLine());networkOut.newLine(); } else System.out.println("Il file NON ESISTE."); networkOut.flush(); socket.close(); //srvsocket.close(); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("Bruh."); System.exit(1); } } }
package de.fu_berlin.cdv.chasingpictures.api; import android.util.Log; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.File; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Date; /** * This class represents a picture which is associated with a place. * @author Simon Kalt */ @JsonIgnoreProperties(ignoreUnknown = true) public class Picture implements Serializable { private long id; private Date time; private String url; // TODO: Deserialize as URL? @JsonProperty("place_id") private long placeId; @JsonProperty("created_at") private Date createdAt; @JsonProperty("updated_at") private Date updatedAt; @JsonIgnore private File cachedFile; // TODO: Split up these properties into a separate object private String file_file_name; private String file_content_type; private Integer file_file_size; private Date file_updated_at; private Integer user_id; public long getId() { return id; } public void setId(long id) { this.id = id; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getUrl() { return url; } public URL getASCIIUrl() { try { URI uri = new URL(url).toURI(); return new URL(uri.toASCIIString()); } catch (MalformedURLException | URISyntaxException e) { Log.e("Picture", Log.getStackTraceString(e)); } return null; } public void setUrl(String url) { this.url = url; } public long getPlaceId() { return placeId; } public void setPlaceId(long placeId) { this.placeId = placeId; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } public File getCachedFile() { return cachedFile; } public void setCachedFile(File cachedFile) { this.cachedFile = cachedFile; } public String getFile_file_name() { return file_file_name; } public void setFile_file_name(String file_file_name) { this.file_file_name = file_file_name; } public String getFile_content_type() { return file_content_type; } public void setFile_content_type(String file_content_type) { this.file_content_type = file_content_type; } public Integer getFile_file_size() { return file_file_size; } public void setFile_file_size(Integer file_file_size) { this.file_file_size = file_file_size; } public Date getFile_updated_at() { return file_updated_at; } public void setFile_updated_at(Date file_updated_at) { this.file_updated_at = file_updated_at; } public Integer getUser_id() { return user_id; } public void setUser_id(Integer user_id) { this.user_id = user_id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Picture picture = (Picture) o; if (id != picture.id) return false; if (placeId != picture.placeId) return false; if (time != null ? !time.equals(picture.time) : picture.time != null) return false; if (url != null ? !url.equals(picture.url) : picture.url != null) return false; if (createdAt != null ? !createdAt.equals(picture.createdAt) : picture.createdAt != null) return false; return !(updatedAt != null ? !updatedAt.equals(picture.updatedAt) : picture.updatedAt != null); } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (time != null ? time.hashCode() : 0); result = 31 * result + (url != null ? url.hashCode() : 0); result = 31 * result + (int) (placeId ^ (placeId >>> 32)); result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0); result = 31 * result + (updatedAt != null ? updatedAt.hashCode() : 0); return result; } @Override public String toString() { return "Picture{" + "id=" + id + ", time=" + time + ", url='" + url + '\'' + ", placeId=" + placeId + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + '}'; } }
public class Main1_3 { public static void main(String[] args) { int initScore = 5; int scoreTom = initScore; int scoreBob = initScore; System.out.println("Round 1 results:"); System.out.println(scoreTom++); System.out.println(--scoreBob); } }
package com.lxl.service; import com.lxl.beans.po.DfGroupTypePo; import com.lxl.beans.po.DfGroupTypePoExample; import com.lxl.beans.po.TypePo; import com.lxl.beans.po.TypePoExample; import com.lxl.beans.vo.DfGroupType; import com.lxl.constants.EType; import com.lxl.dao.DfGroupTypePoMapper; import com.lxl.dao.TypePoMapper; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import com.lxl.beans.vo.Type; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * Created by xiaolu on 15/5/4. */ @Service public class TypeService { Logger logger = Logger.getLogger(TypeService.class); @Resource TypePoMapper typePoMapper; @Resource DfGroupTypePoMapper dfGroupTypePoMapper; public List<DfGroupType> getGroupTypeByTypeid(Integer typeid) { DfGroupTypePoExample example = new DfGroupTypePoExample(); example.createCriteria().andTypeidEqualTo(typeid); example.setOrderByClause("groupid asc"); List<DfGroupTypePo> list = this.dfGroupTypePoMapper.selectByExample(example); List<DfGroupType> ret = new ArrayList<DfGroupType>(); for(DfGroupTypePo po : list) { ret.add(new DfGroupType(po)); } return ret; } public Type getTypeById(int id) { TypePoExample example = new TypePoExample(); example.createCriteria() .andIdEqualTo(id); TypePo typePo; try { typePo = this.typePoMapper.selectByExample(example).get(0); } catch (Exception e) { return new Type(); } return new Type(typePo); } public List<Type> getLevelTwoTypeList(int id) { TypePoExample example = new TypePoExample(); example.createCriteria() .andLevelEqualTo(EType.LevelTwo.getIndex()) .andParentidEqualTo(id); example.setOrderByClause("id asc"); return this.getTypeList(example); } public List<Type> getLevelTypeList() { TypePoExample example = new TypePoExample(); return this.getTypeList(example); } public List<Type> getLevelOneTypeList() { TypePoExample example = new TypePoExample(); example.createCriteria().andLevelEqualTo(EType.LevelOne.getIndex()); example.setOrderByClause("id asc"); return this.getTypeList(example); } public List<Type> getTypeList(TypePoExample type) { List<TypePo> typePos = typePoMapper.selectByExample(type); List<Type> list = new ArrayList<Type>(); for(TypePo typePo : typePos) { list.add(new Type(typePo)); } return list; } public boolean addType(Type type) { logger.info("addtype"+type.getName()); TypePo typePo = new TypePo(); typePo.setName(type.getName()); typePo.setParentid(type.getParentid()); typePo.setDescription(type.getDescription()); typePo.setLevel(type.getLevel()); try { this.typePoMapper.insert(typePo); logger.info("add success"); } catch (Exception e) { logger.info("add type false",e); return false; } return true; } private boolean validDfGroupTypeForAdd(DfGroupType dfGroupType) { if(dfGroupType.getGroupid() == null || dfGroupType.getGroupid() <= 0) { return false; } else if (dfGroupType.getTypeid() == null || dfGroupType.getTypeid() <= 0) { return false; } return true; } public boolean addTypeGroup(DfGroupType dfGroupType) { logger.info("add typegroup" + dfGroupType); if(!this.validDfGroupTypeForAdd(dfGroupType)) { return false; } DfGroupTypePo po = new DfGroupTypePo(); po.setGroupid(dfGroupType.getGroupid()); po.setTypeid(dfGroupType.getTypeid()); try{ this.dfGroupTypePoMapper.insert(po); }catch (Exception e) { logger.warn("add typegroup faiil"+dfGroupType, e); return false; } return true; } }
package io.fabiandev.validator; import io.fabiandev.validator.support.StringHelper; import org.junit.Test; import static org.junit.Assert.*; public class StringHelperTest { @Test public void testSplit() { String str = "some.value"; String[] parts = StringHelper.split(str, "."); assertEquals(2, parts.length); assertEquals("some", parts[0]); assertEquals("value", parts[1]); } @Test public void testSplitStringWithoutDelimiter() { String str = "some"; String[] parts = StringHelper.split(str, "."); assertEquals(1, parts.length); assertEquals("some", parts[0]); } @Test public void testCamelToSnakeCase() { String str1 = "SomeCamelCaseString"; String str2 = "String"; String str3 = "string"; String str4 = "someString"; String str5 = "some_string"; String str6 = "some_String"; String str7 = "StringWithNumber1"; String snakeCase1 = StringHelper.camelToSnakeCase(str1); String snakeCase2 = StringHelper.camelToSnakeCase(str2); String snakeCase3 = StringHelper.camelToSnakeCase(str3); String snakeCase4 = StringHelper.camelToSnakeCase(str4); String snakeCase5 = StringHelper.camelToSnakeCase(str5); String snakeCase6 = StringHelper.camelToSnakeCase(str6); String snakeCase7 = StringHelper.camelToSnakeCase(str7); assertEquals("some_camel_case_string", snakeCase1); assertEquals("string", snakeCase2); assertEquals("string", snakeCase3); assertEquals("some_string", snakeCase4); assertEquals("some_string", snakeCase5); assertEquals("some__string", snakeCase6); assertEquals("string_with_number1", snakeCase7); } }
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations; import org.giddap.dreamfactory.leetcode.onlinejudge.RemoveDuplicatesFromSortedArrayII; /** * 弼馬溫注解: * <ul> * <li>Time complexity: O(n)</li> * <li>Space complexity: O(1)</li> * <li>Use two pointers: * <ul> * <li>fast: points to the next element.</li> * <li>slow: points to the last verified element</li> * <li>Extra condition to satisfy 'at most twice'.</li> * </ul> * </li> * <li>Thought Process: Let's start with a simpler case - no duplicate is * allowed. We then build up the more complicated case on top of the simpler * case. * </li> * <li> * <pre> * if ((A[j] != A[i]) || (i == 0) || (A[i] != A[i - 1])) { * A[++i] = A[j]; * } * </pre> * </li> * </ul> */ public class RemoveDuplicatesFromSortedArrayIIImpl implements RemoveDuplicatesFromSortedArrayII { @Override public int removeDuplicates(int[] A) { final int len = A.length; if (len <= 2) { return len; } int i = 2; for (int j = 2; j < len; j++) { if (A[j] != A[i - 1] || A[j] != A[i - 2]) { A[i] = A[j]; i++; } } return i; } }
package com.zym.blog.service.impl; import com.github.pagehelper.PageHelper; import com.zym.blog.dao.AdminDao; import com.zym.blog.form.AdminForm; import com.zym.blog.model.Admin; import com.zym.blog.model.example.AdminExample; import com.zym.blog.service.AdminService; import com.zym.blog.utils.StringUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author Gavin * @date 2016-10-14 */ @Service("adminService") public class AdminServiceImpl implements AdminService { @Autowired private AdminDao adminDao; @Override public Admin getByLoginName(String loginName) { AdminExample example = new AdminExample(); AdminExample.Criteria criteria = example.createCriteria(); criteria.andLoginNameEqualTo(loginName); List<Admin> admins = adminDao.selectByExample(example); if (admins != null && admins.size() > 0) { return admins.get(0); } return null; } @Override public List<Admin> getByForm(AdminForm form, Integer page, Integer perPage) { AdminExample example = new AdminExample(); AdminExample.Criteria criteria = example.createCriteria(); if (form.getAdminId() != null && form.getAdminId() > 0) { criteria.andAdminIdNotEqualTo(form.getAdminId()); } if (!StringUtil.isEmpty(form.getLoginName())) { criteria.andLoginNameLike(form.getLoginName()); } if (form.getStatus() != null) { criteria.andStatusEqualTo(form.getStatus()); } if (!StringUtil.isEmpty(form.getPhone())) { criteria.andPhoneLike(form.getPhone()); } if (!StringUtil.isEmpty(form.getEmail())) { criteria.andEmailLike(form.getEmail()); } if (!StringUtil.isEmpty(form.getNickName())) { criteria.andNickNameLike(form.getNickName()); } PageHelper.startPage(page, perPage); return adminDao.selectByExample(example); } @Override public int insert(Admin admin) { return adminDao.insert(admin); } @Override public int deleteByPrimaryKey(int adminId) { return adminDao.deleteByPrimaryKey(adminId); } @Override public int updateByPrimaryKey(Admin record) { return adminDao.updateByPrimaryKey(record); } }
package org.squonk.execution.steps.impl; import org.squonk.types.MoleculeObject; import org.apache.camel.CamelContext; import org.squonk.camel.util.CamelUtils; import org.squonk.dataset.Dataset; import org.squonk.execution.steps.AbstractStep; import org.squonk.execution.steps.StepDefinitionConstants; import org.squonk.execution.variable.VariableManager; import org.squonk.types.io.JsonHandler; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; /** * Reads a Dataset and sends it to a service, writing the results without caring what type they are. Typically used when * needing to convert to a specific format needed by the next step. e.g. converting molecules to SDF. * * @author timbo */ public class DatasetServiceExecutorStep extends AbstractStep { private static final Logger LOG = Logger.getLogger(DatasetServiceExecutorStep.class.getName()); public static final String OPTION_SERVICE_ENDPOINT = StepDefinitionConstants.OPTION_SERVICE_ENDPOINT; public static final String VAR_INPUT_DATASET = StepDefinitionConstants.VARIABLE_INPUT_DATASET; public static final String VAR_OUTPUT_DATASET = StepDefinitionConstants.VARIABLE_OUTPUT_DATASET; @Override public void execute(VariableManager varman, CamelContext context) throws Exception { statusMessage = MSG_PREPARING_INPUT; Dataset<MoleculeObject> dataset = fetchMappedInput(VAR_INPUT_DATASET, Dataset.class, varman); String endpoint = getOption(OPTION_SERVICE_ENDPOINT, String.class); InputStream is = JsonHandler.getInstance().marshalStreamToJsonArray(dataset.getStream(), false); // String inputData = IOUtils.convertStreamToString(input); // LOG.info("Input: " + inputData); // input = new ByteArrayInputStream(inputData.getBytes()); Map<String, Object> requestHeaders = new HashMap<>(); requestHeaders.put("Accept-Encoding", "gzip"); // NOTE: setting the Content-Encoding will cause camel to gzip the data, we don't need to do it requestHeaders.put("Content-Encoding", "gzip"); // send for execution statusMessage = "Posting request ..."; Map<String, Object> responseHeaders = new HashMap<>(); InputStream output = CamelUtils.doRequestUsingHeadersAndQueryParams(context, "POST", endpoint, is, requestHeaders, responseHeaders, options); statusMessage = "Handling results ..."; // String data = IOUtils.convertStreamToString(IOUtils.getGunzippedInputStream(output), 1000); // LOG.info("Results: " + data); // output = new ByteArrayInputStream(data.getBytes()); createMappedOutput(VAR_OUTPUT_DATASET, InputStream.class, output, varman); statusMessage = generateStatusMessage(dataset.getSize(), -1, -1); } }
package com.needii.dashboard.service; import com.needii.dashboard.model.PaymentShippersHistories; import java.util.Date; import java.util.List; public interface PaymentShippersHistoriesService { List<PaymentShippersHistories> findAll(); List<PaymentShippersHistories> findAllDateMonthYear(Long shippersId, Date from, Date to); List<PaymentShippersHistories> findAllRevenueExpenditure(Long customerId, int revenueExpenditure); PaymentShippersHistories findOne(int id); PaymentShippersHistories findOneOrderCode(String orderCode); void create(PaymentShippersHistories entity); void update(PaymentShippersHistories entity); void delete(PaymentShippersHistories entity); }
package be.openclinic.datacenter; import java.io.ByteArrayInputStream; import java.text.SimpleDateFormat; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class AckMessage extends DatacenterMessage { public AckMessage(String xml){ SAXReader reader = new SAXReader(false); try { Document document = reader.read(new ByteArrayInputStream(xml.getBytes("UTF-8"))); Element root = document.getRootElement(); Element data = root.element("data"); if(data!=null){ setServerId(Integer.parseInt(data.attributeValue("serverid"))); setObjectId(Integer.parseInt(data.attributeValue("objectid"))); setAckDateTime(new SimpleDateFormat("yyyyMMddHHmmss").parse(data.attributeValue("ackdatetime"))); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public AckMessage(Element data){ SAXReader reader = new SAXReader(false); try { if(data!=null){ setServerId(Integer.parseInt(data.attributeValue("serverid"))); setObjectId(Integer.parseInt(data.attributeValue("objectid"))); setAckDateTime(new SimpleDateFormat("yyyyMMddHHmmss").parse(data.attributeValue("ackdatetime"))); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.flipmart.data; import java.util.ArrayList; import java.util.List; import com.flipmart.model.Customer; import com.flipmart.model.Order; import com.flipmart.model.Item; public class Data { private static Data data = null; List<Item> itemList; List<Customer> customerList; List<Order> orderList; Data() { itemList = new ArrayList<Item>(); customerList = new ArrayList<Customer>(); orderList = new ArrayList<Order>(); } public static Data get() { if(data != null) return data; data = new Data(); return data; } public List<Item> getItemList() { return itemList; } public List<Customer> getCustomerList() { return customerList; } public List<Order> getOrderList() { return orderList; } }
package com.forfinance.web.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.forfinance.dto.CustomerDTO; import com.forfinance.dto.HistoryDTO; import com.forfinance.dto.OrderDTO; import com.forfinance.web.controller.validator.CustomerValidator; import com.forfinance.web.service.MainApplicationService; import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc; import com.jayway.restassured.module.mockmvc.response.MockMvcResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.beans.factory.annotation.Autowired; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.given; import static junit.framework.TestCase.assertEquals; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; @RunWith(MockitoJUnitRunner.class) public class MainControllerMockRestTest { @Mock @SuppressWarnings("unused") private MainApplicationService applicationService; @InjectMocks @SuppressWarnings("unused") private MainController mainController; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); RestAssuredMockMvc.standaloneSetup(mainController); } @Test public void getCustomers() throws Exception { List<CustomerDTO> dtoList = new ArrayList<>(); CustomerDTO customerDTO = new CustomerDTO(); customerDTO.setId(111L); customerDTO.setFirstName("Aaa"); customerDTO.setLastName("Bbb"); customerDTO.setCode("qwerty"); dtoList.add(customerDTO); Mockito.doReturn(dtoList).when(applicationService).getCustomers(); MockMvcResponse res = given().when().get("/customers"); ObjectMapper objectMapper = new ObjectMapper(); CustomerDTO[] array = objectMapper.readValue(res.asString(), CustomerDTO[].class); assertEquals(1, array.length); assertEquals(Long.valueOf(111), array[0].getId()); assertEquals("Aaa", array[0].getFirstName()); assertEquals("Bbb", array[0].getLastName()); assertEquals("qwerty", array[0].getCode()); } @Test public void getCustomer() { CustomerDTO customerDTO = new CustomerDTO(); customerDTO.setId(111L); customerDTO.setFirstName("Aaa"); customerDTO.setLastName("Bbb"); customerDTO.setCode("qwerty"); Mockito.doReturn(customerDTO).when(applicationService).getCustomer(111L); given(). when(). get("/customer/111"). then(). statusCode(200). body("id", equalTo(111)). body("firstName", equalTo("Aaa")). body("lastName", equalTo("Bbb")). body("code", equalTo("qwerty")); } @Test public void createCustomer() throws Exception { CustomerValidator customerValidator = new CustomerValidator(); injectService(mainController, customerValidator, "customerValidator", Autowired.class); CustomerDTO customerDTO = new CustomerDTO(); customerDTO.setId(111L); customerDTO.setFirstName("Aaa"); customerDTO.setLastName("Bbb"); customerDTO.setCode("qwerty"); Mockito.doReturn(customerDTO).when(applicationService).createCustomer(Mockito.any(CustomerDTO.class)); given().param("firstName", "A").param("lastName", "B").param("code", "100"). when(). post("/customer"). then(). statusCode(201). body("id", equalTo(111)). body("firstName", equalTo("Aaa")). body("lastName", equalTo("Bbb")). body("code", equalTo("qwerty")); } @Test public void getCustomerHistory() { HistoryDTO customerHistory = new HistoryDTO(); CustomerDTO customerDTO = new CustomerDTO(); customerDTO.setId(111L); customerHistory.setCustomer(customerDTO); OrderDTO orderDTO_1 = new OrderDTO(); orderDTO_1.setId(222L); customerHistory.getOrders().add(orderDTO_1); OrderDTO orderDTO_2 = new OrderDTO(); orderDTO_2.setId(333L); customerHistory.getOrders().add(orderDTO_2); Mockito.doReturn(customerHistory).when(applicationService).getCustomerHistory(Long.valueOf("111")); given(). when(). get("/customer/111/history"). then(). statusCode(200). body("customer.id", equalTo(111)). body("orders.id", hasItems(222, 333)); } void injectService(Object container, Object service, String serviceName, Class<? extends Annotation> annotationClass) throws Exception { Set<Field> autoWiredFields = new HashSet<>(); Field[] fields = container.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(annotationClass)) { autoWiredFields.add(field); } } for (Field field : autoWiredFields) { String fieldName = field.getName(); if (serviceName.equals(fieldName)) { field.setAccessible(true); field.set(container, service); } } } }
package RestMethod; import com.fasterxml.jackson.core.JsonProcessingException; import PojoPayload.ObjectMapperCustom; import TestingCommon.BaseUrl; import TestingCommon.BookBaseTest; import TestingCommon.RestFWLogger; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; public class CommonRestMethod { public Response getRequest(String requestURI) { RestFWLogger.info("Base URL is - " + BookBaseTest.getBaseURL()); RestFWLogger.info("Resouce path is - " + requestURI); RequestSpecification requestSpecification = RestAssured.given(); requestSpecification.contentType(ContentType.JSON); Response response = requestSpecification.get(BookBaseTest.getBaseURL(requestURI)); RestFWLogger.info("Response is - " + response.getBody().asString()); return response; } public Response getRequestWithToken(String requestURI, String bearerToken) { RestFWLogger.info("Base URL is - " + BookBaseTest.getBaseURL()); RestFWLogger.info("Resouce path is - " + requestURI); RequestSpecification requestSpecification = RestAssured.given(); requestSpecification.contentType(ContentType.JSON); requestSpecification.header("Authorization", "Bearer " + bearerToken); Response response = requestSpecification.get(BookBaseTest.getBaseURL(requestURI)); RestFWLogger.info("Response is - " + response.getBody().asString()); return response; } public Response postRequest(String requestURI, Object requestPayLoad) throws JsonProcessingException { RestFWLogger.info("Base URL is - " + BookBaseTest.getBaseURL()); RestFWLogger.info("Resouce path is - " + requestURI); RestFWLogger.info("Request payload is - " + ObjectMapperCustom.ObjectMapper(requestPayLoad)); RequestSpecification requestSpecification = RestAssured.given().body(requestPayLoad); requestSpecification.contentType(ContentType.JSON); Response response = requestSpecification.post(BookBaseTest.getBaseURL(requestURI)); RestFWLogger.info("Response is - " + response.getBody().asString()); return response; } public Response postRequest(String requestURI, Object requestPayLoad, String bearerToken) throws JsonProcessingException { RestFWLogger.info("Base URL is - " + BookBaseTest.getBaseURL()); RestFWLogger.info("Resouce path is - " + requestURI); RestFWLogger.info("Request payload is - " + ObjectMapperCustom.ObjectMapper(requestPayLoad)); RequestSpecification requestSpecification = RestAssured.given().body(requestPayLoad); requestSpecification.contentType(ContentType.JSON); requestSpecification.header("Authorization", "Bearer " + bearerToken); Response response = requestSpecification.post(BookBaseTest.getBaseURL(requestURI)); RestFWLogger.info("Resouce path is - " + response.getBody().asString()); return response; } public Response putRequest(String requestURI, String requestPayLoad) { RequestSpecification requestSpecification = RestAssured.given().body(requestPayLoad); requestSpecification.contentType(ContentType.JSON); Response response = requestSpecification.put(requestURI); return response; } public Response deleteRequest(String requestURI) { RequestSpecification requestSpecification = RestAssured.given(); requestSpecification.contentType(ContentType.JSON); Response response = requestSpecification.delete(requestURI); return response; } public Response deleteRequestWithPayload(String requestURI, String requestPayLoad) { RequestSpecification requestSpecification = RestAssured.given().body(requestPayLoad); requestSpecification.contentType(ContentType.JSON); Response response = requestSpecification.delete(requestURI); return response; } public Response deleteRequest(String requestURI, String bearerToken) { RestFWLogger.info("Base URL is - " + BaseUrl.getBaseURL()); RestFWLogger.info("Resouce path is - " + requestURI); RequestSpecification requestSpecification = RestAssured.given(); requestSpecification.contentType(ContentType.JSON); requestSpecification.header("Authorization", "Bearer " + bearerToken); Response response = requestSpecification.delete(BaseUrl.getBaseURL(requestURI)); return response; } public Response deleteRequestWithPayload(String requestURI, Object requestPayLoad, String bearerToken) throws JsonProcessingException { RestFWLogger.info("Base URL is - " + BaseUrl.getBaseURL()); RestFWLogger.info("Resouce path is - " + requestURI); RestFWLogger.info("Request payload is - " + ObjectMapperCustom.ObjectMapper(requestPayLoad)); RequestSpecification requestSpecification = RestAssured.given().body(requestPayLoad); requestSpecification.contentType(ContentType.JSON); requestSpecification.header("Authorization", "Bearer " + bearerToken); Response response = requestSpecification.delete(BookBaseTest.getBaseURL(requestURI)); RestFWLogger.info("Response path is - " + response.getBody().asString()); return response; } }
package slimeknights.tconstruct.tools.common.item; import net.minecraft.block.Block; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import slimeknights.mantle.item.ItemBlockMeta; import slimeknights.mantle.util.LocUtils; import slimeknights.tconstruct.library.Util; import slimeknights.tconstruct.library.smeltery.ICast; import slimeknights.tconstruct.library.tools.IPattern; import slimeknights.tconstruct.library.utils.TagUtil; import slimeknights.tconstruct.shared.tileentity.TileTable; import slimeknights.tconstruct.tools.common.block.BlockToolTable; public class ItemBlockTable extends ItemBlockMeta { public ItemBlockTable(Block block) { super(block); } @Override public void addInformation(@Nonnull ItemStack stack, @Nullable World worldIn, @Nonnull List<String> tooltip, ITooltipFlag flagIn) { super.addInformation(stack, worldIn, tooltip, flagIn); if(!stack.hasTagCompound()) { return; } ItemStack legs = getLegStack(stack); if(!legs.isEmpty()) { tooltip.add(legs.getDisplayName()); } if(stack.getTagCompound().hasKey("inventory")) { this.addInventoryInformation(stack, worldIn, tooltip, flagIn); } } /** * Gets the itemstack that determines the leg's texture from the table * @param table Input table * @return The itemstack determining the leg's texture, or null if none exists */ public static ItemStack getLegStack(ItemStack table) { NBTTagCompound tag = TagUtil.getTagSafe(table).getCompoundTag(TileTable.FEET_TAG); return new ItemStack(tag); } protected void addInventoryInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { // get the inventory, so we can inspect its items NBTTagCompound inventory = stack.getTagCompound().getCompoundTag("inventory"); if(!inventory.hasKey("Items")) { return; } NBTTagList items = inventory.getTagList("Items", 10); if(items.hasNoTags()) { return; // Items tag list with no items?! } // check if it's a PatternChest (damage value corresponds to TableTypes enum) if(BlockToolTable.TableTypes.fromMeta(stack.getItemDamage()) == BlockToolTable.TableTypes.PatternChest) { // determine if it holds casts or patterns String desc = null; for(int i = 0; i < items.tagCount(); ++i) { // iterate the item stacks, until we find a valid item ItemStack inventoryStack = new ItemStack(items.getCompoundTagAt(i)); if(inventoryStack.isEmpty()) { continue; // unable to load any item for this NBT tag - assume invalid/removed item, so check next } Item item = inventoryStack.getItem(); if(item instanceof ICast || item instanceof IPattern) { desc = ((item instanceof ICast) ? "tooltip.patternchest.holds_casts" : "tooltip.patternchest.holds_patterns"); break; // found the first valid Item, break loop } } if(desc != null) { tooltip.addAll(LocUtils.getTooltips(Util.translateFormatted(desc, items.tagCount()))); } } else { // generic chest, only show count tooltip.addAll(LocUtils.getTooltips(Util.translateFormatted("tooltip.chest.has_items", items.tagCount()))); } } }
package fr.treeptik.truitter.action; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import fr.treeptik.truitter.exception.ServiceException; import fr.treeptik.truitter.model.User; import fr.treeptik.truitter.service.UserService; @Namespace("/user") public class UserAction extends ActionSupport implements ModelDriven<User> { private static final long serialVersionUID = 1L; @Autowired private UserService userService; private User user = new User(); @Override public User getModel() { return user; } @Action(value="registerLink", results={@Result(name="success", type="tiles", location="/user/register.tiles"),}) public String registerForm() { return "success"; } @Action(value="registerAction", results={ @Result(name="success", type="redirectAction", location="../message/listLink", params={"userLogin", "${user.login}"}), @Result(name="input", type="redirectAction", location="registerLink")}) public String register() throws ServiceException { userService.saveOrUpdate(user); return "success"; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }