hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
743b57adc6aaea1f656a3a1d9c09318d90bb9a77
2,330
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.vision.customvision.training.models; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * The ImageTagCreateSummary model. */ public class ImageTagCreateSummary { /** * The created property. */ @JsonProperty(value = "created") private List<ImageTagCreateEntry> created; /** * The duplicated property. */ @JsonProperty(value = "duplicated") private List<ImageTagCreateEntry> duplicated; /** * The exceeded property. */ @JsonProperty(value = "exceeded") private List<ImageTagCreateEntry> exceeded; /** * Get the created value. * * @return the created value */ public List<ImageTagCreateEntry> created() { return this.created; } /** * Set the created value. * * @param created the created value to set * @return the ImageTagCreateSummary object itself. */ public ImageTagCreateSummary withCreated(List<ImageTagCreateEntry> created) { this.created = created; return this; } /** * Get the duplicated value. * * @return the duplicated value */ public List<ImageTagCreateEntry> duplicated() { return this.duplicated; } /** * Set the duplicated value. * * @param duplicated the duplicated value to set * @return the ImageTagCreateSummary object itself. */ public ImageTagCreateSummary withDuplicated(List<ImageTagCreateEntry> duplicated) { this.duplicated = duplicated; return this; } /** * Get the exceeded value. * * @return the exceeded value */ public List<ImageTagCreateEntry> exceeded() { return this.exceeded; } /** * Set the exceeded value. * * @param exceeded the exceeded value to set * @return the ImageTagCreateSummary object itself. */ public ImageTagCreateSummary withExceeded(List<ImageTagCreateEntry> exceeded) { this.exceeded = exceeded; return this; } }
24.020619
87
0.644206
bd6f3bf64fcfd8136a469ea71364bbe1c40ea3e6
176
package net.renfei.core.entity.wechat; import lombok.Data; @Data public class Video { private String MediaId; private String Title; private String Description; }
16
38
0.738636
7e0a4c156b477741a07af286d019aa0df4b5428c
684
package org.apereo.cas; import org.apereo.cas.config.CasServicesStreamingKafkaConfigurationTests; import org.apereo.cas.services.RegisteredServiceKafkaDistributedCacheListenerTests; import org.apereo.cas.services.RegisteredServiceKafkaDistributedCacheManagerTests; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; /** * Test suite to run all tests. * * @author Misagh Moayyed * @since 6.3.0 */ @SelectClasses({ RegisteredServiceKafkaDistributedCacheManagerTests.class, RegisteredServiceKafkaDistributedCacheListenerTests.class, CasServicesStreamingKafkaConfigurationTests.class }) @Suite public class AllTestsSuite { }
28.5
83
0.828947
f86824be4b5916b0f1e966ac59e2f2ca7e8477b6
6,955
package org.apereo.cas.config; import org.apereo.cas.CentralAuthenticationService; import org.apereo.cas.audit.AuditableExecution; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.support.oauth.OAuth20Constants; import org.apereo.cas.support.oauth.web.endpoints.OAuth20AccessTokenEndpointController; import org.apereo.cas.support.oauth.web.endpoints.OAuth20AuthorizeEndpointController; import org.apereo.cas.support.oauth.web.endpoints.OAuth20CallbackAuthorizeEndpointController; import org.apereo.cas.support.oauth.web.endpoints.OAuth20ConfigurationContext; import org.apereo.cas.support.oauth.web.endpoints.OAuth20DeviceUserCodeApprovalEndpointController; import org.apereo.cas.support.oauth.web.endpoints.OAuth20IntrospectionEndpointController; import org.apereo.cas.support.oauth.web.endpoints.OAuth20RevocationEndpointController; import org.apereo.cas.support.oauth.web.endpoints.OAuth20UserProfileEndpointController; import org.apereo.cas.support.oauth.web.mgmt.OAuth20TokenManagementEndpoint; import org.apereo.cas.token.JwtBuilder; import org.apereo.cas.web.ProtocolEndpointWebSecurityConfigurer; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ScopedProxyMode; import java.util.List; /** * This this {@link CasOAuth20EndpointsConfiguration}. * * @author Misagh Moayyed * @since 6.2.0 */ @Configuration(value = "CasOAuth20EndpointsConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) public class CasOAuth20EndpointsConfiguration { @Configuration(value = "CasOAuth20EndpointControllersConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) public static class CasOAuth20EndpointControllersConfiguration { @Bean @ConditionalOnMissingBean(name = "callbackAuthorizeController") @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public OAuth20CallbackAuthorizeEndpointController callbackAuthorizeController( @Qualifier("oauth20ConfigurationContext") final OAuth20ConfigurationContext context) { return new OAuth20CallbackAuthorizeEndpointController(context); } @ConditionalOnMissingBean(name = "introspectionEndpointController") @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public OAuth20IntrospectionEndpointController<OAuth20ConfigurationContext> introspectionEndpointController( @Qualifier("oauth20ConfigurationContext") final OAuth20ConfigurationContext context) { return new OAuth20IntrospectionEndpointController<>(context); } @ConditionalOnMissingBean(name = "accessTokenController") @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public OAuth20AccessTokenEndpointController<OAuth20ConfigurationContext> accessTokenController( @Qualifier("accessTokenGrantAuditableRequestExtractor") final AuditableExecution accessTokenGrantAuditableRequestExtractor, @Qualifier("oauth20ConfigurationContext") final OAuth20ConfigurationContext context) { return new OAuth20AccessTokenEndpointController(context, accessTokenGrantAuditableRequestExtractor); } @ConditionalOnMissingBean(name = "deviceUserCodeApprovalEndpointController") @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public OAuth20DeviceUserCodeApprovalEndpointController deviceUserCodeApprovalEndpointController( @Qualifier("oauth20ConfigurationContext") final OAuth20ConfigurationContext context) { return new OAuth20DeviceUserCodeApprovalEndpointController(context); } @ConditionalOnMissingBean(name = "oauthProfileController") @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public OAuth20UserProfileEndpointController<OAuth20ConfigurationContext> oauthProfileController( @Qualifier("oauth20ConfigurationContext") final OAuth20ConfigurationContext context) { return new OAuth20UserProfileEndpointController(context); } @ConditionalOnMissingBean(name = "oauthRevocationController") @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public OAuth20RevocationEndpointController<OAuth20ConfigurationContext> oauthRevocationController( @Qualifier("oauth20ConfigurationContext") final OAuth20ConfigurationContext context) { return new OAuth20RevocationEndpointController(context); } @ConditionalOnMissingBean(name = "authorizeController") @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public OAuth20AuthorizeEndpointController<OAuth20ConfigurationContext> authorizeController( @Qualifier("oauth20ConfigurationContext") final OAuth20ConfigurationContext context) { return new OAuth20AuthorizeEndpointController(context); } @Bean @ConditionalOnAvailableEndpoint public OAuth20TokenManagementEndpoint oauth20TokenManagementEndpoint( @Qualifier("accessTokenJwtBuilder") final JwtBuilder accessTokenJwtBuilder, @Qualifier(CentralAuthenticationService.BEAN_NAME) final CentralAuthenticationService centralAuthenticationService, final CasConfigurationProperties casProperties) { return new OAuth20TokenManagementEndpoint(casProperties, centralAuthenticationService, accessTokenJwtBuilder); } } @Configuration(value = "CasOAuth20EndpointSecurityConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) public static class CasOAuth20EndpointSecurityConfiguration { @Bean @ConditionalOnMissingBean(name = "oauth20ProtocolEndpointConfigurer") public ProtocolEndpointWebSecurityConfigurer<Void> oauth20ProtocolEndpointConfigurer() { return new ProtocolEndpointWebSecurityConfigurer<>() { @Override public List<String> getIgnoredEndpoints() { return List.of(StringUtils.prependIfMissing(OAuth20Constants.BASE_OAUTH20_URL, "/")); } }; } } }
50.766423
115
0.767649
ed996ed54ebc0e0c8389a0450b0efdd32ebf24c8
5,775
package com.threepillar.labs.socialauthsample.bean; public class User { /** * Email */ private String email; /** * First Name */ private String firstName; /** * Last Name */ private String lastName; /** * Country */ private String country; /** * Language */ private String language; /** * Full Name */ private String name; /** * Display Name */ private String displayName; /** * Date of Birth */ private String dob; /** * Gender */ private String gender; /** * Location */ private String location; /** * profile image URL */ private String profileImageURL; /** * provider id with this profile associates */ private String providerId; /** * Unique id */ private String uniqueId; /** * Retrieves the first name * * @return String the first name */ public String getFirstName() { return firstName; } /** * Updates the first name * * @param firstName * the first name of user */ public void setFirstName(final String firstName) { this.firstName = firstName; } /** * Retrieves the last name * * @return String the last name */ public String getLastName() { return lastName; } /** * Updates the last name * * @param lastName * the last name of user */ public void setLastName(final String lastName) { this.lastName = lastName; } /** * Returns the email address. * * @return email address of the user */ public String getEmail() { return email; } /** * Updates the email * * @param email * the email of user */ public void setEmail(final String email) { this.email = email; } /** * Retrieves the display name * * @return String the display name */ public String getDisplayName() { return displayName; } /** * Updates the display name * * @param displayName * the display name of user */ public void setDisplayName(final String displayName) { this.displayName = displayName; } /** * Retrieves the country * * @return String the country */ public String getCountry() { return country; } /** * Updates the country * * @param country * the country of user */ public void setCountry(final String country) { this.country = country; } /** * Retrieves the language * * @return String the language */ public String getLanguage() { return language; } /** * Updates the language * * @param language * the language of user */ public void setLanguage(final String language) { this.language = language; } /** * Retrieves the full name * * @return String the full name */ public String getName() { return name; } /** * Updates the name * * @param name * the full name of user */ public void setName(final String name) { this.name = name; } /** * Retrieves the date of birth * * @return the date of birth different providers may use different formats */ public String getDob() { return dob; } /** * Updates the date of birth * * @param dob * the date of birth of user */ public void setDob(final String dob) { this.dob = dob; } /** * Retrieves the gender * * @return String the gender - could be "Male", "M" or "male" */ public String getGender() { return gender; } /** * Updates the gender * * @param gender * the gender of user */ public void setGender(final String gender) { this.gender = gender; } /** * Retrieves the location * * @return String the location */ public String getLocation() { return location; } /** * Updates the location * * @param location * the location of user */ public void setLocation(final String location) { this.location = location; } /** * Retrieves the profile image URL * * @return String the profileImageURL */ public String getProfileImageURL() { return profileImageURL; } /** * Updates the profile image URL * * @param profileImageURL * profile image URL of user */ public void setProfileImageURL(final String profileImageURL) { this.profileImageURL = profileImageURL; } /** * Retrieves the provider id with this profile associates * * @return the provider id */ public String getProviderId() { return providerId; } /** * Updates the provider id * * @param providerId * the provider id */ public void setProviderId(final String providerId) { this.providerId = providerId; } /** * Retrieves the profile info as a string * * @return String */ @Override public String toString() { StringBuilder result = new StringBuilder(); String NEW_LINE = System.getProperty("line.separator"); result.append(this.getClass().getName() + " Object {" + NEW_LINE); result.append(" email: " + email + NEW_LINE); result.append(" firstName: " + firstName + NEW_LINE); result.append(" lastName: " + lastName + NEW_LINE); result.append(" country: " + country + NEW_LINE); result.append(" language: " + language + NEW_LINE); result.append(" name: " + name + NEW_LINE); result.append(" displayName: " + displayName + NEW_LINE); result.append(" dob: " + dob + NEW_LINE); result.append(" gender: " + gender + NEW_LINE); result.append(" location: " + location + NEW_LINE); result.append(" uniqueId: " + uniqueId + NEW_LINE); result.append(" profileImageURL: " + profileImageURL + NEW_LINE); result.append(" providerId: " + providerId + NEW_LINE); result.append("}"); return result.toString(); } public String getUniqueId() { return uniqueId; } public void setUniqueId(final String uniqueId) { this.uniqueId = uniqueId; } }
17.290419
75
0.625281
2475c1e9a6b50adec9b5f67e47c04a898ed643fc
100
/** * Classes used for registering things on the client side. */ package co.uk.niadel.napi.client;
25
58
0.73
c2ff75fd436f56959a800c9ed2475f2c8b1bf4cb
692
// ********************************************************************** // This file was generated by a TARS parser! // TARS version 1.7.2. // ********************************************************************** package com.qq.tars; public enum DateType { SECONDS(0), MINIUES(1), HOUR(2), DAY(3), MONTH(4), YEAR(5); private final int value; private DateType(int value) { this.value = value; } public int value() { return this.value; } @Override public String toString() { return this.name() + ":" + this.value; } public static DateType convert(int value) { for(DateType v : values()) { if(v.value() == value) { return v; } } return null; } }
16.878049
73
0.486994
d8d32edf2a504a90222b7b8a408f0a254057cda1
1,126
package io.macrolayer.services.users; import java.util.ArrayList; import java.util.List; import org.junit.Before; import io.macrolayer.services.users.User; import io.macrolayer.services.users.UserRepository; import io.macrolayer.services.users.UsersController; public class UsersControllerTests extends AbstractUserControllerTests { protected static final User theUser = new User(USER_1, USER_1_NAME, SURNAME_1_NAME, SURNAME_2_NAME); protected static class TestUserRepository implements UserRepository { @Override public User findByNumber(String userNumber) { if (userNumber.equals(USER_1)) return theUser; else return null; } @Override public List<User> findByNameContainingIgnoreCase(String partialName) { List<User> users = new ArrayList<User>(); if (USER_1_NAME.toLowerCase().indexOf(partialName.toLowerCase()) != -1) users.add(theUser); return users; } @Override public int countUsers() { return 1; } } protected TestUserRepository testRepo = new TestUserRepository(); @Before public void setup() { userController = new UsersController(testRepo); } }
22.979592
101
0.759325
4948f2f4d67b942e9b9dee6f359fe24449485d40
8,421
/** * @PROJECT.FULLNAME@ @VERSION@ License. * * Copyright @YEAR@ L2FProd.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.l2fprod.common.swing.plaf.basic; import com.l2fprod.common.swing.JFontChooser; import com.l2fprod.common.swing.LookAndFeelTweaks; import com.l2fprod.common.swing.PercentLayout; import com.l2fprod.common.swing.plaf.FontChooserUI; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.font.TextAttribute; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.plaf.ComponentUI; /** * BasicFontChooserUI. <br> * */ public class BasicFontChooserUI extends FontChooserUI { public static ComponentUI createUI(JComponent component) { return new BasicFontChooserUI(); } private JFontChooser chooser; private JPanel fontPanel; private JTextField fontField; private JList fontList; private JPanel fontSizePanel; private JTextField fontSizeField; private JList fontSizeList; private JCheckBox boldCheck; private JCheckBox italicCheck; private JTextArea previewPanel; private PropertyChangeListener propertyListener; public void installUI(JComponent c) { super.installUI(c); chooser = (JFontChooser)c; installComponents(); installListeners(); } protected void installComponents() { JLabel label; ResourceBundle bundle = ResourceBundle.getBundle(FontChooserUI.class.getName() + "RB"); fontPanel = new JPanel(new PercentLayout(PercentLayout.VERTICAL, 2)); fontPanel.add( label = new JLabel(bundle.getString("FontChooserUI.fontLabel"))); fontPanel.add(fontField = new JTextField(25)); fontField.setEditable(false); fontPanel.add(new JScrollPane(fontList = new JList()), "*"); label.setLabelFor(fontList); label.setDisplayedMnemonic( bundle.getString("FontChooserUI.fontLabel.mnemonic").charAt(0)); fontList.setVisibleRowCount(7); fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); String[] fontFamilies = chooser.getModel().getFontFamilies(null); fontList.setListData(fontFamilies); fontSizePanel = new JPanel(new PercentLayout(PercentLayout.VERTICAL, 2)); fontSizePanel.add( label = new JLabel(bundle.getString("FontChooserUI.styleLabel"))); fontSizePanel.add( boldCheck = new JCheckBox(bundle.getString("FontChooserUI.style.bold"))); fontSizePanel.add( italicCheck = new JCheckBox(bundle.getString("FontChooserUI.style.italic"))); boldCheck.setMnemonic( bundle.getString("FontChooserUI.style.bold.mnemonic").charAt(0)); italicCheck.setMnemonic( bundle.getString("FontChooserUI.style.italic.mnemonic").charAt(0)); fontSizePanel.add( label = new JLabel(bundle.getString("FontChooserUI.sizeLabel"))); label.setDisplayedMnemonic( bundle.getString("FontChooserUI.sizeLabel.mnemonic").charAt(0)); fontSizePanel.add(fontSizeField = new JTextField()); label.setLabelFor(fontSizeField); fontSizePanel.add(new JScrollPane(fontSizeList = new JList()), "*"); int[] defaultFontSizes = chooser.getModel().getDefaultSizes(); String[] sizes = new String[defaultFontSizes.length]; for (int i = 0, c = sizes.length; i < c; i++) { sizes[i] = String.valueOf(defaultFontSizes[i]); } fontSizeList.setListData(sizes); fontSizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontSizeList.setVisibleRowCount(2); chooser.setLayout(LookAndFeelTweaks.createBorderLayout()); JPanel panel = new JPanel(); panel.setLayout(LookAndFeelTweaks.createHorizontalPercentLayout()); panel.add(fontPanel, "*"); panel.add(fontSizePanel); chooser.add("Center", panel); previewPanel = new JTextArea(); previewPanel.setPreferredSize(new Dimension(100, 40)); previewPanel.setText(chooser.getModel().getPreviewMessage(null)); JScrollPane scroll = new JScrollPane(previewPanel); chooser.add("South", scroll); } protected void installListeners() { SelectedFontUpdater listener = new SelectedFontUpdater(); fontList.addListSelectionListener(listener); fontSizeList.addListSelectionListener(listener); fontSizeField.getDocument().addDocumentListener(listener); boldCheck.addActionListener(listener); italicCheck.addActionListener(listener); propertyListener = createPropertyChangeListener(); chooser.addPropertyChangeListener( JFontChooser.SELECTED_FONT_CHANGED_KEY, propertyListener); } public void uninstallUI(JComponent c) { chooser.remove(fontPanel); chooser.remove(fontSizePanel); super.uninstallUI(c); } public void uninstallListeners() { chooser.removePropertyChangeListener(propertyListener); } protected PropertyChangeListener createPropertyChangeListener() { return new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { updateDisplay(); } }; } private void updateDisplay() { Font selected = chooser.getSelectedFont(); if (selected != null) { previewPanel.setFont(selected); fontList.setSelectedValue(selected.getName(), true); fontSizeField.setText(String.valueOf(selected.getSize())); fontSizeList.setSelectedValue(String.valueOf(selected.getSize()), true); boldCheck.setSelected(selected.isBold()); italicCheck.setSelected(selected.isItalic()); } } private void updateSelectedFont() { Font currentFont = chooser.getSelectedFont(); String fontFamily = currentFont == null ? "SansSerif" : currentFont.getName(); int fontSize = currentFont == null ? 11 : currentFont.getSize(); if (fontList.getSelectedIndex() >= 0) { fontFamily = (String)fontList.getSelectedValue(); } if (fontSizeField.getText().trim().length() > 0) { try { fontSize = Integer.parseInt(fontSizeField.getText().trim()); } catch (Exception e) { // ignore the NumberFormatException } } Map attributes = new HashMap(); attributes.put(TextAttribute.SIZE, new Float(fontSize)); attributes.put(TextAttribute.FAMILY, fontFamily); if (boldCheck.isSelected()) { attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); } if (italicCheck.isSelected()) { attributes.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE); } Font font = Font.getFont(attributes); if (!font.equals(currentFont)) { chooser.setSelectedFont(font); previewPanel.setFont(font); } } private class SelectedFontUpdater implements ListSelectionListener, DocumentListener, ActionListener { public void valueChanged(ListSelectionEvent e) { if (fontList == e.getSource() && fontList.getSelectedValue() != null) { fontField.setText((String)fontList.getSelectedValue()); } if (fontSizeList == e.getSource() && fontSizeList.getSelectedValue() != null) { fontSizeField.setText((String)fontSizeList.getSelectedValue()); } updateSelectedFont(); } public void changedUpdate(DocumentEvent e) { updateLater(); } public void insertUpdate(DocumentEvent e) { updateLater(); } public void removeUpdate(DocumentEvent e) { updateLater(); } public void actionPerformed(ActionEvent e) { updateLater(); } void updateLater() { SwingUtilities.invokeLater(new Runnable() { public void run() { updateSelectedFont(); } }); } } }
32.264368
79
0.718323
c587f359246f1c98956608227395bad535ed7533
2,110
/* * Copyright (c) 2018-2025, baba 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 the pig4cloud.com developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: baba (wzysz888@gmail.com) */ package com.ygg.baba.app.config; import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; /** * @author baba * @date 2017/10/29 */ @Configuration @MapperScan("com.ygg.baba.app.mapper") public class MybatisPlusConfig { /** * 分页插件 * * @return PaginationInterceptor */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } /** * 乐观锁插件 * * @return OptimisticLockerInterceptor */ @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } @Bean @Profile({"dev", "test"}) public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor interceptor = new PerformanceInterceptor(); interceptor.setFormat(true); interceptor.setMaxTime(1000); return interceptor; } }
32.461538
78
0.746919
1df8248d00efde4695e9d5850479e5067091ae44
2,492
package com.github.curiousoddman.rgxgen.parsing.dflt; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Collection; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeThat; @RunWith(Parameterized.class) public class CharIteratorContextTests { private static Stream<Object[]> shorterContext() { String inputText = "01234"; return IntStream.rangeClosed(1, inputText.length()) .mapToObj(i -> new Object[]{inputText, i}); } private static Stream<Object[]> longerContext() { String inputText = "0123456789ABCDEF"; return IntStream.rangeClosed(1, inputText.length()) .mapToObj(i -> new Object[]{inputText, i}); } @Parameterized.Parameters(name = "{0}:{1}") public static Collection<Object[]> data() { return Stream.concat(shorterContext(), longerContext()) .collect(Collectors.toList()); } @Parameterized.Parameter public String aInitialText; @Parameterized.Parameter(1) public int aOffset; @Test public void verifyContextTest() { CharIterator iterator = new CharIterator(aInitialText); iterator.skip(aOffset); String context = iterator.context(); String[] split = context.split("\n"); assertEquals("", split[0]); int i = split[2].indexOf('^'); // -1 because actual context is taken from previous symbol, not from actual at index, but previous. assertEquals(String.format("%X", aOffset - 1), split[1].substring(i, i + 1)); } @Test public void verifyContextWithPosTest() { assumeThat(aOffset, not(aInitialText.length())); CharIterator iterator = new CharIterator(aInitialText); String context = iterator.context(aOffset); String[] split = context.split("\n"); assertEquals("", split[0]); int i = split[2].indexOf('^'); // -1 for the ' at the start of previous line assertEquals(String.format("%X", aOffset), split[1].substring(i, i + 1)); } @Test public void verifyPos() { CharIterator iterator = new CharIterator(aInitialText); iterator.skip(aOffset); assertEquals(aOffset - 1, iterator.prevPos()); } }
34.136986
107
0.649679
4110481e808905e4359252d93f939ace82fcb13c
3,466
/** * Copyright (c) 2019,2020 honintech * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package cn.weforward.data.jdbc; /** * Copyright (c) 2019,2020 honintech * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ import java.sql.Connection; import java.sql.SQLException; import org.slf4j.LoggerFactory; /** * JDBC数据库连接池接口 * * @author liangyi * */ public interface ConnectionPool { /** * 日志记录器 */ public final static org.slf4j.Logger _Logger = LoggerFactory.getLogger(ConnectionPool.class); /** * 是否允许trace,通常写法 * * <pre> * if(Pool._TraceEnabled){ * Pool._Logger.trace(...); * } * </pre> */ public final static boolean _TraceEnabled = _Logger.isTraceEnabled(); public final static boolean _DebugEnabled = _Logger.isDebugEnabled(); public final static boolean _InfoEnabled = _Logger.isInfoEnabled(); public final static boolean _WarnEnabled = _Logger.isWarnEnabled(); /** * 由池获取连接 * * @return 数据库连接 * @throws SQLException 数据库异常 */ Connection getConnection() throws SQLException; /** * 释放由池取得的数据库连接回池 * * @param conn 由池取得的数据库连接 */ void freeConnection(Connection conn); /** * 在非业务性异常发生时,使用其代替freeConnection释放由池取得的数据库连接回池,以检查连接的可靠性 * * @param conn 由池取得的数据库连接 */ void freeConnectionAtException(Connection conn); /** * 关闭连接池中所有连接(清空连接池) */ void freeAllConnections(); /** * 获取连接的详情 * * @param conn 数据库连接 * @return 关于此连接的状态描述 */ String getConnectionDetail(Connection conn); }
39.386364
463
0.750144
3d3a22df1f530e5b50398be49a199e50d3b45009
4,782
/* * www.javagl.de - Selection - A generic selection model * * Copyright (c) 2013-2015 Marco Hutter - http://www.javagl.de * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package de.javagl.selection; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; /** * Default implementation of a {@link SelectionModel} * * @param <T> The type of the elements in this selection */ class DefaultSelectionModel<T> extends AbstractSelectionModel<T> { /** * The selection */ private final Set<T> selection; /** * The unmodifiable view on the selection */ private final Set<T> selectionView; /** * Default constructor */ DefaultSelectionModel() { this.selection = new LinkedHashSet<T>(); this.selectionView = Collections.unmodifiableSet(selection); } @Override public void addToSelection(T element) { boolean changed = selection.add(element); if (changed) { fireSelectionChanged(element, null); } } @Override public void removeFromSelection(T element) { boolean changed = selection.remove(element); if (changed) { fireSelectionChanged(null, element); } } @Override public void addToSelection(Collection<? extends T> elements) { Set<T> addedElements = new LinkedHashSet<T>(); for (T element : elements) { boolean wasAdded = selection.add(element); if (wasAdded) { addedElements.add(element); } } if (!addedElements.isEmpty()) { fireSelectionChanged( Collections.unmodifiableSet(addedElements), null); } } @Override public void removeFromSelection(Collection<? extends T> elements) { Set<T> removedElements = new LinkedHashSet<T>(); for (T element : elements) { boolean wasRemoved = selection.remove(element); if (wasRemoved) { removedElements.add(element); } } if (!removedElements.isEmpty()) { fireSelectionChanged( null, Collections.unmodifiableSet(removedElements)); } } @Override public void setSelection(Collection<? extends T> elements) { if (!selection.equals(elements)) { Set<T> removedElements = new LinkedHashSet<T>(selection); Set<T> addedElements = new LinkedHashSet<T>(elements); removedElements.removeAll(addedElements); addedElements.removeAll(selection); selection.clear(); selection.addAll(elements); if (!addedElements.isEmpty() || !removedElements.isEmpty()) { fireSelectionChanged( Collections.unmodifiableSet(addedElements), Collections.unmodifiableSet(removedElements)); } } } @Override public void clear() { if (!selection.isEmpty()) { Set<T> removedElements = new LinkedHashSet<T>(selection); selection.clear(); fireSelectionChanged(null, removedElements); } } @Override public boolean isSelected(T element) { return selection.contains(element); } @Override public Set<T> getSelection() { return selectionView; } }
29.518519
72
0.594521
4527880f92e974cb7a6a26618f4ab60472b7d2b0
2,143
package org.media.container.merge.io; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; /** * Byte output stream with a constant size. If the bytes to write exceed capacity, only the trailing part is kept. */ public class ByteBufferOutputStream extends OutputStream { //================================================================================================================== // Attributes //================================================================================================================== private final ByteBuffer buffer; //================================================================================================================== // Constructors //================================================================================================================== public ByteBufferOutputStream(int capacity) { this.buffer = ByteBuffer.allocate(capacity); } //================================================================================================================== // Public methods //================================================================================================================== @Override public void write(int b) throws IOException { if ( buffer.position() == buffer.capacity() ) { buffer.position(1); buffer.compact(); } buffer.put((byte) b); } @SuppressWarnings("NullableProblems") @Override public void write(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } final int actualLen = Math.min(len, buffer.capacity()); if ( buffer.position() + actualLen > buffer.capacity() ) { buffer.position(actualLen); buffer.compact(); } buffer.put(b, off + (len - actualLen), actualLen); } @Override public String toString() { return new String(buffer.array(), 0, buffer.position()); } @Override public void close() throws IOException { } }
32.469697
117
0.45357
5dea451b75033cd9700fec367c89717568958c2e
5,002
package com.webcheckers.model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Unit Tests for {@link Game} Component * @author Sasha Persaud, Shubhang Mehrotra, Quynh Duong */ @Tag("Model-tier") public class GameTest { // Component under test private Game CuT; // Friendlies private Player redPlayer; private Player whitePlayer; private String id; private BoardView whiteView; private BoardView redView; private Game.ActiveColor activeColor; @BeforeEach private void setUp(){ redPlayer = mock(Player.class); whitePlayer = mock(Player.class); // redView = mock(BoardView.class); // whiteView = mock(BoardView.class); id = "1234"; activeColor = Game.ActiveColor.RED; } @Test public void testCreateGame(){ // Invoke CuT = new Game(id,redPlayer, whitePlayer); // Analyze assertNotNull(CuT); } @Test public void testGetRedPlayer(){ // Invoke CuT = new Game(id,redPlayer, whitePlayer); Player testPlayer = CuT.getRedPlayer(); // Analyze assertEquals(redPlayer, testPlayer); } @Test public void testGetWhiteView(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); whiteView = CuT.getWhiteView(); // Analyze assertEquals(CuT.getWhiteView(), whiteView); } @Test public void testGetId(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); String testID = CuT.getId(); // Analyze assertEquals(id, testID); } @Test public void testGameAbandoned(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); redPlayer.exitGame(); whitePlayer.exitGame(); //analyze assertTrue(CuT.isGameAbandoned()); } @Test public void testGameNotAbandoned(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); when(redPlayer.isPlayingWith(whitePlayer)).thenReturn(false); when(whitePlayer.isPlayingWith(redPlayer)).thenReturn(true); //analyze assertFalse(CuT.isGameAbandoned()); } @Test public void testGameNotAbandoned2(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); when(redPlayer.isPlayingWith(whitePlayer)).thenReturn(true); when(whitePlayer.isPlayingWith(redPlayer)).thenReturn(false); //analyze assertFalse(CuT.isGameAbandoned()); } @Test public void testGameNotAbandoned3(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); when(redPlayer.isPlayingWith(whitePlayer)).thenReturn(true); when(whitePlayer.isPlayingWith(redPlayer)).thenReturn(true); //analyze assertFalse(CuT.isGameAbandoned()); } @Test public void testHasPlayerResigned(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); when(redPlayer.isPlayingWith(whitePlayer)).thenReturn(false); when(whitePlayer.isPlayingWith(redPlayer)).thenReturn(false); //analyze assertTrue(CuT.hasPlayerResigned()); } @Test public void testHasPlayerResigned2(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); when(redPlayer.isPlayingWith(whitePlayer)).thenReturn(false); when(whitePlayer.isPlayingWith(redPlayer)).thenReturn(true); //analyze assertTrue(CuT.hasPlayerResigned()); } @Test public void testHasPlayerResigned3(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); when(redPlayer.isPlayingWith(whitePlayer)).thenReturn(true); when(whitePlayer.isPlayingWith(redPlayer)).thenReturn(false); //analyze assertTrue(CuT.hasPlayerResigned()); } @Test public void testPlayerNotResigned(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); when(redPlayer.isPlayingWith(whitePlayer)).thenReturn(true); when(whitePlayer.isPlayingWith(redPlayer)).thenReturn(true); //analyze assertFalse(CuT.hasPlayerResigned()); } @Test public void testGetCurrentTurn(){ CuT = new Game(id, redPlayer, whitePlayer); Turn getTurn = CuT.getCurrentTurn(); assertEquals(getTurn, CuT.getCurrentTurn()); } // @Test public void testGetWinner(){ // Invoke CuT = new Game(id, redPlayer, whitePlayer); redView = CuT.getRedView(); whiteView = CuT.getWhiteView(); // when(redView.getRemainingPieces(Piece.Color.RED)).thenReturn(0); // when(redView.getRemainingPieces(Piece.Color.WHITE)).thenReturn(0); assertEquals(CuT.getWinner(), CuT.getWhitePlayer()); } }
26.052083
76
0.630948
9a2a4707aa0330f6e43586554ae49a1215241a9b
5,142
/* Finished.java -- SSL Finished message. Copyright (C) 2006 Free Software Foundation, Inc. This file is a part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.javax.net.ssl.provider; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.ByteBuffer; final class Finished implements Handshake.Body { // Fields. // ------------------------------------------------------------------------- private final ByteBuffer buffer; private final ProtocolVersion version; // Constructor. // ------------------------------------------------------------------------- Finished (final ByteBuffer buffer, final ProtocolVersion version) { buffer.getClass (); version.getClass (); this.buffer = buffer; this.version = version; } // Instance methods. // ------------------------------------------------------------------------- public int length () { if (version.compareTo(ProtocolVersion.TLS_1) >= 0) return 12; if (version == ProtocolVersion.SSL_3) return 36; throw new IllegalArgumentException ("length for this version unknown"); } byte[] verifyData() { if (version.compareTo(ProtocolVersion.TLS_1) >= 0) { byte[] verify = new byte[12]; buffer.position (0); buffer.get (verify); return verify; } throw new IllegalArgumentException ("not TLSv1.0 or later"); } byte[] md5Hash() { if (version == ProtocolVersion.SSL_3) { byte[] md5 = new byte[16]; buffer.position (0); buffer.get (md5); return md5; } throw new IllegalArgumentException ("not SSLv3"); } byte[] shaHash() { if (version == ProtocolVersion.SSL_3) { byte[] sha = new byte[20]; buffer.position (16); buffer.get (sha); return sha; } throw new IllegalArgumentException ("not SSLv3"); } void setVerifyData (final byte[] verifyData, final int offset) { if (version == ProtocolVersion.SSL_3) throw new IllegalArgumentException ("not TLSv1"); buffer.position (0); buffer.put (verifyData, offset, 12); } void setMD5Hash (final byte[] md5, final int offset) { if (version != ProtocolVersion.SSL_3) throw new IllegalArgumentException ("not SSLv3"); buffer.position (0); buffer.put (md5, offset, 16); } void setShaHash (final byte[] sha, final int offset) { if (version != ProtocolVersion.SSL_3) throw new IllegalArgumentException ("not SSLv3"); buffer.position (16); buffer.put (sha, offset, 20); } public String toString () { return toString (null); } public String toString (final String prefix) { StringWriter str = new StringWriter (); PrintWriter out = new PrintWriter (str); if (prefix != null) out.print (prefix); out.println ("struct {"); if (prefix != null) out.print (prefix); if (version.compareTo(ProtocolVersion.TLS_1) >= 0) { out.print (" verifyData = "); out.print (Util.toHexString (verifyData (), ':')); } else if (version == ProtocolVersion.SSL_3) { out.print (" md5 = "); out.print (Util.toHexString (md5Hash (), ':')); out.println (';'); if (prefix != null) out.print (prefix); out.print (" sha = "); out.print (Util.toHexString (shaHash (), ':')); } out.println (';'); if (prefix != null) out.print (prefix); out.print ("} Finished;"); return str.toString (); } }
29.551724
78
0.639829
cf9af5108dccdeff36dc2145297bcea225e2c818
2,840
package pt.lsts.imc4j.msg; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.Exception; import java.lang.String; import java.nio.ByteBuffer; import pt.lsts.imc4j.annotations.FieldType; import pt.lsts.imc4j.annotations.IMCField; import pt.lsts.imc4j.def.SpeedUnits; /** * In this maneuver, a vehicle drives to the center of two other * systems (a, b) in order to be used as a communications relay. */ public class CommsRelay extends Maneuver { public static final int ID_STATIC = 472; /** * WGS-84 Latitude for start point. */ @FieldType( type = IMCField.TYPE_FP64, max = 1.5707963267948966, min = -1.5707963267948966, units = "rad" ) public double lat = 0; /** * WGS-84 Longitude for start point. */ @FieldType( type = IMCField.TYPE_FP64, max = 3.141592653589793, min = -3.141592653589793, units = "rad" ) public double lon = 0; /** * Reference speed. */ @FieldType( type = IMCField.TYPE_FP32 ) public float speed = 0f; /** * Reference speed units. */ @FieldType( type = IMCField.TYPE_UINT8, units = "Enumerated" ) public SpeedUnits speed_units = SpeedUnits.values()[0]; /** * Duration of maneuver, 0 for unlimited duration. */ @FieldType( type = IMCField.TYPE_UINT16, units = "s" ) public int duration = 0; /** * The IMC id of the system A. */ @FieldType( type = IMCField.TYPE_UINT16 ) public int sys_a = 0; /** * The IMC id of the system B. */ @FieldType( type = IMCField.TYPE_UINT16 ) public int sys_b = 0; /** * Move only if the distance to the target is bigger than this * threshold. */ @FieldType( type = IMCField.TYPE_FP32, units = "m" ) public float move_threshold = 0f; public String abbrev() { return "CommsRelay"; } public int mgid() { return 472; } public byte[] serializeFields() { try { ByteArrayOutputStream _data = new ByteArrayOutputStream(); DataOutputStream _out = new DataOutputStream(_data); _out.writeDouble(lat); _out.writeDouble(lon); _out.writeFloat(speed); _out.writeByte((int)(speed_units != null? speed_units.value() : 0)); _out.writeShort(duration); _out.writeShort(sys_a); _out.writeShort(sys_b); _out.writeFloat(move_threshold); return _data.toByteArray(); } catch (IOException e) { e.printStackTrace(); return new byte[0]; } } public void deserializeFields(ByteBuffer buf) throws IOException { try { lat = buf.getDouble(); lon = buf.getDouble(); speed = buf.getFloat(); speed_units = SpeedUnits.valueOf(buf.get() & 0xFF); duration = buf.getShort() & 0xFFFF; sys_a = buf.getShort() & 0xFFFF; sys_b = buf.getShort() & 0xFFFF; move_threshold = buf.getFloat(); } catch (Exception e) { throw new IOException(e); } } }
20.57971
71
0.671479
0f2c9db543febe190655cc33f32aa7254249ff57
11,176
package cn.msy.zc.commonutils; import android.text.TextUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by hxy on 2016/7/22 0022. * description : 正则表达式的工具类. */ public class RegularUtils { /** * email的正则 */ public static final String EMAIL_REGUAL = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; /** * 身份证 */ public static final String ID_CARD_REGUAL = "\\d{17}[0-9a-zA-Z]"; /** * 手机号 */ public static final String MOBILE_REGUAL = "^[1][34578]\\d{9}$"; /** * 固定电话 */ public static final String PHONE_REGUAL = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; /** * 整数 */ public static final String DIGIT_REGUAL = "\\-?[1-9]\\d+"; /** * 浮点数 */ public static final String DECIMALS_REGUAL = "\\-?[1-9]\\d+(\\.\\d+)?"; /** * 空格 */ public static final String BLANK_SPACE_REGUAL = "\\s+"; /** * 中文 */ public static final String CHINESE_REGUAL = "^[\u4E00-\u9FA5]+$"; /** * 生日 */ public static final String BIRTHDAY_REGUAL = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; /** * url */ public static final String URL_REGUAL = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*" + "(\\??(.+=.*)?(&.+=.*)?)?"; /** * 一级域名 */ public static final String DOMAIN_REGUAL = "(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)"; /** * 完整域名 */ public static final String FULL_DOMAIN_REGUAL = "(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)"; /** * 邮政编码 */ public static final String POSTCODE_REGUAL = "[1-9]\\d{5}"; /** * ip地址 */ public static final String IP_ADDRESS_REGUAL = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?)" + "" + ")\\.(0|([1-9](\\d{1,2})?))"; /** * 替换手机的第4-7位为星*号 */ public static final String CHANGE_PHONENUM = "(\\d{3})\\d{4}(\\d{4})"; /** * emoji字符的正则 */ public static final String EMOJI_REGUAL="/\\uD83C[\\uDF00-\\uDFFF]|\\uD83D[\\uDC00-\\uDE4F]/g"; public static boolean isEmojiExist(String string){ if (TextUtils.isEmpty(string)) { return false; } int len = string.length(); for (int i = 0; i < len; i++) { char codePoint = string.charAt(i); if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情 return true; } } return false; } // 校验Tag Alias 只能是数字,英文字母和中文 public static boolean isValidTagAndAlias(String s) { Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$"); Matcher m = p.matcher(s); return m.matches(); } /** * 判断是否是Emoji * * @param codePoint 比较的单个字符 * @return */ private static boolean isEmojiCharacter(char codePoint) { return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)); } public static final String changePhoneNum(String phoneNum) { if (TextUtils.isEmpty(phoneNum)) { return ""; } phoneNum = phoneNum.replaceAll("\\s+", ""); phoneNum = phoneNum.replaceAll(CHANGE_PHONENUM, "$1****$2"); return phoneNum; } public static final String changeEmailNum(String emailNum) { if (TextUtils.isEmpty(emailNum)) { return ""; } emailNum = emailNum.replaceAll("\\s+", ""); String surplusStr = emailNum.substring(0, emailNum.indexOf("@")); if(surplusStr.length()<3){ emailNum = emailNum.substring(0,1)+"*****"+emailNum.substring(emailNum.indexOf("@"), emailNum.length()); }else{ emailNum = emailNum.substring(0,3)+"*****"+emailNum.substring(emailNum.indexOf("@"), emailNum.length()); } return emailNum; } /** * 银行卡替换 */ public static String CHANGE_BANKCARD = "(?<=\\d{0})\\d(?=\\d{4})"; /** * 银行卡替换,保留后四位 * <p/> * 如果银行卡号为空 或者 null ,返回null ;否则,返回替换后的字符串; * * @param bankCard 银行卡号 * @return */ public static String bankCardReplaceWithStar(String bankCard) { if (bankCard.isEmpty() || bankCard == null) { return null; } else { bankCard = bankCard.replaceAll("\\s+", ""); StringBuilder sb = new StringBuilder("**** **** **** "); int length = bankCard.length(); String endText = bankCard.substring(length-4,length); String result = sb.append(endText).toString(); return result; } } /** * 每4位加入空格 * @param bankCardNum * @return */ public static String replaceSplace(String bankCardNum) { StringBuilder sb = new StringBuilder(bankCardNum); int length = bankCardNum.length() / 4 + bankCardNum.length(); for (int i = 0; i < length; i++) { if (i % 5 == 0) { sb.insert(i, " "); } } sb.deleteCharAt(0); return sb.toString(); } /** * 校验输入的 只能是中文或者英文 * @param text * @return */ public static boolean commitText(String text) { // 只能输入汉字或者英文 if (!text.matches("^[\\u4e00-\\u9fa5_a-zA-Z]+$")) { return false; } return true; } /** * 校验银行卡卡号 http://bbs.csdn.net/topics/300203203 * * @param cardId * @return true 代表通过校验 false没通过校验 */ public static boolean checkBankCard(String cardId) { char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1)); if (bit == 'N') { return false; } return cardId.charAt(cardId.length() - 1) == bit; } /** * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位 * * @param nonCheckCodeCardId * @return */ public static char getBankCardCheckCode(String nonCheckCodeCardId) { if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0 || !nonCheckCodeCardId.matches("\\d+")) { //如果传的不是数据返回N return 'N'; } char[] chs = nonCheckCodeCardId.trim().toCharArray(); int luhmSum = 0; for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) { int k = chs[i] - '0'; if (j % 2 == 0) { k *= 2; k = k / 10 + k % 10; } luhmSum += k; } return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0'); } /** * 验证Email * * @param email email地址 * @return 验证成功返回true,验证失败返回false */ public static boolean checkEmail(String email) { return Pattern.matches(EMAIL_REGUAL, email); } /** * 验证身份证号码 * * @param idCard 居民身份证号码15位或18位,最后一位可能是数字或字母 * @return 验证成功返回true,验证失败返回false */ public static boolean checkIdCard(String idCard) { return Pattern.matches(ID_CARD_REGUAL, idCard); } /** * 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港)) * * @param mobile 移动、联通、电信运营商的号码段 * <p>移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡) * 、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用)</p> * <p>联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g)</p> * <p>电信的号段:133、153、180(未启用)、189</p> * @return 验证成功返回true,验证失败返回false * 044 */ public static boolean checkMobile(String mobile) { return Pattern.matches(MOBILE_REGUAL, mobile); } /** * 验证固定电话号码 * * @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447 * <p><b>国家(地区) 代码 :</b>标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 的一位或多位数字, * 数字之后是空格分隔的国家(地区)代码。</p> * <p><b>区号(城市代码):</b>这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号—— * 对不使用地区或城市代码的国家(地区),则省略该组件。</p> * <p><b>电话号码:</b>这包含从 0 到 9 的一个或多个数字 </p> * @return 验证成功返回true,验证失败返回false */ public static boolean checkPhone(String phone) { return Pattern.matches(PHONE_REGUAL, phone); } /** * 验证整数(正整数和负整数) * * @param digit 一位或多位0-9之间的整数 * @return 验证成功返回true,验证失败返回false */ public static boolean checkDigit(String digit) { return Pattern.matches(DIGIT_REGUAL, digit); } /** * 验证整数和浮点数(正负整数和正负浮点数) * * @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30 * @return 验证成功返回true,验证失败返回false */ public static boolean checkDecimals(String decimals) { return Pattern.matches(DECIMALS_REGUAL, decimals); } /** * 验证空白字符 * * @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B * @return 验证成功返回true,验证失败返回false */ public static boolean checkBlankSpace(String blankSpace) { return Pattern.matches(BLANK_SPACE_REGUAL, blankSpace); } /** * 验证中文 * * @param chinese 中文字符 * @return 验证成功返回true,验证失败返回false */ public static boolean checkChinese(String chinese) { return Pattern.matches(CHINESE_REGUAL, chinese); } /** * 验证日期(年月日) * * @param birthday 日期,格式:1992-09-03,或1992.09.03 * @return 验证成功返回true,验证失败返回false */ public static boolean checkBirthday(String birthday) { return Pattern.matches(BIRTHDAY_REGUAL, birthday); } /** * 验证URL地址 * * @param url 格式:http://blog.csdn.net:80/xyang81/article/details/7705960? 或 http://www.csdn.net:80 * @return 验证成功返回true,验证失败返回false */ public static boolean checkURL(String url) { return Pattern.matches(URL_REGUAL, url); } /** * <pre> * 获取网址 URL 的一级域名 * http://detail.tmall.com/item.htm?spm=a230r.1.10.44.1xpDSH&id=15453106243&_u=f4ve1uq1092 ->> tmall.com * </pre> * * @param url * @return */ public static String getDomain(String url) { Pattern p = Pattern.compile(DOMAIN_REGUAL, Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(url); matcher.find(); return matcher.group(); } /** * 获取完整的域名 * * @param url * @return */ public static String getFullDomain(String url) { Pattern p = Pattern.compile(FULL_DOMAIN_REGUAL, Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(url); matcher.find(); return matcher.group(); } /** * 匹配中国邮政编码 * * @param postcode 邮政编码 * @return 验证成功返回true,验证失败返回false */ public static boolean checkPostcode(String postcode) { return Pattern.matches(POSTCODE_REGUAL, postcode); } /** * 匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小) * * @param ipAddress IPv4标准地址 * @return 验证成功返回true,验证失败返回false */ public static boolean checkIpAddress(String ipAddress) { return Pattern.matches(IP_ADDRESS_REGUAL, ipAddress); } }
28.151134
144
0.53597
7ec1247a58b44371480aef0420a107ec6a9c6188
495
package ch.basler.fire.marshall; import static org.junit.Assert.assertEquals; import org.junit.Ignore; import org.junit.Test; import ch.basler.fire.dom.EnvironmentSetting; public class FirewallSettingTest { @Test @Ignore public void testEnvironmentTest() throws Exception { FirewallSetting firewallSetting = new FirewallSetting(); EnvironmentSetting environmentSetting = firewallSetting.getEnvironmentSetting(); assertEquals("", environmentSetting.getEntryPath()); } }
23.571429
84
0.783838
bbdc677b4783da52e657e3402f875a2d2fcfff8f
1,335
package controller.course; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import model.StudentRecordSystem; import model.exceptions.SRSException; import view.MainWindow; import com.lazokin.util.SwingInput; public class addStandardCourseActionListener implements ActionListener { private MainWindow mainWindow; private StudentRecordSystem srs; public addStandardCourseActionListener(MainWindow mainWindow, StudentRecordSystem srs) { this.srs = srs; this.mainWindow = mainWindow; } @Override public void actionPerformed(ActionEvent arg0) { String[] input = SwingInput.showTextDialog(mainWindow, "Add Standard Course", 200, new String[] { "Course Id", "Course Name", "Course Fee" }); if (input != null) { try { String id = input[0]; String name = input[1]; String fee = input[2]; srs.addStandardCourse(id, name, fee); mainWindow.refresh(); } catch (SRSException e) { JOptionPane.showMessageDialog(mainWindow, e.getMessage(), "Add Standard Course Error", JOptionPane.ERROR_MESSAGE); } } } }
26.7
80
0.618727
d947669c76c68ea08298721303ff85621e17fcae
476
package com.accenture.pocproject.customerDetail; /** * Created by fjodors.pohodnevs on 8/29/2016. */ public interface CustomerDetailContract { interface View { void showCustomerDetail(CustomerDetail customerDetail); void showError(Throwable e); void hideProgress(); void showSuccess(); } interface Presenter { void fetchCustomerDetail(); void editCustomerData(CustomerDetailEdit customerDetailEdit); } }
20.695652
69
0.689076
285027ba5cfed11eb71f1bdb5b68b99e6a50a2b3
10,156
package me.Wundero.Ray.conversation; /* The MIT License (MIT) Copyright (c) 2016 Wundero Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.TextTemplate; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.serializer.TextSerializers; import me.Wundero.Ray.Ray; import me.Wundero.Ray.translation.M; import me.Wundero.Ray.utils.TextUtils; import me.Wundero.Ray.utils.Utils; public class TextEditConversation { public static void start(Player player, Text original, Consumer<Text> func) { if (!player.hasPermission("ray.textedit")) { M.sm(player, "error.nopermission"); return; } Conversation c = ConversationFactory.builder(Ray.get().getPlugin()).withEcho(true).withSuppression(true) .withPrefix(Text.of(TextColors.AQUA, "[Text]")) .withFirstPrompt(new TextEditPrompt(TextUtils.flatten(original, true), func)) .withCanceller(new ConversationCanceller() { @Override public boolean shouldCancel(ConversationContext context, String input) { return input.equalsIgnoreCase("exit"); } @Override public void onCancel(ConversationContext context) { func.accept(original); } }).build(player); c.start(); } private static TextTemplate getTemplate(List<Text> t) { List<Text> mod = (List<Text>) Utils.applyToAll(t, text -> { return text.toBuilder().onClick(TextActions.runCommand("" + t.indexOf(text))).build(); }, () -> new ArrayList<Text>()); Text t2 = Text.builder().append(mod).build(); return TextTemplate.of(Text.of(TextColors.WHITE) .concat(Text.of(TextColors.AQUA, "Now editing text: (Click on any part to edit it, or type ", TextColors.GOLD, "done", TextColors.AQUA, "!)", Text.NEW_LINE)), (t2)); } private static class TextEditPrompt extends TypePrompt<Integer> { private List<Text> text; private Consumer<Text> finished; public TextEditPrompt(List<Text> text, Consumer<Text> finished) { this(TextEditConversation.getTemplate(text)); this.text = text; this.finished = finished; } private TextEditPrompt(TextTemplate template) { super(template, Integer.class); } @Override public Text getQuestion(ConversationContext context) { return formatTemplate(context); } @Override public boolean isInputValid(ConversationContext ctx, String in) { if (in.equalsIgnoreCase("done")) { return true; } if (super.isInputValid(ctx, in)) { int val = get(getSelected(ctx, in)); if (val < 0 || val >= text.size()) { return false; } else { return true; } } else { return false; } } @Override public Prompt onInput(Optional<Option> selected, String text, ConversationContext context) { if (text.equals("done")) { finished.accept(Text.join(this.text)); return null; } return onTypeInput(get(selected), text, context); } @Override public Prompt onTypeInput(Integer object, String text, ConversationContext context) { return new EditTextPrompt(object, this.text, this.finished); } @Override public Text getFailedText(ConversationContext context, String failedInput) { return Text.of(TextColors.RED, "That is not a valid index!"); } } private static class EditTextPrompt extends Prompt { private List<Text> allText; private int index; private Consumer<Text> func; public EditTextPrompt(int index, List<Text> texts, Consumer<Text> finished) { super(TextTemplate.of(TextColors.AQUA, "Please choose what to edit, or type ", TextColors.GOLD, "done", TextColors.AQUA, " to finish: ", TextTemplate.arg("options").color(TextColors.GOLD).build())); this.index = index; this.func = finished; this.allText = texts; } @Override public Text getQuestion(ConversationContext context) { return formatTemplate(context); } @Override public boolean isInputValid(ConversationContext context, String input) { return input.equalsIgnoreCase("done") || super.isInputValid(context, input); } @Override public Optional<List<Option>> options(ConversationContext context) { List<Option> out = Utils.al(); out.add(Option.build("text", "text")); out.add(Option.build("click", "click")); out.add(Option.build("hover", "hover")); return Optional.of(out); } @Override public Text getFailedText(ConversationContext context, String failedInput) { return Text.of(TextColors.RED, "That is not a valid option!"); } @Override public Prompt onInput(Optional<Option> selected, String text, ConversationContext context) { if (text.equalsIgnoreCase("done")) { return new TextEditPrompt(allText, func); } else { return new EditPartPrompt(text, this.allText, this.index, this.func); } } } private static class EditPartPrompt extends Prompt { private List<Text> all; private Text cur; private int ind; private Consumer<Text> func; private int type = 0; public EditPartPrompt(String type, List<Text> all, int ind, Consumer<Text> func) { super(TextTemplate.of(TextColors.AQUA, "Now editing ", TextColors.GOLD, TextActions.suggestCommand(getTypeSer(getType(type), all.get(ind))), "[" + type + "]")); this.all = all; this.ind = ind; this.func = func; this.cur = all.get(ind); this.type = getType(type); } private static String getTypeSer(int type, Text cur) { switch (type) { case 0: return TextSerializers.FORMATTING_CODE.serialize(cur); case 1: { String out = ""; if (cur.getHoverAction().isPresent() && cur.getHoverAction().get().getResult() instanceof Text) { return TextSerializers.FORMATTING_CODE.serialize((Text) cur.getHoverAction().get().getResult()); } return out; } case 2: { String out = ""; if (cur.getClickAction().isPresent()) { ClickAction<?> click = cur.getClickAction().get(); Object res = click.getResult(); if (!(res instanceof Consumer)) { if (click instanceof ClickAction.ChangePage) { out = "page:"; } if (click instanceof ClickAction.RunCommand) { out = "run:"; } if (click instanceof ClickAction.OpenUrl) { out = "url:"; } return out + res.toString(); } } return out; } } return ""; } private static ClickAction<?> get(String in) { String inOrg = in; in = in.toLowerCase(); if (in.startsWith("page:")) { in = in.replaceFirst("page\\:", ""); try { Integer i = Integer.parseInt(in); return TextActions.changePage(i); } catch (Exception e) { return TextActions.suggestCommand(inOrg.substring(5)); } } if (in.startsWith("run:")) { return TextActions.runCommand(inOrg.substring(4)); } if (in.startsWith("url:")) { Optional<URL> u = Utils.toUrlSafe(inOrg.substring(4)); if (u.isPresent()) { return TextActions.openUrl(u.get()); } else { return TextActions.suggestCommand(inOrg.substring(4)); } } if (in.startsWith("suggest:")) { inOrg = inOrg.substring("suggest:".length()); } return TextActions.suggestCommand(inOrg); } private static int getType(String type) { int t = 0; switch (type.toLowerCase().trim()) { case "click": t++; case "hover": t++; } return t; } @Override public Text getQuestion(ConversationContext context) { return formatTemplate(context); } @Override public Optional<List<Option>> options(ConversationContext context) { return Optional.empty(); } @Override public Text getFailedText(ConversationContext context, String failedInput) { return Text.of(TextColors.DARK_RED, "Fatal error."); } @Override public Prompt onInput(Optional<Option> selected, String text, ConversationContext context) { if (type == 2) { this.all.set(ind, cur.toBuilder().onClick(get(text)).build()); context.sendMessage(Text.of(TextColors.AQUA, "Part now set!")); return new EditTextPrompt(this.ind, this.all, this.func); } Text ser = TextSerializers.FORMATTING_CODE.deserialize(text); if (type == 1) { this.all.set(ind, cur.toBuilder().onHover(TextActions.showText(ser)).build()); context.sendMessage(Text.of(TextColors.AQUA, "Part now set!")); return new EditTextPrompt(this.ind, this.all, this.func); } context.sendMessage(Text.of(TextColors.AQUA, "Part now set!")); Text v = TextUtils.apply(ser.toBuilder(), all.get(ind).toBuilder()).build(); this.all.set(ind, v); return new EditTextPrompt(this.ind, this.all, this.func); } } }
32.447284
107
0.674478
ab3abdb4f990edb81174d4b9eaa7928c1d90ef6a
8,785
package virtual_robot.games; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.LinearGradient; import javafx.scene.paint.Stop; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.BodyFixture; import org.dyn4j.geometry.Vector2; import org.dyn4j.world.NarrowphaseCollisionData; import org.dyn4j.world.listener.CollisionListenerAdapter; import virtual_robot.controller.Game; import virtual_robot.controller.VirtualGameElement; import virtual_robot.game_elements.classes.*; public class FreightFrenzy extends Game { public static final Vector2[] HUB_POSITIONS_INCHES = new Vector2[]{ new Vector2(24, -12), // Red hub new Vector2(-24, -12), // Blue hub new Vector2(0, 48) // Neutral hub }; public static final Vector2 RED_CAROUSEL_POSITION_INCHES = new Vector2(68.75, -68.75); public static final Vector2 BLUE_CAROUSEL_POSITION_INCHES = new Vector2(-68.75, -68.75); private Carousel redCarousel = null; private Carousel blueCarousel = null; private boolean humanPlayerActive = false; @Override public void initialize() { //Calling the super method causes the game elements to be created, populating the gameElements list. super.initialize(); //Assign the game elements to the appropriate static final lists. for (VirtualGameElement e: gameElements){ if (e instanceof CargoFreight){ CargoFreight.cargos.add((CargoFreight)e); Freight.FREIGHT_ITEMS.add((Freight)e); } else if (e instanceof BoxFreight){ BoxFreight.boxes.add((BoxFreight)e); Freight.FREIGHT_ITEMS.add((Freight)e); } else if (e instanceof DuckFreight){ DuckFreight.ducks.add((DuckFreight)e); Freight.FREIGHT_ITEMS.add((Freight)e); } else if (e instanceof ShippingHub){ ShippingHub.shippingHubs.add((ShippingHub) e); } else if (e instanceof Barrier){ Barrier.theBarrier = (Barrier) e; } else if (e instanceof Carousel) { Carousel.carousels.add((Carousel)e); } } /* * Set the Shipping Hub Colors -- Red, Blue, and Green (for neutral) */ ShippingHub.shippingHubs.get(0).getOuterCircle().setFill(Color.valueOf("FF0000")); ShippingHub.shippingHubs.get(1).getOuterCircle().setFill(Color.valueOf("0000FF")); Stop blueStop = new Stop(0.49, Color.BLUE); Stop redStop = new Stop(0.51, Color.RED); LinearGradient gradient = new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, blueStop, redStop); ShippingHub.shippingHubs.get(2).getOuterCircle().setFill(gradient); redCarousel = Carousel.carousels.get(0); blueCarousel = Carousel.carousels.get(1); redCarousel.setLocationInches(RED_CAROUSEL_POSITION_INCHES); redCarousel.setOnField(true); blueCarousel.setLocationInches(BLUE_CAROUSEL_POSITION_INCHES); blueCarousel.setOnField(true); /* * Add a collision listener to implement "special" handling of certain types of collision. For example, * this includes collisions involving rings that are stacked (to cause the stack to scatter). It should not * include collisions resulting in the robot controlling a game element: that should be handled within * the specific VirtualBot implementations. */ world.addCollisionListener(new CollisionListenerAdapter<Body, BodyFixture>(){ @Override public boolean collision(NarrowphaseCollisionData<Body, BodyFixture> collision) { return handleNarrowPhaseCollision(collision); } }); } /** * Narrowphase Collision event handler * This can be used for game element--game element collisions, as needed. * Robot--game element collisions should be handled in the specific robot config class, not here. * * For the current game implementation, no special handling of game element--game element collisions is needed; * the default handling by the physics engine suffices. * * However, this method can be useful for logging purposes during debugging. */ private boolean handleNarrowPhaseCollision(NarrowphaseCollisionData<Body, BodyFixture> collision){ return true; } /* * Set/Reset all game elements to their initial positions */ @Override public void resetGameElements() { for (int i=0; i<3; i++){ ShippingHub.shippingHubs.get(i).setOnField(true); ShippingHub.shippingHubs.get(i).setLocationInches(HUB_POSITIONS_INCHES[i]); } Barrier.theBarrier.setOnField(true); Barrier.theBarrier.setLocationInches(0, 24); //Before repositioning freight items, detach from shipping hubs for (Freight f: Freight.FREIGHT_ITEMS){ f.setOwningShippingHub(null); } for (int i=0; i<30; i++){ int row = i / 5; int col = i % 5; float x = row<3? -66 + col * 8 : 34 + col * 8; float y = 32 + (row % 3) * 16; BoxFreight.boxes.get(i).setOnField(true); BoxFreight.boxes.get(i).setLocationInches(x, y); } for (int i=0; i<20; i++){ int row = i / 5; int col = i % 5; float x = row<2? -66 + col * 8 : 34 + col * 8; float y = 40 + (row % 2) * 16; CargoFreight.cargos.get(i).setOnField(true); CargoFreight.cargos.get(i).setLocationInches(x, y); } // Remove attached ducks from carousels redCarousel.clearAttachedDuck(); blueCarousel.clearAttachedDuck(); // Clear, then repopulate the red and blue loading docks, each with one half of the ducks int numDucks = DuckFreight.ducks.size(); DuckFreight.redLoadingDock.clear(); DuckFreight.blueLoadingDock.clear(); for (int i=0; i<numDucks; i++){ DuckFreight.ducks.get(i).setOnField(false); if (i< numDucks/2) DuckFreight.redLoadingDock.add(DuckFreight.ducks.get(i)); else DuckFreight.blueLoadingDock.add(DuckFreight.ducks.get(i)); } // Attach a duck to each carousel, and remove from the corresponding loading dock redCarousel.attachDuck(DuckFreight.redLoadingDock.get(0)); DuckFreight.redLoadingDock.remove(0); blueCarousel.attachDuck(DuckFreight.blueLoadingDock.get(0)); DuckFreight.blueLoadingDock.remove(0); // Simulation isn't running when this method is called, so explicit display update required updateDisplay(); } /** * Freight Frenzy effectively does use a human player, so return true. * @return */ @Override public boolean hasHumanPlayer() { return true; } @Override public boolean isHumanPlayerAuto() { return humanPlayerActive; } @Override public void setHumanPlayerAuto(boolean selected) { humanPlayerActive = selected; } /** * Update the human player state. If humanPlaterActive is true, this method will be called once during * each iteration of the game loop. Otherwise, it will be called during the game loop only if * humanPlayerActionRequested is true (and that is set using the Human Action button). * @param millis milliseconds since the previous update */ @Override public void updateHumanPlayerState(double millis) { /* * For each carousel, attach a duck only if: there is currently no attached duck AND at least 1 second * has passed since prior duck release AND there is at least one duck remaining in the corresponding loading * dock AND the carousel has stopped spinning. */ if (redCarousel.getAttachedDuck() == null && redCarousel.getTimerMilliseconds() > 1000 && DuckFreight.redLoadingDock.size() > 0 && Math.abs(redCarousel.getElementBody().getAngularVelocity()) < 0.01) { redCarousel.attachDuck(DuckFreight.redLoadingDock.get(0)); DuckFreight.redLoadingDock.remove(0); } if (blueCarousel.getAttachedDuck() == null && blueCarousel.getTimerMilliseconds() > 1000 && DuckFreight.blueLoadingDock.size() > 0 && Math.abs(blueCarousel.getElementBody().getAngularVelocity()) < 0.01) { blueCarousel.attachDuck(DuckFreight.blueLoadingDock.get(0)); DuckFreight.blueLoadingDock.remove(0); } humanPlayerActionRequested = false; } }
40.671296
116
0.646443
b472106ab77a48fd6fb85be9828ec14af4d902db
2,137
/* * Copyright 2016 ZJNU ACM. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.edu.zjnu.acm.judge.mapper; import cn.edu.zjnu.acm.judge.Application; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; /** * * @author zhanhb */ @RunWith(JUnitPlatform.class) @Slf4j @SpringBootTest(classes = Application.class) @Transactional @WebAppConfiguration public class ProblemMapperTest { @Autowired private ProblemMapper instance; private final String lang = "en"; /** * Test of findOne method, of class ProblemMapper. */ @Test public void testFindOne() { log.debug("findOne"); String[] locales = {lang, null}; for (String locale : locales) { instance.findOne(0, locale); instance.findOne(1000, locale); } } /** * Test of findOne method, of class ProblemMapper. */ @Test public void testFindOneNoI18n() { log.debug("findOne"); instance.findOneNoI18n(0); instance.findOneNoI18n(1000); } /** * Test of touchI18n method, of class ProblemMapper. */ @Test public void testTouchI18n() { log.info("touchI18n"); long problemId = 0L; instance.touchI18n(problemId, lang); } }
27.753247
75
0.691156
63d13e00b0c7441e85e1634cab3fcc0595c341b0
5,420
package nfm.open; /** * Created by Rafael on 24/07/2016. * * TODO integrate fully (currently only Mad) */ public class Stat { final int[] swits; final float[] acelf; final int handb; final float airs; final int airc; final int turn; final float grip; final float bounce; final float simag; final float moment; final float comprad; final int push; final int revpush; final int lift; final int revlift; final int powerloss; final int flipy; final int msquash; final int clrad; final float dammult; final int maxmag; final float dishandle; final float outdam; final int cclass; final String names; final int enginsignature; boolean include = false; String createdby = ""; int publish = 0; public Stat(int[] swits, float[] acelf, int handb, float airs, int airc, int turn, float grip, float bounce, float simag, float moment, float comprad, int push, int revpush, int lift, int revlift, int powerloss, int flipy, int msquash, int clrad, float dammult, int maxmag, float dishandle, float outdam, int cclass, String names, int enginsignature, boolean include, String createdby, int publish) { this(swits, acelf, handb, airs, airc, turn, grip, bounce, simag, moment, comprad, push, revpush, lift, revlift, powerloss, flipy, msquash, clrad, dammult, maxmag, dishandle, outdam, cclass, names, enginsignature); this.include = include; this.createdby = createdby; this.publish = publish; } public Stat(int[] swits, float[] acelf, int handb, float airs, int airc, int turn, float grip, float bounce, float simag, float moment, float comprad, int push, int revpush, int lift, int revlift, int powerloss, int flipy, int msquash, int clrad, float dammult, int maxmag, float dishandle, float outdam, int cclass, String names, int enginsignature) { this.swits = swits.clone(); this.acelf = acelf.clone(); this.handb = handb; this.airs = airs; this.airc = airc; this.turn = turn; this.grip = grip; this.bounce = bounce; this.simag = simag; this.moment = moment; this.comprad = comprad; this.push = push; this.revpush = revpush; this.lift = lift; this.revlift = revlift; this.powerloss = powerloss; this.flipy = flipy; this.msquash = msquash; this.clrad = clrad; this.dammult = dammult; this.maxmag = maxmag; this.dishandle = dishandle; this.outdam = outdam; this.cclass = cclass; this.names = names; this.enginsignature = enginsignature; } public Stat(Stat clone) { this.swits = clone.swits.clone(); this.acelf = clone.acelf.clone(); this.handb = clone.handb; this.airs = clone.airs; this.airc = clone.airc; this.turn = clone.turn; this.grip = clone.grip; this.bounce = clone.bounce; this.simag = clone.simag; this.moment = clone.moment; this.comprad = clone.comprad; this.push = clone.push; this.revpush = clone.revpush; this.lift = clone.lift; this.revlift = clone.revlift; this.powerloss = clone.powerloss; this.flipy = clone.flipy; this.msquash = clone.msquash; this.clrad = clone.clrad; this.dammult = clone.dammult; this.maxmag = clone.maxmag; this.dishandle = clone.dishandle; this.outdam = clone.outdam; this.cclass = clone.cclass; this.names = clone.names; this.enginsignature = clone.enginsignature; } public Stat(int cn) { this.swits = CarDefine.swits[cn].clone(); this.acelf = CarDefine.acelf[cn].clone(); this.handb = CarDefine.handb[cn]; this.airs = CarDefine.airs[cn]; this.airc = CarDefine.airc[cn]; this.turn = CarDefine.turn[cn]; this.grip = CarDefine.grip[cn]; this.bounce = CarDefine.bounce[cn]; this.simag = CarDefine.simag[cn]; this.moment = CarDefine.moment[cn]; this.comprad = CarDefine.comprad[cn]; this.push = CarDefine.push[cn]; this.revpush = CarDefine.revpush[cn]; this.lift = CarDefine.lift[cn]; this.revlift = CarDefine.revlift[cn]; this.powerloss = CarDefine.powerloss[cn]; this.flipy = CarDefine.flipy[cn]; this.msquash = CarDefine.msquash[cn]; this.clrad = CarDefine.clrad[cn]; this.dammult = CarDefine.dammult[cn]; this.maxmag = CarDefine.maxmag[cn]; this.dishandle = CarDefine.dishandle[cn]; this.outdam = CarDefine.outdam[cn]; this.cclass = CarDefine.cclass[cn]; this.names = CarDefine.names[cn]; this.enginsignature = CarDefine.enginsignature[cn]; if (cn >= CarDefine.SIXTEEN) { include = CarDefine.include[cn]; createdby = CarDefine.createdby[cn]; publish = CarDefine.publish[cn]; } } }
31.882353
356
0.578967
c075a5246b8a05fef7b81daed2d2c6b4a9d45240
333
package com.resourcetracker; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Deploy { /** * Runs application * * @param args command line arguments * */ public static void main(String[] args) throws Exception { SpringApplication.run(Deploy.class, args); } }
18.5
68
0.747748
9df418a8dab84d60cc9e4d27ea4a80d983b82ef6
12,962
/* * Copyright 2017 alehuo. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alehuo.untitledjavagame; import com.alehuo.untitledjavagame.item.Inventory; import com.alehuo.untitledjavagame.item.ItemRegistry; import com.alehuo.untitledjavagame.menu.MenuState; import com.alehuo.untitledjavagame.menu.Menu; import com.alehuo.untitledjavagame.input.MouseHandler; import com.alehuo.untitledjavagame.graphics.Renderer; import com.alehuo.untitledjavagame.singleplayer.SaveGame; import com.alehuo.untitledjavagame.entities.MpPlayer; import com.alehuo.untitledjavagame.entities.NpcTicker; import com.alehuo.untitledjavagame.entities.Player; import static com.alehuo.untitledjavagame.Game.CENTERX; import static com.alehuo.untitledjavagame.Game.CENTERY; import static com.alehuo.untitledjavagame.Game.DEBUG_PLAYER; import static com.alehuo.untitledjavagame.Game.FONTSCALE; import static com.alehuo.untitledjavagame.Game.NAME; import static com.alehuo.untitledjavagame.Game.WINDOW_HEIGHT; import static com.alehuo.untitledjavagame.Game.WINDOW_WIDTH; import static com.alehuo.untitledjavagame.Game.frame; import static com.alehuo.untitledjavagame.Game.tickrate; import com.alehuo.untitledjavagame.postprocess.filters.DarkenFilter; import com.alehuo.untitledjavagame.graphics.SpriteSheet; import com.alehuo.untitledjavagame.graphics.animation.Animation; import com.alehuo.untitledjavagame.graphics.animation.AnimationTicker; import com.alehuo.untitledjavagame.map.GameMap; import com.alehuo.untitledjavagame.net.Client; import com.alehuo.untitledjavagame.net.PlayerList; import java.awt.*; import java.awt.image.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author alehuo */ public class GameWindow extends Canvas implements Runnable, Tickable { /** * SpriteSheet */ public static SpriteSheet spriteSheet = new SpriteSheet("spriteSheet.png"); /** * Animation ticker */ public static final AnimationTicker animationTicker = new AnimationTicker(); /** * NPC ticker */ public static final NpcTicker npcTicker = new NpcTicker(); /** * Player */ public static final Player player = new Player(); /** * Inventory */ public static final Inventory inventory = new Inventory(); /** * Inventory state */ public static boolean SHOW_INVENTORY = false; /** * ItemRegistry */ public static ItemRegistry itemRegistry = new ItemRegistry(); /** * Connection state Note: Multiplayer functionality is not currently * implemented. */ public static boolean isConnectedToServer = false; /** * Menu state */ public static MenuState menuState = MenuState.MAINMENU; /** * Is the menu open? */ public static boolean isInMenu = true; /** * Is the save loaded? */ public static boolean playing = false; /** * Logger */ private static final Logger LOG = Logger.getLogger(Game.class.getName()); /** * GameTime */ private static final GameTime gameTime = new GameTime(); /** * Save file name */ private String saveFileName = "save.sav"; /** * Game state */ public boolean running = false; /** * Tick count */ public int tickCount = 0; /** * Image data */ private final BufferedImage image = new BufferedImage(WINDOW_WIDTH, WINDOW_HEIGHT, BufferedImage.TYPE_INT_RGB); /** * Pixel array */ private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); /** * Renderer */ private Renderer renderer; /** * Graphics object */ private Graphics g; /** * Current font */ private Font currentFont; /** * Animation for PLAYER low health */ private final Animation playerLowHealth; /** * Save object */ private SaveGame save; /** * GameMap */ public GameMap map = new GameMap("map3"); /** * MouseHandler */ private final MouseHandler mouseHandler = new MouseHandler(inventory); /** * Client */ private Client client; /** * Menu */ private Menu menu; /** * Constructor */ public GameWindow() { renderer = new Renderer(WINDOW_WIDTH, WINDOW_HEIGHT, pixels); /** * Load sprites and animations here */ //Player picture (up) spriteSheet.loadSprite("player_up", 32, 32, 16); //Player picture (down) spriteSheet.loadSprite("player_down", 32, 16, 16); //Player picture (left) spriteSheet.loadSprite("player_left", 32, 64, 16); //Player picture (right) spriteSheet.loadSprite("player_right", 32, 48, 16); //Swimming: //Player picture (up) spriteSheet.loadSprite("player_swimming_up", 80, 32, 16); //Player picture (down) spriteSheet.loadSprite("player_swimming_down", 80, 16, 16); //Player picture (left) spriteSheet.loadSprite("player_swimming_left", 80, 64, 16); //Player picture (right) spriteSheet.loadSprite("player_swimming_right", 80, 48, 16); //Full heart spriteSheet.loadSprite("full_heart", 112, 96, 32); //Half heart spriteSheet.loadSprite("half_a_heart", 144, 96, 32); //Player shadow spriteSheet.loadSprite("player_shadow", 208, 14, 32, 34); //Animations playerLowHealth = new Animation("PlayerLowHealth", 30); //Register animations to be tickable animationTicker.register(playerLowHealth); start(); } /** * */ public void init() { } private synchronized void start() { running = true; new Thread(this).start(); } private synchronized void stop() { running = false; } @Override public void run() { long lastTime = System.nanoTime(); double nsPerTick = 1000000000D / tickrate; int frames = 0; int ticks = 0; long lastTimer = System.currentTimeMillis(); double delta = 0; //Init init(); while (running) { long now = System.nanoTime(); delta += (now - lastTime) / nsPerTick; lastTime = now; //Use false to limit fps to the number of ticks boolean shouldRender = false; while (delta >= 1) { //Tick ticks++; tick(); delta -= 1; shouldRender = true; } if (shouldRender) { try { Thread.sleep(1); } catch (InterruptedException ex) { LOG.log(Level.SEVERE, null, ex); } } if (shouldRender) { //Render a new frame frames++; render(); } if (System.currentTimeMillis() - lastTimer >= 1000) { lastTimer += 1000; frame.setTitle(NAME + " (" + frames + " frames, " + ticks + " ticks)"); frames = 0; ticks = 0; } } } /** * */ @Override public void tick() { tickCount++; //Tick animations, input, npcs and PLAYER if (Game.menuState != MenuState.PAUSED) { animationTicker.tick(); npcTicker.tick(); player.tick(); //Tick tick.. if (tickCount % 40 == 0) { gameTime.tick(); } } //Tick the server if we are connected if (isConnectedToServer) { client.tick(); } } /** * */ public void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { //Triple buffering createBufferStrategy(3); return; } try { //Get draw graphics g = bs.getDrawGraphics(); //Clear renderer.clear(); //Render base image renderer.render(); //Font currentFont = g.getFont(); g.setFont(new Font(currentFont.getName(), Font.BOLD, (int) Math.floor(18 * FONTSCALE))); if (Game.menuState != MenuState.NONE) { //Image g.drawImage(image, 0, 0, getWidth(), getHeight(), null); // menu.render(g); } else { //If the game is running, render map & npcs //Apply darken filter renderer.setFilters(new DarkenFilter(gameTime.getFactor())); //Map map.renderMap(g, renderer, player); //Other objects map.renderObjects(g, renderer, player); map.detectCollision(player); //NPCs here player.render(renderer, g, map); //Render MP players if (isConnectedToServer) { PlayerList pList = client.getPlayerList(); for (MpPlayer plr : pList.getPlayers().values()) { try { if (plr.getUuid().equals(client.getUuid())) { continue; } plr.renderMpPlayer(g, renderer, player); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error rendering player(s): " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } } } //Reset filter renderer.resetFilter(); //Player health system int playerFullHearts = (int) Math.floor(player.getHealth() / 20); int playerHalfHearts = (int) Math.floor((player.getHealth() - playerFullHearts * 20) / 10); int heartX = CENTERX - 256; int heartY = 5; g.drawString(player.getHealth() + " / " + player.getMaxHealth() + " LP", heartX - 78, heartY + 22); g.drawString(player.getXp() + " xp", heartX - 78, heartY + 44); if (playerFullHearts == 0 && playerHalfHearts == 0 && player.getHealth() > 0) { playerLowHealth.nextFrame(renderer, heartX, heartY); } else if (player.getHealth() == 0) { g.setColor(Color.red); //Black background g.drawImage(image, 0, 0, getWidth(), getHeight(), null); g.drawString("YOU DIED", CENTERX - 48, CENTERY); } else { for (int hearts = 0; hearts < playerFullHearts; hearts++) { spriteSheet.paint(renderer, "full_heart", heartX, heartY); heartX += 26; } if (playerHalfHearts > 0) { spriteSheet.paint(renderer, "half_a_heart", heartX, heartY); } } if (SHOW_INVENTORY) { inventory.renderInventory(g, renderer); } //Final image g.drawImage(image, 0, 0, getWidth(), getHeight(), null); //Debug for PLAYER g.setColor(Color.white); if (DEBUG_PLAYER) { g.drawString("x " + player.getX(), 5, 15); g.drawString("y " + player.getY(), 5, 31); g.drawString("tileCount " + map.getRenderedTileCount(), 5, 47); g.drawString("tileX " + map.getCurrentTileX(), 5, 63); g.drawString("tileY " + map.getCurrentTileY(), 5, 79); g.drawString("windowWidth " + Game.WINDOW_WIDTH, 5, 95); g.drawString("windowHeight " + Game.WINDOW_HEIGHT, 5, 111); g.drawString("gameTime (0 - 2359) " + gameTime.getTime() + ", " + String.format("%.5f", gameTime.getFactor()), 5, 127); } } } finally { //Empty buffer g.dispose(); } //Show frame bs.show(); } }
30.285047
146
0.55169
645c849c1e4a49ce617c44fd1f1e15c31dd45ebd
7,868
package com.alvism.webmagic.processor; import com.alvism.webmagic.util.URLUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import us.codecraft.webmagic.Page; import us.codecraft.webmagic.Site; import us.codecraft.webmagic.Spider; import us.codecraft.webmagic.processor.PageProcessor; import us.codecraft.webmagic.selector.Html; import us.codecraft.webmagic.selector.Selectable; import java.util.List; import java.util.stream.Collectors; /** * 阿里巴巴商品数据爬虫,基于WebMagic爬虫框架 * 该类需要借助Chrome浏览器的ChromeDriver驱动 * 可根据操作系统到网站http://npm.taobao.org/mirrors/chromedriver/下载对应的最新驱动 * Windows操作系统默认加载“C:\Windows\System32\chromedriver.exe” * Linux操作系统默认加载“/usr/bin/chromedriver.sh” */ @Slf4j public class AlibabaProdProcessor implements PageProcessor, BaseProcessor { //搜索域名 private static final String SEARCH_DOMAIN = "https://s.1688.com/"; //详情域名 private static final String DETAIL_DOMAIN = "https://detail.1688.com/"; //目标URL private static final String TARGET_URL = "https://s.1688.com/selloffer/offer_search.htm?keywords=#KEYWORD&beginPage=#PAGE"; //关键字 private String keyWord; //谷歌浏览器参数 private static ChromeOptions options; //当前数量 private long current; //爬取数量 private long size; static { //设置无头模式 options = new ChromeOptions(); options.addArguments("headless", "disable-gpu"); } @Override public void process(Page page) { //创建谷歌浏览器驱动 ChromeDriver driver = new ChromeDriver(options); String url = page.getUrl().get(); //打开URL driver.get(url); //浏览器窗口最大化 driver.manage().window().maximize(); //执行滚动脚本,模拟浏览器滚动,完成图片懒加载 //driver.executeScript("window.scrollTo(0, document.body.scrollHeight)"); //滚动后,停留0.5s //ThreadUtil.sleep(500); //获取HTML结构 Html html = new Html(driver.getPageSource()); if (url.startsWith(DETAIL_DOMAIN)) { //判断是否为详情页 //商品编号 String prodNum = URLUtil.resolve(page.getUrl().toString()).getValue("prodNum"); //商品名称 //*[@id="mod-detail-title"]/h1 String prodName = html.xpath("//*[@id='mod-detail-title']/h1/text()").get(); //商品价格 String prodPrice = URLUtil.resolve(page.getUrl().toString()).getValue("prodPrice"); //店铺名称 String storeName = URLUtil.resolve(page.getUrl().toString()).getValue("storeName"); System.out.println(prodNum); System.out.println(prodName); System.out.println(prodPrice); System.out.println(storeName); //商品属性 //obj-leading Selectable leading = html.xpath("//div[@class='d-content']/div[@class='obj-leading']"); if (leading != null && !StringUtils.isEmpty(leading.get())) { System.out.println(leading.xpath("//div[@class='obj-header']/span/text()").get() + ":" + leading.xpath("//div[@class='obj-content']/ul/li/div/a/span/text()").all()); } //obj-sku Selectable sku = html.xpath("//div[@class='d-content']/div[@class='obj-sku']"); if (sku != null && !StringUtils.isEmpty(sku.get())) { //这里判断属性值显示的是文本还是图片,问题则直接取文本,否则取span标签的title属性 if (!StringUtils.isEmpty(sku.xpath("//div[@class='obj-content']/table/tbody/tr[1]/td[1]/span/text()").get())) { System.out.println(sku.xpath("//div[@class='obj-header']/span/text()").get() + ":" + sku.xpath("//div[@class='obj-content']/table/tbody/tr/td[1]/span/text()").all()); } else { System.out.println(sku.xpath("//div[@class='obj-header']/span/text()").get() + ":" + sku.xpath("//div[@class='obj-content']/table/tbody/tr/td[1]/span/@title").all()); } } //商品图片 //缩略图 List<String> thumb = html.xpath("//div[@id='dt-tab']/div/ul/li/div/a/img/@src").all(); System.out.println("缩略图片:" + thumb); //标准图片 List<String> img = thumb.parallelStream() .map(str -> str.replace("60x60", "400x400")).collect(Collectors.toList()); System.out.println("标准图片:" + img); //放大图片 List<String> bigImg = thumb.parallelStream() .map(str -> str.replace(".60x60", "")).collect(Collectors.toList()); System.out.println("放大图片:" + bigImg); //详情图片 String detailUrl = html.xpath("//div[@id='mod-detail-description']/div[1]/div[1]/@data-tfs-url").get(); System.out.println("详情图片:" + detailUrl); System.out.println(); } else if (url.startsWith(SEARCH_DOMAIN)) { //判断是否为搜索页 List<String> prodNums = html.xpath("//*[@id='sm-offer-list']/li[@t-offer-id]/@t-offer-id").all(); List<String> detailUrls = html.xpath("//*[@class='imgofferresult-mainBlock']/div[3]/a/@href").all(); List<String> prodPrices = html.xpath("//*[@class='imgofferresult-mainBlock']/div[2]/span[1]/text()").all(); List<String> storeNames = html.xpath("//*[@class='imgofferresult-mainBlock']/div[4]/a[1]/text()").all(); if (detailUrls != null && detailUrls.size() > 0) { //先将详情加入到待爬取列表中 String detailUrl; for (int i = 0; i < detailUrls.size(); i++) { detailUrl = detailUrls.get(i); if (!detailUrl.startsWith("https:")) { detailUrl = "https:" + detailUrl; } if (this.current < this.size) { current += 1; if (detailUrl.contains("html?")) { page.addTargetRequest(detailUrl + "&prodPrice=" + prodPrices.get(i) + "&storeName=" + storeNames.get(i) + "&prodNum=" + prodNums.get(i)); } else { page.addTargetRequest(detailUrl + "?prodPrice=" + prodPrices.get(i) + "&storeName=" + storeNames.get(i) + "&prodNum=" + prodNums.get(i)); } } } //判断是否爬取了目标数量,否则开启下一页爬取 if (current < this.size) { //获取当前页码 int pageNum = Integer.valueOf(URLUtil.resolve(page.getUrl().toString()).getValue("beginPage")); //最大爬取100页数据,“pageNum + 1” 是根据阿里巴巴分页算法得出 if (pageNum < 100) { page.addTargetRequest(TARGET_URL.replace("#KEYWORD", this.keyWord).replace("#PAGE", String.valueOf(pageNum + 1))); } } } } driver.quit(); } @Override public Site getSite() { return Site.me() .setRetryTimes(5) .setSleepTime(100) .setTimeOut(10000) .setUserAgent(UserAgentSupport.random()); } /** * 初始化爬虫 * * @param keyWord * @return */ public static AlibabaProdProcessor init(String keyWord) { return init(keyWord, 100); } /** * 初始化爬虫(指定爬取限制数量) * * @param keyWord * @return */ public static AlibabaProdProcessor init(String keyWord, long size) { AlibabaProdProcessor processor = new AlibabaProdProcessor(); processor.keyWord = keyWord; processor.size = size; return processor; } /** * 开始爬虫 */ @Override public long run() { Spider.create(this) .addUrl(TARGET_URL.replace("#KEYWORD", this.keyWord).replace("#PAGE", String.valueOf(1))) .thread(6) .run(); return current; } }
39.537688
186
0.5591
8e66fa70b20a87c9fbd78479dade31e2ebee0221
5,590
/** * Copyright 2011-2021 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.dmdl.directio.csv.driver; import java.io.IOException; import java.text.MessageFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.asakusafw.dmdl.directio.csv.driver.CsvFieldTrait.Kind; import com.asakusafw.dmdl.directio.util.DirectFileInputDescriptionGenerator; import com.asakusafw.dmdl.directio.util.DirectFileOutputDescriptionGenerator; import com.asakusafw.dmdl.java.emitter.EmitContext; import com.asakusafw.dmdl.java.spi.JavaDataModelDriver; import com.asakusafw.dmdl.semantics.ModelDeclaration; import com.asakusafw.dmdl.semantics.PropertyDeclaration; import com.asakusafw.dmdl.semantics.Type; import com.asakusafw.dmdl.semantics.type.BasicType; import com.asakusafw.runtime.directio.BinaryStreamFormat; import com.asakusafw.utils.java.model.syntax.Name; /** * Emits {@link BinaryStreamFormat} implementations. * @since 0.2.5 */ public class CsvFormatEmitter extends JavaDataModelDriver { static final Logger LOG = LoggerFactory.getLogger(CsvFormatEmitter.class); /** * Category name for CSV format. */ public static final String CATEGORY_STREAM = "csv"; //$NON-NLS-1$ @Override public void generateResources(EmitContext context, ModelDeclaration model) throws IOException { if (isTarget(model) == false) { return; } checkPropertyType(model); Name supportName = generateFormat(context, model); generateInputDescription(context, supportName, model); generateOutputDescription(context, supportName, model); } private Name generateFormat(EmitContext context, ModelDeclaration model) throws IOException { assert context != null; assert model != null; EmitContext next = new EmitContext( context.getSemantics(), context.getConfiguration(), model, CATEGORY_STREAM, "{0}CsvFormat"); //$NON-NLS-1$ LOG.debug("Generating CSV format for {}", //$NON-NLS-1$ context.getQualifiedTypeName().toNameString()); CsvFormatTrait.Configuration conf = model.getTrait(CsvFormatTrait.class).getConfiguration(); new CsvStreamFormatGenerator(next, model, conf).emit(); LOG.debug("Generated CSV format for {}: {}", //$NON-NLS-1$ context.getQualifiedTypeName().toNameString(), next.getQualifiedTypeName().toNameString()); return next.getQualifiedTypeName(); } private void generateInputDescription( EmitContext context, Name formatClassName, ModelDeclaration model) throws IOException { EmitContext next = new EmitContext( context.getSemantics(), context.getConfiguration(), model, CATEGORY_STREAM, "Abstract{0}CsvInputDescription"); //$NON-NLS-1$ DirectFileInputDescriptionGenerator.Description desc = new DirectFileInputDescriptionGenerator.Description( "CSV file input", context.getQualifiedTypeName()); //$NON-NLS-1$ desc.setFormatClassName(formatClassName); DirectFileInputDescriptionGenerator.generate(next, desc); } private void generateOutputDescription( EmitContext context, Name formatClassName, ModelDeclaration model) throws IOException { EmitContext next = new EmitContext( context.getSemantics(), context.getConfiguration(), model, CATEGORY_STREAM, "Abstract{0}CsvOutputDescription"); //$NON-NLS-1$ DirectFileOutputDescriptionGenerator.Description desc = new DirectFileOutputDescriptionGenerator.Description( "CSV file output", context.getQualifiedTypeName()); //$NON-NLS-1$ desc.setFormatClassName(formatClassName); DirectFileOutputDescriptionGenerator.generate(next, desc); } private boolean isTarget(ModelDeclaration model) { assert model != null; CsvFormatTrait trait = model.getTrait(CsvFormatTrait.class); return trait != null; } private void checkPropertyType(ModelDeclaration model) throws IOException { assert model != null; for (PropertyDeclaration prop : model.getDeclaredProperties()) { if (isValueField(prop)) { Type type = prop.getType(); if ((type instanceof BasicType) == false) { throw new IOException(MessageFormat.format( Messages.getString("CsvFormatEmitter.errorUnsupportedType"), //$NON-NLS-1$ type, prop.getOwner().getName().identifier, prop.getName().identifier)); } } } } static boolean isValueField(PropertyDeclaration property) { assert property != null; return CsvFieldTrait.getKind(property) == Kind.VALUE; } }
41.716418
117
0.671377
9147ded190d07f4bbb65bd434eb2ef3f9cb4763b
5,432
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package graphene.security.tomcat.preaa; import graphene.model.idl.G_User; import graphene.model.idl.G_UserDataAccess; import java.util.Set; import org.apache.avro.AvroRemoteException; import org.apache.catalina.realm.GenericPrincipal; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.ExpiredCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAccount; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.CredentialsMatcher; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.CollectionUtils; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.services.RequestGlobals; import org.slf4j.Logger; import org.tynamo.security.services.SecurityService; /** * A Realm is Shiro terminology for a specialized DAO type object that knows how * to deal with Users, Roles, and Permissions. In online examples this is * sometimes done by called a different DAO for each of those object types. * * With Graphene, we already had a similar object called G_UserDataAccess, which * talks to the appropriate DAOs. (G_UserDataAccess also does much more, and * deals with workspaces and user groups, etc) * * @author djue * */ public class PreAASecurityRealm extends AuthorizingRealm { @Inject private G_UserDataAccess userDataAccess; private Logger logger; static final String REALM_NAME = "preAARealm"; private RequestGlobals rq; @Inject private SecurityService ss; public PreAASecurityRealm(final Logger logger, final RequestGlobals rq) { this.rq = rq; this.logger = logger; logger.debug("Created " + REALM_NAME); setName(REALM_NAME); setCredentialsMatcher(new CredentialsMatcher() { @Override public boolean doCredentialsMatch(final AuthenticationToken token, final AuthenticationInfo info) { logger.debug("doCredentialsMatch " + rq.getHTTPServletRequest().getRemoteUser()); return true; } }); } @Override public void checkRoles(final PrincipalCollection principal, final String... roles) throws AuthorizationException { ss.hasRole("admin"); super.checkRoles(principal, roles); } @Override protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken authToken) throws AuthenticationException { logger.debug("doGetAuthenticationInfo " + authToken.getPrincipal()); // return null; final UsernamePasswordToken upToken = (UsernamePasswordToken) authToken; G_User g_User = null; SimpleAccount account = null; try { g_User = userDataAccess.getByUsername(upToken.getUsername()); final Set<String> roleNames = CollectionUtils.asSet((String[]) null); account = new SimpleAccount(g_User.getUsername(), "password", getName(), roleNames, null); } catch (final AvroRemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (account != null) { if (account.isLocked()) { throw new LockedAccountException("Account [" + account + "] is locked."); } if (account.isCredentialsExpired()) { final String msg = "The credentials for account [" + account + "] are expired"; throw new ExpiredCredentialsException(msg); } } else { logger.error("user was null"); } return account; } @Override protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) { logger.debug("doGetAuthorizationInfo " + principals.asList()); // return null; final Set<String> roleNames = CollectionUtils.asSet((String[]) null); final SimpleAccount simpleAccount = new SimpleAccount(getUsername(principals), "password", getName(), roleNames, null); return simpleAccount; } protected String getUsername(final PrincipalCollection principals) { return getAvailablePrincipal(principals).toString(); } @Override public boolean hasRole(final PrincipalCollection principal, final String roleIdentifier) { // TODO Auto-generated method stub // return super.hasRole(principal, roleIdentifier); for (final Object p : principal.fromRealm(REALM_NAME)) { if (p instanceof GenericPrincipal) { final GenericPrincipal gp = (GenericPrincipal) p; for (final String r : gp.getRoles()) { if (r.equals(roleIdentifier)) { return true; } } } } return false; } }
33.95
115
0.759941
704fc44326f4fe69d9384edb5e7c50aef12d1689
22,571
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v4ox.print; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.pdf.PdfDocument.Page; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.CancellationSignal; import android.os.ParcelFileDescriptor; import android.print.PageRange; import android.print.PrintAttributes; import android.print.PrintDocumentAdapter; import android.print.PrintDocumentInfo; import android.print.PrintManager; import android.print.pdf.PrintedPdfDocument; import android.util.Log; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Kitkat specific PrintManager API implementation. */ class PrintHelperKitkat { private static final String LOG_TAG = "PrintHelperKitkat"; // will be <= 300 dpi on A4 (8.3×11.7) paper (worst case of 150 dpi) private final static int MAX_PRINT_SIZE = 3500; final Context mContext; BitmapFactory.Options mDecodeOptions = null; private final Object mLock = new Object(); /** * image will be scaled but leave white space */ public static final int SCALE_MODE_FIT = 1; /** * image will fill the paper and be cropped (default) */ public static final int SCALE_MODE_FILL = 2; /** * select landscape (default) */ public static final int ORIENTATION_LANDSCAPE = 1; /** * select portrait */ public static final int ORIENTATION_PORTRAIT = 2; /** * this is a black and white image */ public static final int COLOR_MODE_MONOCHROME = 1; /** * this is a color image (default) */ public static final int COLOR_MODE_COLOR = 2; public interface OnPrintFinishCallback { void onFinish(); } int mScaleMode = SCALE_MODE_FILL; int mColorMode = COLOR_MODE_COLOR; int mOrientation = ORIENTATION_LANDSCAPE; PrintHelperKitkat(Context context) { mContext = context; } /** * Selects whether the image will fill the paper and be cropped * <p/> * {@link #SCALE_MODE_FIT} * or whether the image will be scaled but leave white space * {@link #SCALE_MODE_FILL}. * * @param scaleMode {@link #SCALE_MODE_FIT} or * {@link #SCALE_MODE_FILL} */ public void setScaleMode(int scaleMode) { mScaleMode = scaleMode; } /** * Returns the scale mode with which the image will fill the paper. * * @return The scale Mode: {@link #SCALE_MODE_FIT} or * {@link #SCALE_MODE_FILL} */ public int getScaleMode() { return mScaleMode; } /** * Sets whether the image will be printed in color (default) * {@link #COLOR_MODE_COLOR} or in back and white * {@link #COLOR_MODE_MONOCHROME}. * * @param colorMode The color mode which is one of * {@link #COLOR_MODE_COLOR} and {@link #COLOR_MODE_MONOCHROME}. */ public void setColorMode(int colorMode) { mColorMode = colorMode; } /** * Sets whether to select landscape (default), {@link #ORIENTATION_LANDSCAPE} * or portrait {@link #ORIENTATION_PORTRAIT} * @param orientation The page orientation which is one of * {@link #ORIENTATION_LANDSCAPE} or {@link #ORIENTATION_PORTRAIT}. */ public void setOrientation(int orientation) { mOrientation = orientation; } /** * Gets the page orientation with which the image will be printed. * * @return The preferred orientation which is one of * {@link #ORIENTATION_LANDSCAPE} or {@link #ORIENTATION_PORTRAIT} */ public int getOrientation() { return mOrientation; } /** * Gets the color mode with which the image will be printed. * * @return The color mode which is one of {@link #COLOR_MODE_COLOR} * and {@link #COLOR_MODE_MONOCHROME}. */ public int getColorMode() { return mColorMode; } /** * Prints a bitmap. * * @param jobName The print job name. * @param bitmap The bitmap to print. * @param callback Optional callback to observe when printing is finished. */ public void printBitmap(final String jobName, final Bitmap bitmap, final OnPrintFinishCallback callback) { if (bitmap == null) { return; } final int fittingMode = mScaleMode; // grab the fitting mode at time of call PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE); PrintAttributes.MediaSize mediaSize = PrintAttributes.MediaSize.UNKNOWN_PORTRAIT; if (bitmap.getWidth() > bitmap.getHeight()) { mediaSize = PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE; } PrintAttributes attr = new PrintAttributes.Builder() .setMediaSize(mediaSize) .setColorMode(mColorMode) .build(); printManager.print(jobName, new PrintDocumentAdapter() { private PrintAttributes mAttributes; @Override public void onLayout(PrintAttributes oldPrintAttributes, PrintAttributes newPrintAttributes, CancellationSignal cancellationSignal, LayoutResultCallback layoutResultCallback, Bundle bundle) { mAttributes = newPrintAttributes; PrintDocumentInfo info = new PrintDocumentInfo.Builder(jobName) .setContentType(PrintDocumentInfo.CONTENT_TYPE_PHOTO) .setPageCount(1) .build(); boolean changed = !newPrintAttributes.equals(oldPrintAttributes); layoutResultCallback.onLayoutFinished(info, changed); } @Override public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor fileDescriptor, CancellationSignal cancellationSignal, WriteResultCallback writeResultCallback) { PrintedPdfDocument pdfDocument = new PrintedPdfDocument(mContext, mAttributes); Bitmap maybeGrayscale = convertBitmapForColorMode(bitmap, mAttributes.getColorMode()); try { Page page = pdfDocument.startPage(1); RectF content = new RectF(page.getInfo().getContentRect()); Matrix matrix = getMatrix( maybeGrayscale.getWidth(), maybeGrayscale.getHeight(), content, fittingMode); // Draw the bitmap. page.getCanvas().drawBitmap(maybeGrayscale, matrix, null); // Finish the page. pdfDocument.finishPage(page); try { // Write the document. pdfDocument.writeTo(new FileOutputStream( fileDescriptor.getFileDescriptor())); // Done. writeResultCallback.onWriteFinished( new PageRange[]{PageRange.ALL_PAGES}); } catch (IOException ioe) { // Failed. Log.e(LOG_TAG, "Error writing printed content", ioe); writeResultCallback.onWriteFailed(null); } } finally { if (pdfDocument != null) { pdfDocument.close(); } if (fileDescriptor != null) { try { fileDescriptor.close(); } catch (IOException ioe) { /* ignore */ } } // If we created a new instance for grayscaling, then recycle it here. if (maybeGrayscale != bitmap) { maybeGrayscale.recycle(); } } } @Override public void onFinish() { if (callback != null) { callback.onFinish(); } } }, attr); } /** * Calculates the transform the print an Image to fill the page * * @param imageWidth with of bitmap * @param imageHeight height of bitmap * @param content The output page dimensions * @param fittingMode The mode of fitting {@link #SCALE_MODE_FILL} vs {@link #SCALE_MODE_FIT} * @return Matrix to be used in canvas.drawBitmap(bitmap, matrix, null) call */ private Matrix getMatrix(int imageWidth, int imageHeight, RectF content, int fittingMode) { Matrix matrix = new Matrix(); // Compute and apply scale to fill the page. float scale = content.width() / imageWidth; if (fittingMode == SCALE_MODE_FILL) { scale = Math.max(scale, content.height() / imageHeight); } else { scale = Math.min(scale, content.height() / imageHeight); } matrix.postScale(scale, scale); // Center the content. final float translateX = (content.width() - imageWidth * scale) / 2; final float translateY = (content.height() - imageHeight * scale) / 2; matrix.postTranslate(translateX, translateY); return matrix; } /** * Prints an image located at the Uri. Image types supported are those of * <code>BitmapFactory.decodeStream</code> (JPEG, GIF, PNG, BMP, WEBP) * * @param jobName The print job name. * @param imageFile The <code>Uri</code> pointing to an image to print. * @param callback Optional callback to observe when printing is finished. * @throws FileNotFoundException if <code>Uri</code> is not pointing to a valid image. */ public void printBitmap(final String jobName, final Uri imageFile, final OnPrintFinishCallback callback) throws FileNotFoundException { final int fittingMode = mScaleMode; PrintDocumentAdapter printDocumentAdapter = new PrintDocumentAdapter() { private PrintAttributes mAttributes; AsyncTask<Uri, Boolean, Bitmap> mLoadBitmap; Bitmap mBitmap = null; @Override public void onLayout(final PrintAttributes oldPrintAttributes, final PrintAttributes newPrintAttributes, final CancellationSignal cancellationSignal, final LayoutResultCallback layoutResultCallback, Bundle bundle) { mAttributes = newPrintAttributes; if (cancellationSignal.isCanceled()) { layoutResultCallback.onLayoutCancelled(); return; } // we finished the load if (mBitmap != null) { PrintDocumentInfo info = new PrintDocumentInfo.Builder(jobName) .setContentType(PrintDocumentInfo.CONTENT_TYPE_PHOTO) .setPageCount(1) .build(); boolean changed = !newPrintAttributes.equals(oldPrintAttributes); layoutResultCallback.onLayoutFinished(info, changed); return; } mLoadBitmap = new AsyncTask<Uri, Boolean, Bitmap>() { @Override protected void onPreExecute() { // First register for cancellation requests. cancellationSignal.setOnCancelListener( new CancellationSignal.OnCancelListener() { @Override public void onCancel() { // on different thread cancelLoad(); cancel(false); } }); } @Override protected Bitmap doInBackground(Uri... uris) { try { return loadConstrainedBitmap(imageFile, MAX_PRINT_SIZE); } catch (FileNotFoundException e) { /* ignore */ } return null; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); mBitmap = bitmap; if (bitmap != null) { PrintDocumentInfo info = new PrintDocumentInfo.Builder(jobName) .setContentType(PrintDocumentInfo.CONTENT_TYPE_PHOTO) .setPageCount(1) .build(); boolean changed = !newPrintAttributes.equals(oldPrintAttributes); layoutResultCallback.onLayoutFinished(info, changed); } else { layoutResultCallback.onLayoutFailed(null); } mLoadBitmap = null; } @Override protected void onCancelled(Bitmap result) { // Task was cancelled, report that. layoutResultCallback.onLayoutCancelled(); mLoadBitmap = null; } }.execute(); } private void cancelLoad() { synchronized (mLock) { // prevent race with set null below if (mDecodeOptions != null) { mDecodeOptions.requestCancelDecode(); mDecodeOptions = null; } } } @Override public void onFinish() { super.onFinish(); cancelLoad(); if (mLoadBitmap != null) { mLoadBitmap.cancel(true); } if (callback != null) { callback.onFinish(); } if (mBitmap != null) { mBitmap.recycle(); mBitmap = null; } } @Override public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor fileDescriptor, CancellationSignal cancellationSignal, WriteResultCallback writeResultCallback) { PrintedPdfDocument pdfDocument = new PrintedPdfDocument(mContext, mAttributes); Bitmap maybeGrayscale = convertBitmapForColorMode(mBitmap, mAttributes.getColorMode()); try { Page page = pdfDocument.startPage(1); RectF content = new RectF(page.getInfo().getContentRect()); // Compute and apply scale to fill the page. Matrix matrix = getMatrix(mBitmap.getWidth(), mBitmap.getHeight(), content, fittingMode); // Draw the bitmap. page.getCanvas().drawBitmap(maybeGrayscale, matrix, null); // Finish the page. pdfDocument.finishPage(page); try { // Write the document. pdfDocument.writeTo(new FileOutputStream( fileDescriptor.getFileDescriptor())); // Done. writeResultCallback.onWriteFinished( new PageRange[]{PageRange.ALL_PAGES}); } catch (IOException ioe) { // Failed. Log.e(LOG_TAG, "Error writing printed content", ioe); writeResultCallback.onWriteFailed(null); } } finally { if (pdfDocument != null) { pdfDocument.close(); } if (fileDescriptor != null) { try { fileDescriptor.close(); } catch (IOException ioe) { /* ignore */ } } // If we created a new instance for grayscaling, then recycle it here. if (maybeGrayscale != mBitmap) { maybeGrayscale.recycle(); } } } }; PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE); PrintAttributes.Builder builder = new PrintAttributes.Builder(); builder.setColorMode(mColorMode); if (mOrientation == ORIENTATION_LANDSCAPE) { builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE); } else if (mOrientation == ORIENTATION_PORTRAIT) { builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_PORTRAIT); } PrintAttributes attr = builder.build(); printManager.print(jobName, printDocumentAdapter, attr); } /** * Loads a bitmap while limiting its size * * @param uri location of a valid image * @param maxSideLength the maximum length of a size * @return the Bitmap * @throws FileNotFoundException if the Uri does not point to an image */ private Bitmap loadConstrainedBitmap(Uri uri, int maxSideLength) throws FileNotFoundException { if (maxSideLength <= 0 || uri == null || mContext == null) { throw new IllegalArgumentException("bad argument to getScaledBitmap"); } // Get width and height of stored bitmap BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; loadBitmap(uri, opt); int w = opt.outWidth; int h = opt.outHeight; // If bitmap cannot be decoded, return null if (w <= 0 || h <= 0) { return null; } // Find best downsampling size int imageSide = Math.max(w, h); int sampleSize = 1; while (imageSide > maxSideLength) { imageSide >>>= 1; sampleSize <<= 1; } // Make sure sample size is reasonable if (sampleSize <= 0 || 0 >= Math.min(w, h) / sampleSize) { return null; } BitmapFactory.Options decodeOptions = null; synchronized (mLock) { // prevent race with set null below mDecodeOptions = new BitmapFactory.Options(); mDecodeOptions.inMutable = true; mDecodeOptions.inSampleSize = sampleSize; decodeOptions = mDecodeOptions; } try { return loadBitmap(uri, decodeOptions); } finally { synchronized (mLock) { mDecodeOptions = null; } } } /** * Returns the bitmap from the given uri loaded using the given options. * Returns null on failure. */ private Bitmap loadBitmap(Uri uri, BitmapFactory.Options o) throws FileNotFoundException { if (uri == null || mContext == null) { throw new IllegalArgumentException("bad argument to loadBitmap"); } InputStream is = null; try { is = mContext.getContentResolver().openInputStream(uri); return BitmapFactory.decodeStream(is, null, o); } finally { if (is != null) { try { is.close(); } catch (IOException t) { Log.w(LOG_TAG, "close fail ", t); } } } } private Bitmap convertBitmapForColorMode(Bitmap original, int colorMode) { if (colorMode != COLOR_MODE_MONOCHROME) { return original; } // Create a grayscale bitmap Bitmap grayscale = Bitmap.createBitmap(original.getWidth(), original.getHeight(), Config.ARGB_8888); Canvas c = new Canvas(grayscale); Paint p = new Paint(); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); p.setColorFilter(f); c.drawBitmap(original, 0, 0, p); c.setBitmap(null); return grayscale; } }
38.517065
100
0.530504
381fa09de45ff98a8537770f3f04dee5b54ecfa6
6,111
package com.jingjie.forum_demo.service; import com.jingjie.forum_demo.util.JedisAdapter; import com.jingjie.forum_demo.util.RedisKeyUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import redis.clients.jedis.Transaction; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; /** * * Follow and unfollow related services. * * @author jingjiejiang * @history * 1. Created on Feb 1, 2018 */ @Service public class FollowService { @Autowired JedisAdapter jedisAdapter; /** * * Follow an entity. * * @param userId * @param entityType * @param entityId * @return */ public boolean follow (int userId, int entityType, int entityId) { String followerKey = RedisKeyUtil.getKeyFollower(entityType, entityId); String followeeKey = RedisKeyUtil.getKeyFollowee(userId, entityType); Date date = new Date(); // user transaction to finish a follow action // 1) add a follower to zset // 2) add a followee to zset Jedis jedis = jedisAdapter.getJedis(); Transaction trans = jedisAdapter.startOfTransac(jedis); // score is the date that follow happens trans.zadd(followerKey, date.getTime(), String.valueOf(userId)); trans.zadd(followeeKey, date.getTime(), String.valueOf(entityId)); List<Object> res = jedisAdapter.execTransac(trans, jedis); return res.size() == 2 && (long) res.get(0) > 0 && (long) res.get(1) > 0; } /** * * Unfollow an entity. * * @param userId * @param entityType * @param entityId * @return */ public boolean unfollow (int userId, int entityType, int entityId) { String followerKey = RedisKeyUtil.getKeyFollower(entityType, entityId); String followeeKey = RedisKeyUtil.getKeyFollowee(userId, entityType); Date date = new Date(); // user transaction to finish a follow action // 1) add a follower to zset // 2) add a followee to zset Jedis jedis = jedisAdapter.getJedis(); Transaction trans = jedisAdapter.startOfTransac(jedis); // score is the date that follow happens trans.zrem(followerKey, String.valueOf(userId)); trans.zrem(followeeKey, String.valueOf(entityId)); List<Object> res = jedisAdapter.execTransac(trans, jedis); return res.size() == 2 && (long) res.get(0) > 0 && (long) res.get(1) > 0; } /** * * Get a list of followers ids (userIds) from tail to head. * NB: start from 0. * * @param entityType * @param entityId * @param count * @return */ public List<Integer> getFollowersId (int entityType, int entityId, int count) { String followerKey = RedisKeyUtil.getKeyFollower(entityType, entityId); return getIdsFromSet(jedisAdapter.getSortedSetElemsRev(followerKey, 0, count)); } /** * * Get a list of followers ids (userIds) from tail to head. * NB: start from offset. * * @param entityType * @param entityId * @param offset * @param count * @return */ public List<Integer> getFollowersIdWithOffset (int entityType, int entityId, int offset, int count) { String followerKey = RedisKeyUtil.getKeyFollower(entityType, entityId); return getIdsFromSet(jedisAdapter.getSortedSetElemsRev(followerKey, offset, offset + count)); } /** * * Get a list of followee ids (entityIds) from tail to head. * NB: start from 0. * * @param userId * @param entityType * @param count * @return */ public List<Integer> getFollowees (int userId, int entityType, int count) { String followeeKey = RedisKeyUtil.getKeyFollowee(userId, entityType); return getIdsFromSet(jedisAdapter.getSortedSetElemsRev(followeeKey, 0, count)); } /** * * Get a list of followee ids (entityIds) from tail to head. * NB: start from offset. * * @param userId * @param entityType * @param offset * @param count * @return */ public List<Integer> getFolloweesIdWithOffset (int userId, int entityType, int offset, int count) { String followeeKey = RedisKeyUtil.getKeyFollowee(userId, entityType); return getIdsFromSet(jedisAdapter.getSortedSetElemsRev(followeeKey, offset, offset + count)); } private List<Integer> getIdsFromSet (Set<String> idSet) { List<Integer> ids = new ArrayList<>(); for (String str : idSet) { ids.add(Integer.parseInt(str)); } return ids; } /** * * Get the number of followers for a given entity. * * @param entityType * @param entityId * @return */ public long getFollowerCount (int entityType, int entityId) { String followerKey = RedisKeyUtil.getKeyFollower(entityType, entityId); return jedisAdapter.getCardOfSortedSet(followerKey); } /** * * Get the number of followee for a given user with a given entityType. * * @param userId * @param entityType * @return */ public long getFolloweeCount (int userId, int entityType) { String followeeKey = RedisKeyUtil.getKeyFollowee(userId, entityType); return jedisAdapter.getCardOfSortedSet(followeeKey); } /** * * Check whether a user follows a given entity. * * @param userId * @param entityType * @param entityId * @return */ public boolean isFollower (int userId, int entityType, int entityId) { String followerKey = RedisKeyUtil.getKeyFollower(entityType, entityId); return jedisAdapter.getSoreInSortedSet(followerKey, String.valueOf(userId)) != null; } }
28.423256
92
0.622648
fe4ed59e1205e0cb9bf6d503059a03fb07ac0850
6,986
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.carapaceproxy.backends; import org.carapaceproxy.utils.TestUtils; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.carapaceproxy.server.RequestHandler.PROPERTY_URI; import static org.junit.Assert.assertEquals; import com.github.tomakehurst.wiremock.http.Fault; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.util.Properties; import org.carapaceproxy.client.ConnectionsManagerStats; import org.carapaceproxy.client.EndpointKey; import org.carapaceproxy.client.impl.ConnectionsManagerImpl; import org.carapaceproxy.configstore.PropertiesConfigurationStore; import org.carapaceproxy.server.HttpProxyServer; import org.carapaceproxy.server.config.NetworkListenerConfiguration; import org.carapaceproxy.utils.RawHttpClient; import static org.junit.Assert.assertTrue; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.carapaceproxy.server.config.ActionConfiguration; import org.carapaceproxy.server.config.BackendConfiguration; import org.carapaceproxy.server.config.DirectorConfiguration; import org.carapaceproxy.server.config.RouteConfiguration; import org.carapaceproxy.server.mapper.StandardEndpointMapper; import org.carapaceproxy.server.mapper.requestmatcher.RegexpRequestMatcher; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; @RunWith(JUnitParamsRunner.class) public class StuckRequestsTest { @Rule public WireMockRule wireMockRule = new WireMockRule(0); @Rule public TemporaryFolder tmpDir = new TemporaryFolder(); @Test @Parameters({"true", "false"}) public void testBackendUnreachableOnStuckRequest(boolean backendsUnreachableOnStuckRequests) throws Exception { stubFor(get(urlEqualTo("/index.html")) .willReturn(aResponse() .withFault(Fault.EMPTY_RESPONSE))); stubFor(get(urlEqualTo("/good-index.html")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/html") .withHeader("Content-Length", "it <b>works</b> !!".length() + "") .withBody("it <b>works</b> !!"))); final int theport = wireMockRule.port(); EndpointKey key = new EndpointKey("localhost", theport); StandardEndpointMapper mapper = new StandardEndpointMapper(); mapper.addBackend(new BackendConfiguration("backend-a", "localhost", theport, "/")); mapper.addDirector(new DirectorConfiguration("director-1").addBackend("backend-a")); mapper.addAction(new ActionConfiguration("proxy-1", ActionConfiguration.TYPE_PROXY, "director-1", null, -1)); mapper.addRoute(new RouteConfiguration("route-1", "proxy-1", true, new RegexpRequestMatcher(PROPERTY_URI, ".*index.html.*"))); ConnectionsManagerStats stats; try (HttpProxyServer server = new HttpProxyServer(mapper, tmpDir.newFolder());) { Properties properties = new Properties(); properties.put("connectionsmanager.stuckrequesttimeout", "100"); // ms properties.put("connectionsmanager.backendsunreachableonstuckrequests", backendsUnreachableOnStuckRequests + ""); // configure resets all listeners configurations server.configureAtBoot(new PropertiesConfigurationStore(properties)); server.addListener(new NetworkListenerConfiguration("localhost", 0)); server.setMapper(mapper); assertEquals(100, server.getCurrentConfiguration().getStuckRequestTimeout()); assertEquals(backendsUnreachableOnStuckRequests, server.getCurrentConfiguration().isBackendsUnreachableOnStuckRequests()); server.start(); stats = server.getConnectionsManager().getStats(); int port = server.getLocalPort(); assertTrue(port > 0); try (RawHttpClient client = new RawHttpClient("localhost", port)) { RawHttpClient.HttpResponse resp = client.executeRequest("GET /index.html HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"); String s = resp.toString(); System.out.println("s:" + s); assertEquals("HTTP/1.1 500 Internal Server Error\r\n", resp.getStatusLine()); assertEquals("<html>\n" + " <body>\n" + " An internal error occurred\n" + " </body> \n" + "</html>\n", resp.getBodyString()); } TestUtils.waitForCondition(TestUtils.ALL_CONNECTIONS_CLOSED(stats), 100); Double value = ((ConnectionsManagerImpl) server.getConnectionsManager()).getPENDING_REQUESTS_GAUGE().get(); assertEquals(0, value.intValue()); assertEquals(backendsUnreachableOnStuckRequests, !server.getBackendHealthManager().isAvailable(key.getHostPort())); try (RawHttpClient client = new RawHttpClient("localhost", port)) { RawHttpClient.HttpResponse resp = client.executeRequest("GET /good-index.html HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"); String s = resp.toString(); System.out.println("s:" + s); if (backendsUnreachableOnStuckRequests) { assertEquals("HTTP/1.1 500 Internal Server Error\r\n", resp.getStatusLine()); assertEquals("<html>\n" + " <body>\n" + " An internal error occurred\n" + " </body> \n" + "</html>\n", resp.getBodyString()); } else { assertEquals("HTTP/1.1 200 OK\r\n", resp.getStatusLine()); assertEquals("it <b>works</b> !!", resp.getBodyString()); } } } } }
49.9
153
0.676066
2ad75b23bba94339cc34c5cdcb35081384991a2c
3,149
/** * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.ga.metaheuristics.mulambda; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.evosuite.ga.Chromosome; import org.evosuite.ga.ChromosomeFactory; import org.evosuite.ga.FitnessFunction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * (Mu, Lambda) EA * * @author José Campos */ public class MuLambdaEA<T extends Chromosome> extends AbstractMuLambda<T> { private static final long serialVersionUID = -1104094637643130537L; private static final Logger logger = LoggerFactory.getLogger(MuLambdaEA.class); public MuLambdaEA(ChromosomeFactory<T> factory, int mu, int lambda) { super(factory, mu, lambda); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void evolve() { List<T> offspring = new ArrayList<T>(this.lambda); // create new offspring by mutating current population for (int i = 0; i < this.mu; i++) { for (int j = 0; j < this.lambda / this.mu; j++) { T t = (T) this.population.get(i).clone(); do { this.notifyMutation(t); t.mutate(); } while (!t.isChanged()); offspring.add(t); } } // update fitness values of offspring for (T t : offspring) { for (FitnessFunction<T> fitnessFunction : this.fitnessFunctions) { fitnessFunction.getFitness(t); this.notifyEvaluation(t); } } if (this.getFitnessFunction().isMaximizationFunction()) { // this if condition assumes *all* fitness functions are either to be maximized or to be // minimized // sort offspring from the one with the highest fitness value to the one with the lowest // fitness value Collections.sort(offspring, Collections.reverseOrder()); } else { // sort offspring from the one with the lowest fitness value to the one with the highest // fitness value Collections.sort(offspring); } // replace mu (i.e., population) out of lambda (i.e., offspring) for (int i = 0; i < this.population.size(); i++) { logger.debug("replacing " + this.population.get(i).getFitness() + " with " + offspring.get(i).getFitness()); this.population.set(i, offspring.get(i)); } } }
32.802083
95
0.658622
b053ef388007f14559a7d6f9417523b382306839
674
package com.vaadin.tests.components.ui; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.vaadin.testbench.elements.LabelElement; import com.vaadin.tests.tb3.MultiBrowserTest; public class UIsInMultipleTabsTest extends MultiBrowserTest { @Test public void testPageReloadChangesUI() throws Exception { openTestURL(); assertUI(1); openTestURL(); assertUI(2); openTestURL("restartApplication"); assertUI(1); } private void assertUI(int i) { assertEquals("Unexpected UI found,", "This is UI number " + i, $(LabelElement.class).first().getText()); } }
24.962963
70
0.672107
3907dba5b3d10487382d79dc2a77b3e3fc3a625e
1,159
package com.ukubuka.core.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.ukubuka.core.exception.TransformException; /** * Load Operation * * @author agrawroh * @version v1.0 */ @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum LoadOperation { JOIN("join"), DISTINCT("distinct"); /* Operation */ private String operation; /********** Private Constructor **********/ private LoadOperation(final String operation) { this.operation = operation; } /** * @return the operation */ public String getOperation() { return operation; } /** * Get Operation * * @param operation * @return TransformOperation * @throws TransformException */ public static LoadOperation getOperation(final String source) throws TransformException { for (final LoadOperation transformOperation : LoadOperation.values()) { if (transformOperation.getOperation().equals(source)) { return transformOperation; } } throw new TransformException("Unsupported Operation!"); } }
23.653061
79
0.629853
808a7d7a381f34181891e6011da93987372dab47
174
package es.cic.curso.curso18.mascotastarcraft.service.starcraft; public interface StarcraftService { void annadirTrabajador(String tipoTrabajador, Long idBase); }
21.75
64
0.793103
f1467f1b16dfca6c62330f11a3bb1dc7b04a0454
1,609
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.run; import com.android.tools.deployer.UIService; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; public class IdeService implements UIService { public static final String TITLE = "Application Installation Failed"; private final Project project; public IdeService(Project project) { this.project = project; } @Override public boolean prompt(@NotNull String message) { return UIUtil.invokeAndWaitIfNeeded(() -> { int result = Messages.showOkCancelDialog( project, message, TITLE, Messages.getQuestionIcon()); return result == Messages.OK; }); } @Override public void message(@NotNull String message) { ApplicationManager.getApplication().invokeLater( () -> Messages.showErrorDialog(project, message, TITLE)); } }
32.836735
75
0.742076
777cc2a9f281359da1ba32ec6f606a9cbedc7416
71
package me.shaftesbury.codegenerator.text; public interface ILine { }
14.2
42
0.802817
bde29c5bbde80933abd2a10f07ee8ecd291c9d59
17,174
/* * The MIT License * * Copyright 2016 Vladimir Syso. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.syso.phonebook.service; import java.io.IOException; import java.io.StringWriter; import java.util.Collection; import java.util.Objects; import java.util.UUID; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.fluent.Content; import org.apache.http.client.fluent.Request; import org.apache.http.client.fluent.Response; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.syso.phonebook.controllers.helpers.JAXBMapper; import org.syso.phonebook.domain.Contact; import org.syso.phonebook.domain.Contacts; import org.syso.phonebook.domain.PhoneNumber; import org.syso.phonebook.domain.PhoneType; /** * PhonebookServiceTest performs unit tests for Servlet and Jersey * implementations of the Phonebook REST API * * @author Vladimir Syso */ @RunWith(value = Parameterized.class) public class PhonebookServiceTest { // Test two following serives via Parameters public static final String JERSEY_REST_SERVICE_URL = "http://localhost:8080/Phonebook/jersey"; public static final String SERVLET_REST_SERVICE_URL = "http://localhost:8080/Phonebook/servlet"; @Parameter public String baseURL; CloseableHttpClient httpClient; private final String testFirstName; private final String testLastName; private final String testPhoneNumber; private final String testPhoneType; private String testContactLocation; private boolean deleteContactOnTearDown; public PhonebookServiceTest() { this.testFirstName = UUID.randomUUID().toString(); this.testLastName = UUID.randomUUID().toString(); this.testPhoneType = "TestPhoneType"; this.testPhoneNumber = "+09(876)543-21-00"; } /** * * @return an array of service URL */ @Parameters public static Object[] data() { return new Object[]{ JERSEY_REST_SERVICE_URL, SERVLET_REST_SERVICE_URL }; } @Before public void setUp() throws IOException { // Create test contact for all tests Contact contact = new Contact(); contact.setFirstName(testFirstName); contact.setLastName(testLastName); JAXBMapper<Contact> adapter = new JAXBMapper<>(Contact.class); StringWriter out = new StringWriter(); adapter.marshal(contact, out, JAXBMapper.MEDIA_TYPE_XML); HttpResponse response = Request.Post(baseURL + "/contact") .bodyString(out.toString(), ContentType.APPLICATION_XML) .execute().returnResponse(); Header[] headers = response.getHeaders("Location"); testContactLocation = headers[0].getValue(); deleteContactOnTearDown = true; } @After public void tearDown() throws IOException { if(deleteContactOnTearDown){ Request.Delete(testContactLocation).execute(); } } /** * Test of findAllContacts method, of class PhonebookService via HTTP * @throws IOException */ @Test public void testFindAllContacts() throws IOException { System.out.println("getContacts"); // Get all contacts Content content = Request.Get(baseURL + "/contacts/").execute().returnContent(); JAXBMapper<Contacts> adapter = new JAXBMapper<>(Contacts.class); Contacts contacts = adapter.unmarshal(content.asString(), JAXBMapper.MEDIA_TYPE_XML); assertNotNull(contacts); Collection<Contact> contactList = contacts.getContacts(); assertFalse(contactList.isEmpty()); // Check the test contact in the list Integer contactId = Integer.valueOf(testContactLocation.substring(testContactLocation.lastIndexOf('/') + 1)); boolean contactFound = false; for (Contact contact : contactList) { if (Objects.equals(contact.getContactId(), contactId)) { assertEquals(contact.getFirstName(), testFirstName); assertEquals(contact.getLastName(), testLastName); contactFound = true; break; } } assertTrue("Test Contact is not enlisted in /contacts", contactFound); } /** * Test of addPhoneNumber method, of class PhonebookService. * @throws java.io.IOException */ @Test public void testAddPhoneNumber() throws IOException { System.out.println("addPhoneNumber"); // Add a test number String jsonRequest = String.format("{\"number\":\"%s\", \"type\":\"%s\"}", testPhoneNumber, testPhoneType); Response response = Request.Post(testContactLocation + "/add_number") .bodyString(jsonRequest, ContentType.APPLICATION_JSON) .execute(); assertEquals(response.returnResponse().getStatusLine().getStatusCode(), HttpStatus.SC_CREATED); // Check number was added to contact response = Request.Get(testContactLocation).execute(); Content content = response.returnContent(); JAXBMapper<Contact> adapter = new JAXBMapper<>(Contact.class); Contact contact = adapter.unmarshal(content.asString(), JAXBMapper.MEDIA_TYPE_XML); assertNotNull(contact); Collection<PhoneNumber> phoneNumbers = contact.getPhoneNumbers(); assertNotNull(phoneNumbers); assertEquals(phoneNumbers.size(), 1); PhoneNumber phoneNumber = phoneNumbers.iterator().next(); assertNotNull(phoneNumber.getNumber()); assertEquals(phoneNumber.getNumber(), testPhoneNumber); assertNotNull(phoneNumber.getType()); assertEquals(phoneNumber.getType().getPhoneTypeName(), testPhoneType); } /** * Test of findContactsByNumber method, of class PhonebookService. * @throws java.io.IOException */ @Test public void testFindContactsByNumber() throws IOException { System.out.println("findContactsByNumber"); // Add a test number String jsonRequest = String.format("{\"number\":\"%s\", \"type\":\"%s\"}", testPhoneNumber, testPhoneType); Response response = Request.Post(testContactLocation + "/add_number") .bodyString(jsonRequest, ContentType.APPLICATION_JSON) .execute(); assertEquals(response.returnResponse().getStatusLine().getStatusCode(), HttpStatus.SC_CREATED); // Test the test contact can be found by number String findByNumberURL = baseURL + "/contacts/find_by_number?phone_number=" + testPhoneNumber + "&match=true"; response = Request.Get(findByNumberURL).execute(); Content content = response.returnContent(); JAXBMapper<Contacts> adapter = new JAXBMapper<>(Contacts.class); Contacts contacts = adapter.unmarshal(content.asString(), JAXBMapper.MEDIA_TYPE_XML); assertNotNull(contacts); Collection<Contact> contactList = contacts.getContacts(); assertNotNull(contactList); assertFalse(contactList.isEmpty()); assertEquals(contactList.size(), 1); Contact contact = contactList.iterator().next(); assertNotNull(contact); Collection<PhoneNumber> phoneNumbers = contact.getPhoneNumbers(); assertNotNull(phoneNumbers); assertEquals(phoneNumbers.size(), 1); PhoneNumber phoneNumber = phoneNumbers.iterator().next(); assertEquals(phoneNumber.getNumber(),testPhoneNumber); assertNotNull(phoneNumber.getType()); assertEquals(phoneNumber.getType().getPhoneTypeName(),testPhoneType); } /** * Test of findContact method, of class PhonebookService. * @throws java.io.IOException */ @Test public void testGetContact() throws IOException { System.out.println("getContact"); // Retreive test contact Response response = Request.Get(testContactLocation).execute(); Content content = response.returnContent(); JAXBMapper<Contact> adapter = new JAXBMapper<>(Contact.class); Contact contact = adapter.unmarshal(content.asString(), JAXBMapper.MEDIA_TYPE_XML); assertNotNull(contact); assertEquals(contact.getFirstName(), testFirstName); assertEquals(contact.getLastName(), testLastName); } /** * Test of createContact method, of class PhonebookService. * @throws java.io.IOException */ @Test public void testCreateContact() throws IOException { System.out.println("CreateContact"); // Test account created in SetUp Response response = Request.Get(testContactLocation).execute(); Content content = response.returnContent(); JAXBMapper<Contact> adapter = new JAXBMapper<>(Contact.class); Contact testContact = adapter.unmarshal(content.asString(), content.getType().getMimeType()); assertEquals(testContact.getFirstName(), testFirstName); assertEquals(testContact.getLastName(), testLastName); // Create another Contact with the same Name with JSON String jsonRequest = String.format("{\"firstName\":\"%s\", \"lastName\":\"%s\"}", testFirstName, testLastName); response = Request.Post(baseURL + "/contact") .bodyString(jsonRequest, ContentType.APPLICATION_JSON) .execute(); HttpResponse httpResponse = response.returnResponse(); assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED); Header[] headers = httpResponse.getHeaders("Location"); assertNotNull(headers); String newContactLocation = headers[0].getValue(); assertNotNull(newContactLocation); // Test that new contact was created and valid response = Request.Get(newContactLocation).execute(); content = response.returnContent(); Contact newContact = adapter.unmarshal(content.asString(), content.getType().getMimeType()); assertNotNull(newContact); assertEquals(newContact.getFirstName(), testFirstName); assertEquals(newContact.getLastName(), testLastName); // Check the Contact created from the SetUp is not the same one created with JSON and the identical name Integer contactId = Integer.valueOf(newContactLocation.substring(newContactLocation.lastIndexOf('/') + 1)); assertNotEquals(contactId, testContact.getContactId()); // Delete the contact response = Request.Delete(testContactLocation).execute(); assertEquals(response.returnResponse().getStatusLine().getStatusCode(), HttpStatus.SC_NO_CONTENT); } /** * Test of updateContact method, of class PhonebookService. * @throws java.io.IOException */ @Test public void testUpdateContact() throws IOException { System.out.println("updateContact"); // Generate info to update String updateFirstName = "Updated"; String updateLastName = UUID.randomUUID().toString(); // Check contact not updated yet Response response = Request.Get(testContactLocation).execute(); Content content = response.returnContent(); JAXBMapper<Contact> adapter = new JAXBMapper<>(Contact.class); Contact createdContact = adapter.unmarshal(content.asString(), content.getType().getMimeType()); assertNotEquals(updateFirstName, createdContact.getFirstName()); assertNotEquals(updateLastName, createdContact.getLastName()); // Update the test contact String jsonRequest = String.format("{\"firstName\":\"%s\", \"lastName\":\"%s\"}", updateFirstName, updateLastName); HttpResponse httpResponse = Request.Put(testContactLocation) .bodyString(jsonRequest, ContentType.APPLICATION_JSON) .execute().returnResponse(); assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_NO_CONTENT); // Check contact was updated response = Request.Get(testContactLocation).execute(); content = response.returnContent(); Contact updatedContact = adapter.unmarshal(content.asString(), content.getType().getMimeType()); assertEquals(updateFirstName, updatedContact.getFirstName()); assertEquals(updateLastName, updatedContact.getLastName()); } /** * Test of deleteContact method, of class PhonebookService. * @throws java.io.IOException */ @Test public void testDeleteContact() throws IOException { System.out.println("deleteContact"); // Test contact deleted Response response = Request.Delete(testContactLocation).execute(); assertEquals(response.returnResponse().getStatusLine().getStatusCode(), HttpStatus.SC_NO_CONTENT); deleteContactOnTearDown = false; } /** * Test of deletePhoneNumber method, of class PhonebookService. * @throws java.io.IOException */ @Test public void testDeletePhoneNumber() throws IOException { System.out.println("deletePhoneNumber"); // Add a test number String jsonRequest = String.format("{\"number\":\"%s\", \"type\":\"%s\"}", testPhoneNumber, testPhoneType); Response response = Request.Post(testContactLocation + "/add_number") .bodyString(jsonRequest, ContentType.APPLICATION_JSON) .execute(); assertEquals(response.returnResponse().getStatusLine().getStatusCode(), HttpStatus.SC_CREATED); // Check it was added response = Request.Get(testContactLocation).execute(); Content content = response.returnContent(); JAXBMapper<Contact> adapter = new JAXBMapper<>(Contact.class); Contact contact = adapter.unmarshal(content.asString(), content.getType().getMimeType()); assertNotNull(contact); assertNotNull(contact.getPhoneNumbers()); assertEquals(contact.getPhoneNumbers().size(), 1); PhoneNumber phoneNumber = contact.getPhoneNumbers().iterator().next(); assertNotNull(phoneNumber.getNumber()); assertEquals(phoneNumber.getNumber(), testPhoneNumber); PhoneType phoneType = phoneNumber.getType(); assertNotNull(phoneType); assertEquals(phoneType.getPhoneTypeName(), testPhoneType); // Delete the number response = Request.Delete(testContactLocation + "/" + testPhoneNumber).execute(); assertEquals(response.returnResponse().getStatusLine().getStatusCode(), HttpStatus.SC_NO_CONTENT); // Test it was deleted response = Request.Get(testContactLocation).execute(); content = response.returnContent(); contact = adapter.unmarshal(content.asString(), content.getType().getMimeType()); assertNotNull(contact); assertNull(contact.getPhoneNumbers()); } }
41.086124
124
0.650809
4d8b9b93b7be13bc20b7bffe63528360db3fe7e2
507
package web.spring.boot.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Configuration; public class JsonUtil { private static final ObjectMapper mapper = new ObjectMapper(); public static String writeValueAsString(Object o) { try { return mapper.writeValueAsString(o); } catch (JsonProcessingException e) { return null; } } }
24.142857
66
0.712032
400b527b4a4ffaea4f6e74df73b01ce34a728dcf
2,701
/*--- Copyright 2006-2007 Visual Systems Corporation. http://www.vscorp.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ---*/ package com.googlecode.wicketwebbeans.model; import java.io.Serializable; import java.util.List; import com.googlecode.wicketwebbeans.model.NonJavaEnum; /** * Base implementation of NonJavaEnum to make it look similar to a Java Enum. * * @author Marc Stock * @author Dan Syrstad */ public abstract class BaseNonJavaEnum implements NonJavaEnum, Serializable { protected String name; protected String displayValue; public BaseNonJavaEnum(String name, String displayValue) { this.name = name; this.displayValue = displayValue; } public String name() { return name; } public String getDisplayValue() { return displayValue; } public void setDisplayValue(String displayValue) { this.displayValue = displayValue; } /** * Get the Enum for the given name. * * @param enumValue name to match * * @return a Enum, or null if not found. * @param enums cachedEnums to search through */ public static BaseNonJavaEnum valueOf(String enumValue, List<? extends BaseNonJavaEnum> enums) { if (enumValue == null) { return null; } for (BaseNonJavaEnum nonJavaEnum : enums) { if (nonJavaEnum.name().equals(enumValue)) { return nonJavaEnum; } } return null; } @Override public String toString() { return getDisplayValue(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BaseNonJavaEnum)) { return false; } BaseNonJavaEnum other = (BaseNonJavaEnum)obj; return name().equals(other.name()); } @Override public int hashCode() { int hash = 3; hash = 59 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 59 * hash + (this.displayValue != null ? this.displayValue.hashCode() : 0); return hash; } }
24.779817
98
0.627545
dcd103a7acb71457730f4013f80709fca15302c4
859
package net.bob.yang.dbdoc; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.sql.SQLException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class Application { public static void main(String[] args) throws SQLException, IOException { ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); DbDocumentor documentor = context.getBean(DbDocumentor.class); //OutputStream output = System.out; OutputStream output = new FileOutputStream(new File("c:/data/db.docx")); String databaseName = null; documentor.document(databaseName, output); } }
34.36
91
0.78929
ef1fe8289c28a5c60d16c70e60647b2e666ec0b1
9,702
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.testsuite.oauth; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.NameValuePair; import org.apache.http.client.CookieStore; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.junit.Test; import org.keycloak.admin.client.resource.ClientResource; import org.keycloak.models.Constants; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; import org.keycloak.testsuite.ActionURIUtils; import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude; import org.keycloak.testsuite.oidc.PkceGenerator; import org.keycloak.testsuite.runonserver.ServerVersion; import java.io.IOException; import java.net.URLEncoder; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer; /** * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> */ @AuthServerContainerExclude(AuthServer.REMOTE) public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest { @Test public void checkIframe() throws IOException { CookieStore cookieStore = new BasicCookieStore(); try (CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build()) { String redirectUri = URLEncoder.encode(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/master/console", "UTF-8"); PkceGenerator pkce = new PkceGenerator(); HttpGet get = new HttpGet( suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/auth?response_type=code&client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&redirect_uri=" + redirectUri + "&scope=openid&code_challenge_method=S256&code_challenge=" + pkce.getCodeChallenge()); CloseableHttpResponse response = client.execute(get); String s = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); response.close(); String action = ActionURIUtils.getActionURIFromPageSource(s); HttpPost post = new HttpPost(action); List<NameValuePair> params = new LinkedList<>(); params.add(new BasicNameValuePair("username", "admin")); params.add(new BasicNameValuePair("password", "admin")); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new UrlEncodedFormEntity(params)); response = client.execute(post); assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue()); Header setIdentityCookieHeader = null; Header setSessionCookieHeader = null; for (Header h : response.getAllHeaders()) { if (h.getName().equals("Set-Cookie")) { if (h.getValue().contains("KEYCLOAK_SESSION")) { setSessionCookieHeader = h; } else if (h.getValue().contains("KEYCLOAK_IDENTITY")) { setIdentityCookieHeader = h; } } } assertNotNull(setIdentityCookieHeader); assertTrue(setIdentityCookieHeader.getValue().contains("HttpOnly")); assertNotNull(setSessionCookieHeader); assertFalse(setSessionCookieHeader.getValue().contains("HttpOnly")); response.close(); Cookie sessionCookie = null; for (Cookie cookie : cookieStore.getCookies()) { if (cookie.getName().equals("KEYCLOAK_SESSION")) { sessionCookie = cookie; break; } } assertNotNull(sessionCookie); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html"); response = client.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); s = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); assertTrue(s.contains("function getCookie()")); assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init"); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=invalid" + "&origin=" + suiteContext.getAuthServerInfo().getContextRoot() ); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&origin=http://invalid" ); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&origin=" + suiteContext.getAuthServerInfo().getContextRoot() ); response = client.execute(get); assertEquals(204, response.getStatusLine().getStatusCode()); response.close(); } } @Test public void checkIframeWildcardOrigin() throws IOException { String id = adminClient.realm("master").clients().findByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID).get(0).getId(); ClientResource master = adminClient.realm("master").clients().get(id); ClientRepresentation rep = master.toRepresentation(); List<String> org = rep.getWebOrigins(); try (CloseableHttpClient client = HttpClients.createDefault()) { rep.setWebOrigins(Collections.singletonList("*")); master.update(rep); HttpGet get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&origin=" + "http://anything" ); try (CloseableHttpResponse response = client.execute(get)) { assertEquals(204, response.getStatusLine().getStatusCode()); } } finally { rep.setWebOrigins(org); master.update(rep); } } @Test public void checkIframeCache() throws IOException { String version = testingClient.server().fetch(new ServerVersion()); try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html"); CloseableHttpResponse response = client.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("no-cache, must-revalidate, no-transform, no-store", response.getHeaders("Cache-Control")[0].getValue()); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html?version=" + version); response = client.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); assertTrue(response.getHeaders("Cache-Control")[0].getValue().contains("max-age")); } } @Override public void addTestRealms(List<RealmRepresentation> testRealms) { } }
45.764151
190
0.672439
d9142c0f6b675926db70ace3e20add1caccd3fbc
1,442
package com.prtech.svarog; import java.util.Map; import org.joda.time.DateTime; import com.prtech.svarog_interfaces.ISvCore; import com.prtech.svarog_interfaces.ISvExecutor; import com.prtech.svarog_interfaces.ISvExecutorGroup; public class SvExecutorWrapper implements ISvExecutor { final ISvExecutorGroup executorGroup; final String methodName; SvExecutorWrapper(ISvExecutorGroup executorGroup, String methodName) { if (executorGroup == null || methodName == null || methodName.isEmpty()) throw new NullPointerException("ExecutorGroup and Method Name can not be null"); this.executorGroup = executorGroup; this.methodName = methodName; } @Override public long versionUID() { return executorGroup.versionUID(); } @Override public Class<?> getReturningType() { return executorGroup.getReturningTypes().get(methodName); } @Override public String getCategory() { return executorGroup.getCategory(); } @Override public String getName() { return methodName; } @Override public String getDescription() { return executorGroup.getDescriptions().get(methodName); } @Override public DateTime getStartDate() { return executorGroup.getStartDate(); } @Override public DateTime getEndDate() { return executorGroup.getEndDate(); } @Override public Object execute(Map<String, Object> params, ISvCore svCore) throws SvException { return executorGroup.execute(methodName, params, svCore); } }
23.258065
87
0.768377
d617210d0f68cabca87e3d3159f16a62cd3941dc
419
package com.github.t1.kubee.boundary.config; import javax.inject.Qualifier; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * The <code>cluster-config.yaml</code> file that defines the clusters that <code>kub-ee</code> manages. * * @see com.github.t1.kubee.entity.Cluster for details */ @Qualifier @Retention(RUNTIME) public @interface ClusterConfigPath {}
26.1875
104
0.775656
628382fe2c6752e43a15327d5e0f9c1957b765fa
3,685
package jp.ne.hatena.hackugyo.thoughtscalendar.model.withoutdb; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.util.Xml; abstract public class AbsXmlParser<T> { // We don't use namespaces protected static final String ns = null; public ArrayList<T> parse(InputStream in) throws XmlPullParserException, IOException { try { XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(in, null); parser.nextTag(); return readFeed(parser); } finally { in.close(); } } protected ArrayList<T> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException { ArrayList<T> entries = new ArrayList<T>(); // parser.require(XmlPullParser.START_TAG, ns, "feed"); while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); // Starts by looking for the entry tag skip(parser); // if (name.equals("Event")) { // entries.add(readEventEntry(parser)); // } else { // skip(parser); // } } return entries; } protected T readEventEntry(XmlPullParser parser) throws XmlPullParserException, IOException { parser.require(XmlPullParser.START_TAG, ns, "entry"); String title = null; String summary = null; String link = null; while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); skip(parser); // if (name.equals("Name")) { // title = readTitle(parser); // } else if (name.equals("DateStart")) { // summary = readDateFrom(parser); // } else { // skip(parser); // } } return null; } // For the tags title and summary, extracts their text values. protected String readText(XmlPullParser parser, final String key) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, ns, key); String title = readTextImpl(parser); parser.require(XmlPullParser.END_TAG, ns, key); return title; } // For the tags title and summary, extracts their text values. private String readTextImpl(XmlPullParser parser) throws IOException, XmlPullParserException { String result = ""; if (parser.next() == XmlPullParser.TEXT) { result = parser.getText(); parser.nextTag(); } return result; } protected void skip(XmlPullParser parser) throws XmlPullParserException, IOException { if (parser.getEventType() != XmlPullParser.START_TAG) { throw new IllegalStateException(); } int depth = 1; while (depth != 0) { switch (parser.next()) { case XmlPullParser.END_TAG: depth--; break; case XmlPullParser.START_TAG: depth++; break; } } } }
34.439252
114
0.553596
2d872126148200c124c4fbdb79af68d520073702
781
package cn.edu.sysu.workflow.common.util; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * Jdbc相关工具类 * * @author Skye * Created on 2019/12/27 */ public class JdbcUtil { /** * 带空值处理的PreparedStatementSetter工具 * * @param ps PreparedStatement实例 * @param parameterIndex 参数索引,从1开始 * @param obj 参数的对象 * @param sqlType 参数对应的sql类型,使用java.sql.Types取值 * @throws SQLException 设置出现异常时抛出 */ public static void preparedStatementSetter(PreparedStatement ps, int parameterIndex, Object obj, int sqlType) throws SQLException { if (null == obj) { ps.setNull(parameterIndex, Types.NULL); } else { ps.setObject(parameterIndex, obj, sqlType); } } }
23.666667
135
0.660691
26c59a1ef54700613c3c93bcf57d19ba24bb2a40
8,722
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.security.ingest; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.ingest.IngestDocument; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.security.authc.Authentication; import org.elasticsearch.xpack.core.security.authc.AuthenticationField; import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.security.ingest.SetSecurityUserProcessor.Property; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.equalTo; public class SetSecurityUserProcessorTests extends ESTestCase { public void testProcessor() throws Exception { User user = new User("_username", new String[]{"role1", "role2"}, "firstname lastname", "_email", Collections.singletonMap("key", "value"), true); Authentication.RealmRef realmRef = new Authentication.RealmRef("_name", "_type", "_node_name"); ThreadContext threadContext = new ThreadContext(Settings.EMPTY); threadContext.putTransient(AuthenticationField.AUTHENTICATION_KEY, new Authentication(user, realmRef, null)); IngestDocument ingestDocument = new IngestDocument(new HashMap<>(), new HashMap<>()); SetSecurityUserProcessor processor = new SetSecurityUserProcessor("_tag", threadContext, "_field", EnumSet.allOf(Property.class)); processor.execute(ingestDocument); Map<String, Object> result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result.size(), equalTo(5)); assertThat(result.get("username"), equalTo("_username")); assertThat(((List) result.get("roles")).size(), equalTo(2)); assertThat(((List) result.get("roles")).get(0), equalTo("role1")); assertThat(((List) result.get("roles")).get(1), equalTo("role2")); assertThat(result.get("full_name"), equalTo("firstname lastname")); assertThat(result.get("email"), equalTo("_email")); assertThat(((Map) result.get("metadata")).size(), equalTo(1)); assertThat(((Map) result.get("metadata")).get("key"), equalTo("value")); // test when user holds no data: threadContext = new ThreadContext(Settings.EMPTY); user = new User(null, null, null); threadContext.putTransient(AuthenticationField.AUTHENTICATION_KEY, new Authentication(user, realmRef, null)); ingestDocument = new IngestDocument(new HashMap<>(), new HashMap<>()); processor = new SetSecurityUserProcessor("_tag", threadContext, "_field", EnumSet.allOf(Property.class)); processor.execute(ingestDocument); result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result.size(), equalTo(0)); } public void testNoCurrentUser() throws Exception { ThreadContext threadContext = new ThreadContext(Settings.EMPTY); IngestDocument ingestDocument = new IngestDocument(new HashMap<>(), new HashMap<>()); SetSecurityUserProcessor processor = new SetSecurityUserProcessor("_tag", threadContext, "_field", EnumSet.allOf(Property.class)); IllegalStateException e = expectThrows(IllegalStateException.class, () -> processor.execute(ingestDocument)); assertThat(e.getMessage(), equalTo("No user authenticated, only use this processor via authenticated user")); } public void testUsernameProperties() throws Exception { ThreadContext threadContext = new ThreadContext(Settings.EMPTY); User user = new User("_username", null, null); Authentication.RealmRef realmRef = new Authentication.RealmRef("_name", "_type", "_node_name"); threadContext.putTransient(AuthenticationField.AUTHENTICATION_KEY, new Authentication(user, realmRef, null)); IngestDocument ingestDocument = new IngestDocument(new HashMap<>(), new HashMap<>()); SetSecurityUserProcessor processor = new SetSecurityUserProcessor("_tag", threadContext, "_field", EnumSet.of(Property.USERNAME)); processor.execute(ingestDocument); @SuppressWarnings("unchecked") Map<String, Object> result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result.size(), equalTo(1)); assertThat(result.get("username"), equalTo("_username")); } public void testRolesProperties() throws Exception { ThreadContext threadContext = new ThreadContext(Settings.EMPTY); User user = new User(null, "role1", "role2"); Authentication.RealmRef realmRef = new Authentication.RealmRef("_name", "_type", "_node_name"); threadContext.putTransient(AuthenticationField.AUTHENTICATION_KEY, new Authentication(user, realmRef, null)); IngestDocument ingestDocument = new IngestDocument(new HashMap<>(), new HashMap<>()); SetSecurityUserProcessor processor = new SetSecurityUserProcessor("_tag", threadContext, "_field", EnumSet.of(Property.ROLES)); processor.execute(ingestDocument); @SuppressWarnings("unchecked") Map<String, Object> result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result.size(), equalTo(1)); assertThat(((List) result.get("roles")).size(), equalTo(2)); assertThat(((List) result.get("roles")).get(0), equalTo("role1")); assertThat(((List) result.get("roles")).get(1), equalTo("role2")); } public void testFullNameProperties() throws Exception { ThreadContext threadContext = new ThreadContext(Settings.EMPTY); User user = new User(null, null, "_full_name", null, null, true); Authentication.RealmRef realmRef = new Authentication.RealmRef("_name", "_type", "_node_name"); threadContext.putTransient(AuthenticationField.AUTHENTICATION_KEY, new Authentication(user, realmRef, null)); IngestDocument ingestDocument = new IngestDocument(new HashMap<>(), new HashMap<>()); SetSecurityUserProcessor processor = new SetSecurityUserProcessor("_tag", threadContext, "_field", EnumSet.of(Property.FULL_NAME)); processor.execute(ingestDocument); @SuppressWarnings("unchecked") Map<String, Object> result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result.size(), equalTo(1)); assertThat(result.get("full_name"), equalTo("_full_name")); } public void testEmailProperties() throws Exception { ThreadContext threadContext = new ThreadContext(Settings.EMPTY); User user = new User(null, null, null, "_email", null, true); Authentication.RealmRef realmRef = new Authentication.RealmRef("_name", "_type", "_node_name"); threadContext.putTransient(AuthenticationField.AUTHENTICATION_KEY, new Authentication(user, realmRef, null)); IngestDocument ingestDocument = new IngestDocument(new HashMap<>(), new HashMap<>()); SetSecurityUserProcessor processor = new SetSecurityUserProcessor("_tag", threadContext, "_field", EnumSet.of(Property.EMAIL)); processor.execute(ingestDocument); @SuppressWarnings("unchecked") Map<String, Object> result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result.size(), equalTo(1)); assertThat(result.get("email"), equalTo("_email")); } public void testMetadataProperties() throws Exception { ThreadContext threadContext = new ThreadContext(Settings.EMPTY); User user = new User(null, null, null, null, Collections.singletonMap("key", "value"), true); Authentication.RealmRef realmRef = new Authentication.RealmRef("_name", "_type", "_node_name"); threadContext.putTransient(AuthenticationField.AUTHENTICATION_KEY, new Authentication(user, realmRef, null)); IngestDocument ingestDocument = new IngestDocument(new HashMap<>(), new HashMap<>()); SetSecurityUserProcessor processor = new SetSecurityUserProcessor("_tag", threadContext, "_field", EnumSet.of(Property.METADATA)); processor.execute(ingestDocument); @SuppressWarnings("unchecked") Map<String, Object> result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result.size(), equalTo(1)); assertThat(((Map) result.get("metadata")).size(), equalTo(1)); assertThat(((Map) result.get("metadata")).get("key"), equalTo("value")); } }
57.381579
139
0.712451
ba77096205a431df076e9aad0338f695e4f8b11b
317
package cn.baiyu.scheduledemo.service; /** * @author baiyu * @data 2019-11-12 11:22 */ public class AliService { String URL = "https://openapi.alipay.com/gateway.do"; // AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE); }
22.642857
136
0.722397
fe638f3e278762e45c4ca457040270a8040d18ee
1,096
package com.luminositygames.smoothietycoon.entities; /** * This file is part of Smoothie Tycoon * * Copyright (c) 2013 - 2015 Luminosity Games * * @author Alan Morel * @since July 1, 2014 * @version 1.0 */ public class Recipe { private double price; private int fruit; private int ice; private int yogurt; private int juice; public Recipe(){ setPrice(0.25); setFruit(10); setIce(10); setYogurt(10); setJuice(10); } public double getPrice() { return price; } public void setPrice(double price) { if (price >= 0.05){ this.price = price; } } public int getFruit() { return fruit; } public void setFruit(int fruit) { if (fruit > 0){ this.fruit = fruit; } } public int getIce() { return ice; } public void setIce(int ice) { if (ice > 0){ this.ice = ice; } } public int getYogurt() { return yogurt; } public void setYogurt(int yogurt) { if (yogurt > 0){ this.yogurt = yogurt; } } public int getJuice() { return juice; } public void setJuice(int juice) { if (juice > 0){ this.juice = juice; } } }
13.873418
52
0.625
bc581bacc70ca45b92e7b9950026926d6b851ee5
2,983
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.completion; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.patterns.XmlPatterns; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlElementType; import com.intellij.util.ProcessingContext; import com.intellij.xml.XmlAttributeDescriptor; import org.jetbrains.annotations.NotNull; import static com.intellij.codeInsight.completion.XmlCompletionContributor.hasEnumerationReference; import static com.intellij.patterns.PlatformPatterns.psiElement; import static com.intellij.patterns.XmlPatterns.xmlAttribute; import static com.intellij.patterns.XmlPatterns.xmlTag; import static com.intellij.psi.filters.getters.XmlAttributeValueGetter.getEnumeratedValues; /** * @author yole */ public class XmlNonFirstCompletionContributor extends CompletionContributor { public XmlNonFirstCompletionContributor() { extend(CompletionType.BASIC, psiElement().inside(xmlAttribute()), new XmlAttributeReferenceCompletionProvider()); extend(CompletionType.BASIC, psiElement().inside(xmlTag()), new TagNameReferenceCompletionProvider()); extend(CompletionType.BASIC, psiElement().inside(XmlPatterns.xmlAttributeValue()), new CompletionProvider<>() { @Override protected void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet result) { PsiElement position = parameters.getPosition(); if (position.getNode().getElementType() != XmlElementType.XML_ATTRIBUTE_VALUE_TOKEN) return; XmlAttribute attr = PsiTreeUtil.getParentOfType(position, XmlAttribute.class); if (attr != null && !hasEnumerationReference(parameters, result)) { final XmlAttributeDescriptor descriptor = attr.getDescriptor(); if (descriptor != null) { if (descriptor.isFixed() && descriptor.getDefaultValue() != null) { result.addElement(LookupElementBuilder.create(descriptor.getDefaultValue())); return; } for (String value : getEnumeratedValues(attr)) { result.addElement(LookupElementBuilder.create(value)); } } } } }); } }
44.522388
117
0.73349
7de1825a37e2c17219d3991806af7140313fc9d1
326
package io.github.filipowm.api; import org.springframework.web.bind.annotation.GetMapping; import io.github.filipowm.api.annotations.Api; import io.github.filipowm.api.annotations.ApiVersion; @Api("mytest") @ApiVersion(2) class TestController { @GetMapping("aaa") String doAction() { return "test"; } }
20.375
58
0.730061
b909aca9500eb47d8955b43dd2f22147368ffbbb
401
package com.wjf.rxweibo.database; /** * description * * @author weijianfeng * @date 16/8/22 */ public class DBContract { public interface User { } public interface Status { public static final String TABLE_NAME = "status"; public static final String COLUMN_NAME_ID = "status_id"; public static final String COLUMN_NAME_STATUS_TEXT = "status_text"; } }
19.095238
75
0.668329
1ee76477c97d3b01b81bf8e1372594cb4ef8154d
733
//给定一个二叉树,检查它是否是镜像对称的。 // // // // 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 // // 1 // / \ // 2 2 // / \ / \ //3 4 4 3 // // // // // 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: // // 1 // / \ // 2 2 // \ \ // 3 3 // // // // // 进阶: // // 你可以运用递归和迭代两种方法解决这个问题吗? // Related Topics 树 深度优先搜索 广度优先搜索 //leetcode submit region begin(Prohibit modification and deletion) import javax.swing.tree.TreeNode; /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { return false; } } //leetcode submit region end(Prohibit modification and deletion)
13.830189
66
0.564802
175383c51abad2953f81a23d0e029dee54aa1502
4,452
/** * Copyright (C) 2014 Antonin Stefanutti (antonin.stefanutti@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.astefanutti.cdeye.web; import io.astefanutti.cdeye.core.CdEye; import io.astefanutti.cdeye.core.model.CdEyeBean; import io.astefanutti.cdeye.core.model.CdEyeBeans; import javax.annotation.ManagedBean; import javax.enterprise.event.Event; import javax.enterprise.inject.Instance; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.InjectionPoint; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; @ManagedBean @Path("beans") public class BeansResource { @Inject private CdEye cdEye; // TODO: find a way to hide CDEye Web internal beans @GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public CdEyeBeans getBeans() { CdEyeBeans beans = new CdEyeBeans(); for (Bean<?> bean : cdEye.getBeans()) { CdEyeBean cdEyeBean = cdEyeBean(bean); for (InjectionPoint ip : bean.getInjectionPoints()) { // Skip InjectionPoint and BeanManager injection points if (InjectionPoint.class.equals(getRawType(ip.getType())) || BeanManager.class.equals(getRawType(ip.getType()))) continue; if (Instance.class.equals(getRawType(ip.getType())) || Event.class.equals(getRawType(ip.getType()))) // TODO: support programmatic lookup and events continue; Bean<?> resolved = cdEye.resolveBean(ip); if (!cdEye.isExcluded(resolved)) cdEyeBean.withInjectionPoints() .withNewInjectionPoint() .withBean(cdEyeBean(resolved)); } if (!cdEye.isProducer(bean)) for (Bean<?> producer : cdEye.getProducers(bean.getBeanClass())) cdEyeBean.withProducers() .withNewProducer() .withName(cdEye.getProducerName(producer)) .withBean(cdEyeBean(producer)); beans.withBean(cdEyeBean); } return beans; } private CdEyeBean cdEyeBean(Bean<?> bean) { return new CdEyeBean() .withId(cdEye.getBeanId(bean)) .withClassName(bean.getBeanClass().getName()) .withClassSimpleName(bean.getBeanClass().getSimpleName()); } private Class<?> getRawType(Type type) { if (type instanceof Class<?>) { return Class.class.cast(type); } else if (type instanceof ParameterizedType) { return getRawType(ParameterizedType.class.cast(type).getRawType()); } else if (type instanceof TypeVariable<?>) { return getBound(TypeVariable.class.cast(type).getBounds()); } else if (type instanceof WildcardType) { return getBound(WildcardType.class.cast(type).getUpperBounds()); } else if (type instanceof GenericArrayType) { Class<?> rawType = getRawType(GenericArrayType.class.cast(type).getGenericComponentType()); if (rawType != null) return Array.newInstance(rawType, 0).getClass(); } return null; } private Class<?> getBound(Type[] bounds) { if (bounds.length == 0) return Object.class; else return getRawType(bounds[0]); } }
38.713043
129
0.628032
05afebf4165a1ff2719f0f69012276dd0be90300
20,155
/* * Copyright © 2017, Salesforce.com, 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 the <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.aptspring.processor; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourcesSubjectFactory.javaSources; import java.io.IOException; import java.util.Arrays; import javax.tools.JavaFileObject; import javax.tools.StandardLocation; import org.junit.Test; import com.google.testing.compile.JavaFileObjects; import com.salesforce.apt.graph.model.storage.classpath.FileStore; public class ParserTests { @Test public void testNonTopLevelClassMayNotBeVerified() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.ImportantClass", "package test;", "", "import org.springframework.context.annotation.Configuration;", "import java.util.Date;", "", "public class ImportantClass {", "", " @com.salesforce.aptspring.Verified", " @Configuration", " public static class TestClass1 {", "", " private static final String someVariable = \"I AM GOOD!\";", " }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("The class must be a top level class, not an internal class") .in(definitionClass) .onLine(10); } @Test public void testShowsTestClassMayContainVerified() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Configuration;", "import java.util.Date;", "", "public class TestClass {", "", " @com.salesforce.aptspring.Verified", " public static class TestClass1 {", "", " private static final String someVariable = \"I AM GOOD!\";", " }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .compilesWithoutError() .and() .generatesFileNamed(StandardLocation.SOURCE_OUTPUT, "test", "TestClass$TestClass1_" + FileStore.STANDARD.getPath() + ".java"); } @Test public void testLiteBeanMethodMustHaveAtLeastOneName() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " @Bean", " private String getValue() { return \"I AM NOT GOOD!\"; }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("All @Bean annotations must define at least one name for a bean") .in(definitionClass) .onLine(10); } @Test public void testLiteBeanMethodMayHaveManyNames() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " @Bean(name={\"name1\",\"name2\"})", " public String getValue() { return \"I AM NOT GOOD!\"; }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .compilesWithoutError() .and() .generatesFileNamed(StandardLocation.SOURCE_OUTPUT, "test", "TestClass_" + FileStore.STANDARD.getPath() + ".java"); } @Test public void testMustNotHaveConfiguration() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "@Configuration", "public class TestClass {", "", " private static final String someVariable = \"I AM GOOD!\";", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("@Verified annotation must only be used on @Bean LITE factory classes or @Component classes") .in(definitionClass) .onLine(7); } @Test public void testNonComponentsMustHaveBeanOrImport() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " private String getValue() { return \"I AM NOT GOOD!\"; }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("All methods on @Configuration must have @Bean annotation") .in(definitionClass) .onLine(8); } @Test public void testConfigurationBeanMethodMustBePublic() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " @Bean(name = {\"stuff\",\"stuff2\"})", " private String getValue() { return \"I AM NOT GOOD!\"; }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("@Bean methods must be marked public") .in(definitionClass) .onLine(10); } @Test public void testConfigurationBeanMustReturnAnObject() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " @Bean(name=\"stuff\")", " public void getValue() { return \"I AM NOT GOOD!\"; }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("@Bean methods must return an Object") .in(definitionClass) .onLine(10); } @Test public void testConfigurationBeanMustReturnAnObjectNotInt() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " @Bean(name=\"stuff\")", " public int getValue() { return 1; }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("@Bean methods must return an Object") .in(definitionClass) .onLine(10); } @Test public void testConfigurationBeanMayNotBeStatic() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " @Bean(name=\"stuff\")", " public static String getValue() { return \"\"; }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("Illegal modifiers found on spring @Bean method: STATIC") .in(definitionClass) .onLine(10); } @Test public void testConfigurationMayNotHaveConstructorsOrInitializationBlocks() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " public TestClass(String s) {", " String s2 = s;", " }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("@Configuration should not have any non-default constructors.") .in(definitionClass) .onLine(9); } @Test public void testConfigurationMayNotHaveNonPublicConstructors() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " private TestClass() {", " }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("@Configuration should not have any non-public constructors.") .in(definitionClass) .onLine(9); } @Test public void testConfigurationErrorIfComponentScan() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "import org.springframework.context.annotation.ComponentScan;", "", "@com.salesforce.aptspring.Verified", "@ComponentScan(\"stuff1\")", "public class TestClass {", "", " @Bean(name=\"stuff\")", " public String getValue() { return \"\"; }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("You may not use @ComponentScan(s) on @Verified classes") .in(definitionClass) .onLine(9); } @Test public void testConfigurationErrorIfComponentScans() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "import org.springframework.context.annotation.ComponentScan;", "", "@com.salesforce.aptspring.Verified", "@ComponentScan(\"stuff1\")", "@ComponentScan(\"stuff2\")", "public class TestClass {", "", " @Bean(name=\"stuff\")", " public String getValue() { return \"\"; }", "", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("You may not use @ComponentScan(s) on @Verified classes") .in(definitionClass) .onLine(10); } @Test public void testFailIfUnmarkedParameter() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "import org.springframework.context.annotation.ComponentScan;", "import org.springframework.beans.factory.annotation.Value;", "import org.springframework.beans.factory.annotation.Qualifier;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " @Bean(value=\"stuff1\")", " public String getValue1(@Value(\"x\") String s) { return \"\"; }", " ", " @Bean(value=\"stuff2\")", " public String getValue2(@Qualifier(\"bob\") String b) { return \"\"; }", " ", " @Bean(name=\"stuff3\")", " public String getValue3(String c) { return \"\"; }", " ", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("All parameters must have an @Qualifier or a @Value annotation") .in(definitionClass) .onLine(19); } @Test public void testFailIfUnexpectedElement() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };", " ", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("Only @Bean methods, private static final literals," + " and default constructors are allowed on @Configuration classes") .in(definitionClass) .onLine(9); } @Test public void testFailUsingValueAndNotRootConfiguration() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "import org.springframework.context.annotation.ComponentScan;", "import org.springframework.beans.factory.annotation.Value;", "import org.springframework.beans.factory.annotation.Qualifier;", "", "@com.salesforce.aptspring.Verified", "public class TestClass {", "", " @Bean(value=\"stuff1\")", " public String getValue1(@Value(\"x\") String s) { return \"\"; }", " ", " @Bean(value=\"stuff2\")", " public String getValue2(@Qualifier(\"stuff1\") String b, @Value(\"x\") String s) { return \"\"; }", " ", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .failsToCompile() .withErrorContaining("Only @Verified(root=true) nodes may use @Value annotations to create beans," + " decouples spring graph from environment") .in(definitionClass) .onLine(13) .and() .withErrorContaining("No method may define both @Qualifier or a @Value annotations," + " keep property values in there own beans") .in(definitionClass) .onLine(16); } @Test public void testRootConfigurationCompilesWithValues() throws IOException { JavaFileObject definitionClass = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import org.springframework.context.annotation.Bean;", "import org.springframework.context.annotation.Configuration;", "import org.springframework.context.annotation.ComponentScan;", "import org.springframework.beans.factory.annotation.Value;", "import org.springframework.beans.factory.annotation.Qualifier;", "", "@com.salesforce.aptspring.Verified(root=true)", "public class TestClass {", " ", " @Bean(value=\"stuff1\")", " public String getValue1(@Value(\"x\") String s) { return \"\"; }", " ", "}"); assertAbout(javaSources()) .that(Arrays.asList(definitionClass)) .processedWith(new VerifiedSpringConfiguration()) .compilesWithoutError() .and() .generatesFileNamed(StandardLocation.SOURCE_OUTPUT, "test", "TestClass_" + FileStore.STANDARD.getPath() + ".java"); } }
36.846435
127
0.616522
8808dc6b1f860e76b317e3bd9ab4635fc9108dc6
2,872
package fi.digi.savonia.movesense.Tools; /** * Helppokäyttöinen wrapper vektori3 laskutoimituksiin */ public class Vector3 { public float x; public float y; public float z; public static Vector3 New(float vector_x, float vector_y, float vector_z) { Vector3 ret = new Vector3(); ret.x=vector_x; ret.y=vector_y; ret.z=vector_z; return ret; } public Vector3(float x, float y, float z) { this.set(x, y, z); } public Vector3(Vector3 v) { this.set(v); } public Vector3() { this.set(0, 0, 0); } public Vector3 set(float x, float y, float z) { this.x = x; this.y = y; this.z = z; return this; } public Vector3 set(Vector3 v) { x = v.x; y = v.y; z = v.z; return this; } public Vector3 normalize() { float norm = norm(); x = x / norm; y = y / norm; z = z / norm; return this; } public Vector3 add(Vector3 v) { Vector3 v0 = new Vector3(); Vector3 v1 = this; Vector3 v2 = v; v0.x = v1.x + v2.x; v0.y = v1.y + v2.y; v0.z = v1.z + v2.z; return v0; } public Vector3 minus(Vector3 v) { Vector3 v0 = new Vector3(); Vector3 v1 = this; Vector3 v2 = v; v0.x = v1.x - v2.x; v0.y = v1.y - v2.y; v0.z = v1.z - v2.z; return v0; } public Vector3 mul1d(float a) { Vector3 v = this; v.x *= a; v.y *= a; v.z *= a; return v; } public Vector3 cross(Vector3 v) { Vector3 v1 = this; Vector3 v2 = v; v.x = (v1.y * v2.z) - (v1.z * v2.y); v.y = (v1.z * v2.x) - (v1.x * v2.z); v.z = (v1.x * v2.y) - (v1.y * v2.x); return v; } public float dot(Vector3 v) { Vector3 v1 = this; Vector3 v2 = v; return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z); } public Quaternion calculate_vector_rotation_quaternion(Vector3 v) { Vector3 v1 = this; Vector3 v2 = v; v = v1.cross(v2); Quaternion q = new Quaternion(v.x, v.y, v.z, 0); q.w = v1.norm() * v2.norm() + v1.dot(v2); q.normalize(); return q; } public Vector3 proj(Vector3 direction) { float dot_product = dot(direction); float norm = direction.norm(); Vector3 v = new Vector3(direction.mul1d(dot_product/norm)); return v; } public float norm() { return (float) Math.sqrt(x * x + y * y + z * z); } public float norm2d() { return (float) Math.sqrt(x*x+y*y); } public String toString() { return "vx," + String.valueOf(x) + ",\nvy," + String.valueOf(y) + ",\nvz," + String.valueOf(z); } }
22.4375
103
0.487813
52997c3c3d207f751f811b96020e79ec05b8e690
1,957
/* * Copyright 2017 Josue Gontijo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.joshworks.snappy.it; import io.joshworks.restclient.http.Unirest; import io.joshworks.snappy.http.Response; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Test; import static io.joshworks.snappy.SnappyServer.basePath; import static io.joshworks.snappy.SnappyServer.get; import static io.joshworks.snappy.SnappyServer.group; import static io.joshworks.snappy.SnappyServer.start; import static io.joshworks.snappy.SnappyServer.stop; /** * Created by josh on 3/11/17. */ public class BasePathTest { @AfterClass public static void shutdown() { stop(); Unirest.close(); } @Test public void getRequest() { try { basePath("/v1"); get("/test", req -> Response.ok()); start(); Assert.assertEquals(200, Unirest.get("http://localhost:9000/v1/test").asString().getStatus()); } finally { stop(); Unirest.close(); } } @Test public void withGroup() { try { basePath("/v1"); group("/a", () -> get("/test", req -> Response.ok())); start(); Assert.assertEquals(200, Unirest.get("http://localhost:9000/v1/a/test").asString().getStatus()); } finally { stop(); Unirest.close(); } } }
26.093333
108
0.635156
7d6932dd368e54b5a294e06b6f35a9865a31c857
25,316
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.dynamicvdb; import java.sql.Connection; import java.sql.DatabaseMetaData; import org.junit.Ignore; import org.junit.Test; import org.teiid.core.util.UnitTestUtil; import org.teiid.jdbc.AbstractMMQueryTestCase; /** * Test the DatabaseMetadata results using the Parts VDB. */ @Ignore public class TestVDBLessExecution extends AbstractMMQueryTestCase { private static final String DQP_PROP_FILE = UnitTestUtil.getTestDataPath() + "/vdbless/dqp.properties;user=test"; //$NON-NLS-1$ private static final String VDB = "VDBLess"; //$NON-NLS-1$ @Test public void testExecution() throws Exception { getConnection(VDB, DQP_PROP_FILE); executeAndAssertResults("select * from Example", new String[] { //$NON-NLS-1$ "TRADEID[string] NOTIONAL[integer]", //$NON-NLS-1$ "x 1", //$NON-NLS-1$ "y 2" //$NON-NLS-1$ }); closeConnection(); } @Test public void testIntegrationExecution() throws Exception { getConnection(VDB, DQP_PROP_FILE); executeAndAssertResults("select * from Example, Smalla where notional = intkey", new String[] { //$NON-NLS-1$ "TRADEID[string] NOTIONAL[integer] INTKEY[integer] STRINGKEY[string] INTNUM[integer] STRINGNUM[string] FLOATNUM[float] LONGNUM[long] DOUBLENUM[double] BYTENUM[short] DATEVALUE[date] TIMEVALUE[time] TIMESTAMPVALUE[timestamp] BOOLEANVALUE[short] CHARVALUE[string] SHORTVALUE[short] BIGINTEGERVALUE[long] BIGDECIMALVALUE[bigdecimal] OBJECTVALUE[string]", //$NON-NLS-1$ "x 1 1 1 -23 null -23.0 -23 -23.0 -127 2000-01-02 01:00:00 2000-01-01 00:00:01.0 1 0 -32767 -23 -23 -23", //$NON-NLS-1$ "y 2 2 2 -22 -22 null -22 -22.0 -126 2000-01-03 02:00:00 2000-01-01 00:00:02.0 0 1 -32766 -22 -22 -22", //$NON-NLS-1$ }); closeConnection(); } /** * We have no results to assert here since derby does not provide procedure resultset columns in their metadata. */ @Test public void testProcedureExecution() throws Exception { getConnection(VDB, DQP_PROP_FILE); execute("exec Derby.SQLUDTS(null, null, null, null, null)"); //$NON-NLS-1$ closeConnection(); } @Test public void testDatabaseMetaDataTables() throws Exception { Connection conn = getConnection(VDB, DQP_PROP_FILE); DatabaseMetaData metadata = conn.getMetaData(); this.internalResultSet = metadata.getTables(null, "SummitData", null, new String[] {"TABLE"}); //$NON-NLS-1$ //$NON-NLS-2$ assertResults(new String[] { "TABLE_CAT[string] TABLE_SCHEM[string] TABLE_NAME[string] TABLE_TYPE[string] REMARKS[string] TYPE_CAT[string] TYPE_SCHEM[string] TYPE_NAME[string] SELF_REFERENCING_COL_NAME[string] REF_GENERATION[string] ISPHYSICAL[boolean]", //$NON-NLS-1$ "VDBLess SummitData EXAMPLE TABLE null null null null null null true" //$NON-NLS-1$ }); closeConnection(); } /** * Ensures that system tables are still visible */ @Test public void testDatabaseMetaDataTables1() throws Exception { Connection conn = getConnection(VDB, DQP_PROP_FILE); DatabaseMetaData metadata = conn.getMetaData(); this.internalResultSet = metadata.getTables(null, null, "%Properties", null); //$NON-NLS-1$ assertResults(new String[] { "TABLE_CAT[string] TABLE_SCHEM[string] TABLE_NAME[string] TABLE_TYPE[string] REMARKS[string] TYPE_CAT[string] TYPE_SCHEM[string] TYPE_NAME[string] SELF_REFERENCING_COL_NAME[string] REF_GENERATION[string] ISPHYSICAL[boolean]", //$NON-NLS-1$ "VDBLess System Properties SYSTEM TABLE null null null null null null true" //$NON-NLS-1$ }); closeConnection(); } @Test public void testDatabaseMetaDataColumns() throws Exception { Connection conn = getConnection(VDB, DQP_PROP_FILE); DatabaseMetaData metadata = conn.getMetaData(); this.internalResultSet = metadata.getColumns(null, "SummitData", null, "%"); //$NON-NLS-1$ //$NON-NLS-2$ assertResults(new String[] { "TABLE_CAT[string] TABLE_SCHEM[string] TABLE_NAME[string] COLUMN_NAME[string] DATA_TYPE[short] TYPE_NAME[string] COLUMN_SIZE[integer] BUFFER_LENGTH[string] DECIMAL_DIGITS[integer] NUM_PREC_RADIX[integer] NULLABLE[integer] REMARKS[string] COLUMN_DEF[string] SQL_DATA_TYPE[string] SQL_DATETIME_SUB[string] CHAR_OCTET_LENGTH[integer] ORDINAL_POSITION[integer] IS_NULLABLE[string] SCOPE_CATALOG[string] SCOPE_SCHEMA[string] SCOPE_TABLE[string] SOURCE_DATA_TYPE[string] IS_AUTOINCREMENT[string]", //$NON-NLS-1$ "VDBLess SummitData EXAMPLE TRADEID 12 string 4000 null 0 0 2 null null null null 0 1 null null null null NO", //$NON-NLS-1$ "VDBLess SummitData EXAMPLE NOTIONAL 4 integer 10 null 0 0 2 null null null null 0 2 null null null null NO", //$NON-NLS-1$ }); closeConnection(); } @Test public void testDatabaseMetaDataColumns1() throws Exception { Connection conn = getConnection(VDB, DQP_PROP_FILE); DatabaseMetaData metadata = conn.getMetaData(); this.internalResultSet = metadata.getColumns(null, null, "%smalla", "%"); //$NON-NLS-1$ //$NON-NLS-2$ assertResults(new String[] { "TABLE_CAT[string] TABLE_SCHEM[string] TABLE_NAME[string] COLUMN_NAME[string] DATA_TYPE[short] TYPE_NAME[string] COLUMN_SIZE[integer] BUFFER_LENGTH[string] DECIMAL_DIGITS[integer] NUM_PREC_RADIX[integer] NULLABLE[integer] REMARKS[string] COLUMN_DEF[string] SQL_DATA_TYPE[string] SQL_DATETIME_SUB[string] CHAR_OCTET_LENGTH[integer] ORDINAL_POSITION[integer] IS_NULLABLE[string] SCOPE_CATALOG[string] SCOPE_SCHEMA[string] SCOPE_TABLE[string] SOURCE_DATA_TYPE[string] IS_AUTOINCREMENT[string]", //$NON-NLS-1$ "VDBLess Derby SMALLA INTKEY 4 integer 10 null 0 10 0 null null null 0 1 YES null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA STRINGKEY 12 string 4000 null 0 0 0 null null null 20 2 YES null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA INTNUM 4 integer 10 null 0 10 1 null null null 0 3 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA STRINGNUM 12 string 4000 null 0 0 1 null null null 20 4 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA FLOATNUM 7 float 20 null 0 2 1 null null null 0 5 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA LONGNUM -5 long 19 null 0 10 1 null null null 0 6 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA DOUBLENUM 8 double 20 null 0 2 1 null null null 0 7 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA BYTENUM 5 short 5 null 0 10 1 null null null 0 8 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA DATEVALUE 91 date 10 null 0 10 1 null null null 0 9 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA TIMEVALUE 92 time 8 null 0 10 1 null null null 0 10 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA TIMESTAMPVALUE 93 timestamp 29 null 0 10 1 null null null 0 11 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA BOOLEANVALUE 5 short 5 null 0 10 1 null null null 0 12 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA CHARVALUE 12 string 4000 null 0 0 1 null null null 2 13 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA SHORTVALUE 5 short 5 null 0 10 1 null null null 0 14 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA BIGINTEGERVALUE -5 long 19 null 0 10 1 null null null 0 15 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA BIGDECIMALVALUE 2 bigdecimal 20 null 0 10 1 null null null 0 16 NO null null null null NO", //$NON-NLS-1$ "VDBLess Derby SMALLA OBJECTVALUE 12 string 4000 null 0 0 1 null null null 4096 17 NO null null null null NO", //$NON-NLS-1$ }); closeConnection(); } @Test public void testDatabaseMetaDataPrimaryKeys() throws Exception { Connection conn = getConnection(VDB, DQP_PROP_FILE); DatabaseMetaData metadata = conn.getMetaData(); //note - the use of null for the table name is a little against spec this.internalResultSet = metadata.getPrimaryKeys(null, null, null); assertResults(new String[] { "TABLE_CAT[string] TABLE_SCHEM[string] TABLE_NAME[string] COLUMN_NAME[string] KEY_SEQ[short] PK_NAME[string]", //$NON-NLS-1$ "VDBLess Derby FLIGHTS FLIGHT_ID 1 SQL090709161814150", //$NON-NLS-1$ "VDBLess Derby FLTAVAIL FLIGHT_ID 1 FLTAVAIL_PK", //$NON-NLS-1$ "VDBLess Derby SMALLA INTKEY 1 SQL060110103634070", //$NON-NLS-1$ "VDBLess Derby SMALLB INTKEY 1 SQL060110103635170", //$NON-NLS-1$ "VDBLess Derby FLIGHTS SEGMENT_NUMBER 2 SQL090709161814150", //$NON-NLS-1$ "VDBLess Derby FLTAVAIL SEGMENT_NUMBER 2 FLTAVAIL_PK", //$NON-NLS-1$ }); closeConnection(); } @Test public void testDatabaseMetaDataExportedKeys() throws Exception { Connection conn = getConnection(VDB, DQP_PROP_FILE); DatabaseMetaData metadata = conn.getMetaData(); this.internalResultSet = metadata.getExportedKeys("VDBLess", "Derby", "FLIGHTS"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ assertResults(new String[] { "PKTABLE_CAT[string] PKTABLE_SCHEM[string] PKTABLE_NAME[string] PKCOLUMN_NAME[string] FKTABLE_CAT[string] FKTABLE_SCHEM[string] FKTABLE_NAME[string] FKCOLUMN_NAME[string] KEY_SEQ[short] UPDATE_RULE[integer] DELETE_RULE[integer] FK_NAME[string] PK_NAME[string] DEFERRABILITY[integer]", //$NON-NLS-1$ "VDBLess Derby FLIGHTS FLIGHT_ID VDBLess Derby FLTAVAIL FLIGHT_ID 1 3 3 FLTS_FK SQL090709161814150 5", //$NON-NLS-1$ "VDBLess Derby FLIGHTS SEGMENT_NUMBER VDBLess Derby FLTAVAIL SEGMENT_NUMBER 2 3 3 FLTS_FK SQL090709161814150 5" //$NON-NLS-1$ }); closeConnection(); } @Test public void testDatabaseMetaDataImportedKeys() throws Exception { Connection conn = getConnection(VDB, DQP_PROP_FILE); DatabaseMetaData metadata = conn.getMetaData(); this.internalResultSet = metadata.getImportedKeys("VDBLess", "Derby", "FLTAVAIL"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ assertResults(new String[] { "PKTABLE_CAT[string] PKTABLE_SCHEM[string] PKTABLE_NAME[string] PKCOLUMN_NAME[string] FKTABLE_CAT[string] FKTABLE_SCHEM[string] FKTABLE_NAME[string] FKCOLUMN_NAME[string] KEY_SEQ[short] UPDATE_RULE[integer] DELETE_RULE[integer] FK_NAME[string] PK_NAME[string] DEFERRABILITY[integer]", //$NON-NLS-1$ "VDBLess Derby FLIGHTS FLIGHT_ID VDBLess Derby FLTAVAIL FLIGHT_ID 1 3 3 FLTS_FK SQL090709161814150 5", //$NON-NLS-1$ "VDBLess Derby FLIGHTS SEGMENT_NUMBER VDBLess Derby FLTAVAIL SEGMENT_NUMBER 2 3 3 FLTS_FK SQL090709161814150 5" //$NON-NLS-1$ }); this.internalResultSet = metadata.getImportedKeys(null, "Derby", "SMALLBRIDGE"); //$NON-NLS-1$ //$NON-NLS-2$ assertResults(new String[] { "PKTABLE_CAT[string] PKTABLE_SCHEM[string] PKTABLE_NAME[string] PKCOLUMN_NAME[string] FKTABLE_CAT[string] FKTABLE_SCHEM[string] FKTABLE_NAME[string] FKCOLUMN_NAME[string] KEY_SEQ[short] UPDATE_RULE[integer] DELETE_RULE[integer] FK_NAME[string] PK_NAME[string] DEFERRABILITY[integer]", //$NON-NLS-1$ "VDBLess Derby SMALLA INTKEY VDBLess Derby SMALLBRIDGE AKEY 1 3 3 SMLA_FK SQL060110103634070 5", //$NON-NLS-1$ "VDBLess Derby SMALLB INTKEY VDBLess Derby SMALLBRIDGE BKEY 1 3 3 SMLB_FK SQL060110103635170 5", //$NON-NLS-1$ }); closeConnection(); } @Test public void testDatabaseMetaDataIndexInfo() throws Exception { Connection conn = getConnection(VDB, DQP_PROP_FILE); DatabaseMetaData metadata = conn.getMetaData(); //note - the use of null for the table name is a little against spec this.internalResultSet = metadata.getIndexInfo(null, null, null, false, true); assertResults(new String[] { "TABLE_CAT[string] TABLE_SCHEM[string] TABLE_NAME[string] NON_UNIQUE[boolean] INDEX_QUALIFIER[string] INDEX_NAME[string] TYPE[integer] ORDINAL_POSITION[short] COLUMN_NAME[string] ASC_OR_DESC[string] CARDINALITY[integer] PAGES[integer] FILTER_CONDITION[string]", //$NON-NLS-1$ "VDBLess Derby FLIGHTS false null ORIGINDEX 0 1 ORIG_AIRPORT null 0 1 null", //$NON-NLS-1$ "VDBLess Derby FLTAVAIL false null SQL090709161840271 0 1 FLIGHT_ID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby FLTAVAIL false null SQL090709161840271 0 2 SEGMENT_NUMBER null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SMALLBRIDGE false null SQL090710102514590 0 1 AKEY null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SMALLBRIDGE false null SQL090710102514591 0 1 BKEY null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCOLUMNS false null SYSCOLUMNS_INDEX2 0 1 COLUMNDEFAULTID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCONGLOMERATES false null SYSCONGLOMERATES_INDEX1 0 1 CONGLOMERATEID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCONGLOMERATES false null SYSCONGLOMERATES_INDEX3 0 1 TABLEID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCONSTRAINTS false null SYSCONSTRAINTS_INDEX3 0 1 TABLEID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSDEPENDS false null SYSDEPENDS_INDEX1 0 1 DEPENDENTID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSDEPENDS false null SYSDEPENDS_INDEX2 0 1 PROVIDERID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSFOREIGNKEYS false null SYSFOREIGNKEYS_INDEX2 0 1 KEYCONSTRAINTID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSSTATISTICS false null SYSSTATISTICS_INDEX1 0 1 TABLEID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSSTATISTICS false null SYSSTATISTICS_INDEX1 0 2 REFERENCEID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSTRIGGERS false null SYSTRIGGERS_INDEX3 0 1 TABLEID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSTRIGGERS false null SYSTRIGGERS_INDEX3 0 2 CREATIONTIMESTAMP null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SMALLA true null SQL060110103634070 0 1 INTKEY null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SMALLB true null SQL060110103635170 0 1 INTKEY null 0 1 null", //$NON-NLS-1$ "VDBLess Derby FLIGHTS true null SQL090709161814150 0 1 FLIGHT_ID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby FLIGHTS true null SQL090709161814150 0 2 SEGMENT_NUMBER null 0 1 null", //$NON-NLS-1$ "VDBLess Derby FLTAVAIL true null SQL090709161840270 0 1 FLIGHT_ID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby FLTAVAIL true null SQL090709161840270 0 2 SEGMENT_NUMBER null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSALIASES true null SYSALIASES_INDEX1 0 1 SCHEMAID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSALIASES true null SYSALIASES_INDEX1 0 2 ALIAS null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSALIASES true null SYSALIASES_INDEX1 0 3 NAMESPACE null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSALIASES true null SYSALIASES_INDEX2 0 1 ALIASID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSALIASES true null SYSALIASES_INDEX3 0 1 SCHEMAID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSALIASES true null SYSALIASES_INDEX3 0 2 SPECIFICNAME null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCHECKS true null SYSCHECKS_INDEX1 0 1 CONSTRAINTID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCOLUMNS true null SYSCOLUMNS_INDEX1 0 1 REFERENCEID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCOLUMNS true null SYSCOLUMNS_INDEX1 0 2 COLUMNNAME null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCONGLOMERATES true null SYSCONGLOMERATES_INDEX2 0 1 CONGLOMERATENAME null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCONGLOMERATES true null SYSCONGLOMERATES_INDEX2 0 2 SCHEMAID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCONSTRAINTS true null SYSCONSTRAINTS_INDEX1 0 1 CONSTRAINTID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCONSTRAINTS true null SYSCONSTRAINTS_INDEX2 0 1 CONSTRAINTNAME null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSCONSTRAINTS true null SYSCONSTRAINTS_INDEX2 0 2 SCHEMAID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSFILES true null SYSFILES_INDEX1 0 1 FILENAME null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSFILES true null SYSFILES_INDEX1 0 2 SCHEMAID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSFILES true null SYSFILES_INDEX2 0 1 FILEID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSFOREIGNKEYS true null SYSFOREIGNKEYS_INDEX1 0 1 CONSTRAINTID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSKEYS true null SYSKEYS_INDEX1 0 1 CONSTRAINTID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSSCHEMAS true null SYSSCHEMAS_INDEX1 0 1 SCHEMANAME null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSSCHEMAS true null SYSSCHEMAS_INDEX2 0 1 SCHEMAID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSSTATEMENTS true null SYSSTATEMENTS_INDEX1 0 1 STMTID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSSTATEMENTS true null SYSSTATEMENTS_INDEX2 0 1 STMTNAME null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSSTATEMENTS true null SYSSTATEMENTS_INDEX2 0 2 SCHEMAID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSTABLES true null SYSTABLES_INDEX1 0 1 TABLENAME null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSTABLES true null SYSTABLES_INDEX1 0 2 SCHEMAID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSTABLES true null SYSTABLES_INDEX2 0 1 TABLEID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSTRIGGERS true null SYSTRIGGERS_INDEX1 0 1 TRIGGERID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSTRIGGERS true null SYSTRIGGERS_INDEX2 0 1 TRIGGERNAME null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSTRIGGERS true null SYSTRIGGERS_INDEX2 0 2 SCHEMAID null 0 1 null", //$NON-NLS-1$ "VDBLess Derby SYSVIEWS true null SYSVIEWS_INDEX1 0 1 TABLEID null 0 1 null", //$NON-NLS-1$ }); closeConnection(); } @Test public void testDatabaseMetaDataProcedures() throws Exception { Connection conn = getConnection(VDB, DQP_PROP_FILE); DatabaseMetaData metadata = conn.getMetaData(); this.internalResultSet = metadata.getProcedures(null, "Derby", "%JAR"); //$NON-NLS-1$ //$NON-NLS-2$ assertResults(new String[] { "PROCEDURE_CAT[string] PROCEDURE_SCHEM[string] PROCEDURE_NAME[string] RESERVED_1[string] RESERVED_2[string] RESERVED_3[string] REMARKS[string] PROCEDURE_TYPE[short] SPECIFIC_NAME[string]", //$NON-NLS-1$ "VDBLess Derby INSTALL_JAR null null null null 1 INSTALL_JAR", //$NON-NLS-1$ "VDBLess Derby REMOVE_JAR null null null null 1 REMOVE_JAR", //$NON-NLS-1$ "VDBLess Derby REPLACE_JAR null null null null 1 REPLACE_JAR", //$NON-NLS-1$ }); closeConnection(); } @Test public void testDatabaseMetaDataProcedureColumns() throws Exception { Connection conn = getConnection(VDB, DQP_PROP_FILE); DatabaseMetaData metadata = conn.getMetaData(); this.internalResultSet = metadata.getProcedureColumns(null, "Derby", "SQLUDTS", null); //$NON-NLS-1$ //$NON-NLS-2$ assertResults(new String[] { "PROCEDURE_CAT[string] PROCEDURE_SCHEM[string] PROCEDURE_NAME[string] COLUMN_NAME[string] COLUMN_TYPE[short] DATA_TYPE[integer] TYPE_NAME[string] PRECISION[integer] LENGTH[integer] SCALE[short] RADIX[integer] NULLABLE[integer] REMARKS[string] COLUMN_DEF[string] SQL_DATA_TYPE[string] SQL_DATETIME_SUB[string] CHAR_OCTET_LENGTH[string] ORDINAL_POSITION[integer] IS_NULLABLE[string] SPECIFIC_NAME[string]", //$NON-NLS-1$ "VDBLess Derby SQLUDTS CATALOGNAME 1 12 string 128 256 0 0 1 null null null null null 1 YES SQLUDTS", //$NON-NLS-1$ "VDBLess Derby SQLUDTS SCHEMAPATTERN 1 12 string 128 256 0 0 1 null null null null null 2 YES SQLUDTS", //$NON-NLS-1$ "VDBLess Derby SQLUDTS TYPENAMEPATTERN 1 12 string 128 256 0 0 1 null null null null null 3 YES SQLUDTS", //$NON-NLS-1$ "VDBLess Derby SQLUDTS UDTTYPES 1 12 string 128 256 0 0 1 null null null null null 4 YES SQLUDTS", //$NON-NLS-1$ "VDBLess Derby SQLUDTS OPTIONS 1 12 string 4000 8000 0 0 1 null null null null null 5 YES SQLUDTS", //$NON-NLS-1$ }); closeConnection(); } }
92.394161
578
0.591918
6df98f80b47f8313b2fe52ff21cdee7e897d1cee
336
package P01_ExtendedArrayList; public class Main { public static void main(String[] args) { ExtendedArrayList<Integer> myList = new ExtendedArrayList<>() {{ add(4); add(5); add(10); add(1); }}; System.out.println(myList.min()); System.out.println(myList.max()); } }
16.8
68
0.565476
bb6e4c5f0689eee39ecec9b8ecf1e48d3540872a
4,727
package cn.icedsoul.messageservice.service.serviceImpl; import cn.icedsoul.commonservice.util.Common; import cn.icedsoul.commonservice.util.Response; import cn.icedsoul.messageservice.domain.Message; import cn.icedsoul.messageservice.repository.MessageRepository; import cn.icedsoul.messageservice.service.serviceApi.MessageService; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; import lombok.extern.java.Log; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.sql.Timestamp; import java.util.Collections; import java.util.List; @Service @Log public class MessageServiceImplement implements MessageService { @Autowired MessageRepository messageRepository; @Override public Response addMessage(Integer fromId, Integer toId, String content, Integer type, String time) { try { Message message = new Message(); message.setFromId(fromId); message.setToId(toId); message.setContent(content); message.setType(type); message.setTime(Common.getTimeFromString(time)); messageRepository.save(message); log.info("I insert message " + message.toString() + " to message-mysql"); return new Response(1, "Insert message success", null); } catch (Exception e){ e.printStackTrace(); return new Response(-1, "Insert message error", null); } } @Override public Response getMessageRecordBetweenUsers(Integer userIdA, Integer userIdB, Integer page, Integer number) { try { Pageable sortedByTime = PageRequest.of(page, number, Sort.by("time").descending()); List<Message> messages = messageRepository.findAllByFromIdAndToIdOrFromIdAndToId(userIdA, userIdB, userIdB, userIdA, sortedByTime); Collections.sort(messages); return new Response(1, "Get message record between users success", JSONArray.toJSONString(messages, SerializerFeature.UseSingleQuotes)); } catch (Exception e) { e.printStackTrace(); return new Response(-1, "Get message record between users error", null); } } @Override public Response addMessages(List<Message> messages) { try { for(Message message : messages){ messageRepository.save(message); } return new Response(1, "add messages success", null); } catch (Exception e) { e.printStackTrace(); return new Response(-1, "add message fail", null); } } private static SerializeConfig mapping = new SerializeConfig(); private static String dateFormat; static { dateFormat = "yyyy-MM-dd HH:mm:ss"; mapping.put(Timestamp.class, new SimpleDateFormatSerializer(dateFormat)); } // /** // * 这个也暂时保留吧,不一定用的上,因为把下最好不把未转发的消息存到消息表,最好加离线消息表,方便查询 // * @param id // * @param isTransport // * @return // */ // @Override // public Response updateMessage(Integer id, Integer isTransport) { // try { // Message message = messageRepository.getOne(id); // message.setIsTransport(isTransport); // messageRepository.save(message); // return new Response(1, "Update message success",null); // } catch (Exception e){ // e.printStackTrace(); // return new Response(1, "Update message error",null); // } // } // // /** // * 暂时保留 // * @param jsonObj // * @return // */ // // @Override // public Response getMessageRecordBetweenUserAndGroup(String jsonObj) { // try { // JSONObject jsonObject = JSONObject.parseObject(jsonObj); // Integer id = jsonObject.getInteger("id"); // Integer userId = jsonObject.getInteger("userId"); // List<Message> messages = messageRepository.findAllByToIdAndTypeAndIsTransport(id, 2, 1); // for (Message message : messages) { // message.setType(1); // message.setToId(userId); // } // return new Response(1, "获取群组聊天记录成功", JSONArray.toJSONString(messages, SerializerFeature.UseSingleQuotes)); // } catch (Exception e) { // e.printStackTrace(); // return new Response(-1, "获取群组聊天记录异常", null); // } // } }
36.929688
148
0.651576
779c71c6f14cb7decc83d4f2368e9ccfd347b8b3
6,185
package com.pcloud.networking.api.adapters; import com.pcloud.networking.api.ApiResponse; import com.pcloud.networking.api.Call; import com.pcloud.networking.api.Interactor; import com.pcloud.networking.api.MultiCall; import org.junit.Before; import org.junit.Test; import rx.observers.TestSubscriber; import java.io.IOException; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; public class RxObservableCallAdapterTest { private Call<ApiResponse> mockCall; private MultiCall<Object, ApiResponse> mockMultiCall; private Interactor<ApiResponse> mockInteractor; private RxObservableCallAdapter<ApiResponse> callAdapter; private TestSubscriber<ApiResponse> subscriber; @SuppressWarnings("unchecked") @Before public void setUp() { callAdapter = new RxObservableCallAdapter<>(ApiResponse.class); mockCall = mock(Call.class); mockMultiCall = mock(MultiCall.class); mockInteractor = mock(Interactor.class); when(mockCall.clone()).thenReturn(mockCall); when(mockMultiCall.clone()).thenReturn(mockMultiCall); when(mockMultiCall.start()).thenReturn(mockInteractor); subscriber = new TestSubscriber<>(); } @Test public void adapt_Call_Returns_NonNull_Observable() { assertNotNull(callAdapter.adapt(mockCall)); } @Test public void adapt_MultiCall_Returns_NonNull_Observable() { assertNotNull(callAdapter.adapt(mockMultiCall)); } @Test public void adapt_Call_Clones_The_Provided_Call() { callAdapter.adapt(mockCall).subscribe(subscriber); verify(mockCall).clone(); } @Test public void adapt_MultiCall_Clones_The_Provided_MultiCall() { callAdapter.adapt(mockMultiCall).subscribe(subscriber); verify(mockMultiCall).clone(); } @Test public void call_Observable_Calls_Call_execute() throws Exception { callAdapter.adapt(mockCall).subscribe(subscriber); verify(mockCall).execute(); } @Test public void call_Observable_Emits_Result_To_Subscriber() throws Exception { ApiResponse response = mock(ApiResponse.class); when(mockCall.execute()).thenReturn(response); callAdapter.adapt(mockCall).subscribe(subscriber); subscriber.assertValues(response); subscriber.assertCompleted(); subscriber.assertNoErrors(); } @Test public void call_Observable_Emits_Errors_To_Subscriber() throws Exception { Throwable error = new IOException(); when(mockCall.execute()).thenThrow(error); callAdapter.adapt(mockCall).subscribe(subscriber); subscriber.assertNoValues(); subscriber.assertError(error); } @Test public void call_Observable_Calls_Call_Cancel_on_Unsubscribe() throws Exception { ApiResponse response = mock(ApiResponse.class); when(mockCall.execute()).thenReturn(response); subscriber = new TestSubscriber<>(0); callAdapter.adapt(mockCall).subscribe(subscriber); subscriber.unsubscribe(); verify(mockCall).cancel(); } @Test public void multiCall_Observable_Calls_MultiCall_start() { callAdapter.adapt(mockMultiCall).subscribe(subscriber); verify(mockMultiCall).start(); } @Test public void multiCall_Observable_Respects_Reactive_Pull() throws Exception { final int pullSize = 5; when(mockInteractor.hasMoreRequests()).thenReturn(true); when(mockInteractor.hasNextResponse()).thenReturn(true); when(mockInteractor.submitRequests(eq(pullSize))).thenReturn(pullSize); subscriber.requestMore(pullSize); callAdapter.adapt(mockMultiCall).subscribe(subscriber); verify(mockInteractor).submitRequests(eq(pullSize)); } @Test public void multiCall_Observable_Emits_Values_To_Subscriber() throws Exception { ApiResponse[] responses = {mock(ApiResponse.class), mock(ApiResponse.class),mock(ApiResponse.class)}; when(mockInteractor.hasMoreRequests()).thenReturn(true, false); when(mockInteractor.hasNextResponse()).thenReturn(true, false); when(mockInteractor.submitRequests(anyInt())).thenReturn(responses.length); when(mockInteractor.nextResponse()).thenReturn(responses[0], responses[1], responses[2]); callAdapter.adapt(mockMultiCall).subscribe(subscriber); verify(mockInteractor, times(responses.length)).nextResponse(); subscriber.assertNoErrors(); subscriber.assertValues(responses); subscriber.assertCompleted(); verify(mockInteractor).close(); } @Test public void multiCall_Observable_Emits_WriteRequest_Errors_To_Subscriber() throws Exception { when(mockInteractor.hasMoreRequests()).thenReturn(true); when(mockInteractor.hasNextResponse()).thenReturn(true); Throwable error = new IOException(); when(mockInteractor.submitRequests(anyInt())).thenThrow(error); callAdapter.adapt(mockMultiCall).subscribe(subscriber); subscriber.assertNoValues(); subscriber.assertError(error); verify(mockInteractor).close(); } @Test public void multiCall_Observable_Emits_ReadResponse_Errors_To_Subscriber() throws Exception { when(mockInteractor.hasMoreRequests()).thenReturn(true); when(mockInteractor.hasNextResponse()).thenReturn(true); Throwable error = new IOException(); when(mockInteractor.submitRequests(anyInt())).thenReturn(Integer.MAX_VALUE); when(mockInteractor.nextResponse()).thenThrow(error); callAdapter.adapt(mockMultiCall).subscribe(subscriber); subscriber.assertNoValues(); subscriber.assertError(error); verify(mockInteractor).close(); } @Test public void multiCall_Observable_Closes_Interactor_On_Unsubscribe() { subscriber.requestMore(0); callAdapter.adapt(mockMultiCall).subscribe(subscriber); subscriber.unsubscribe(); verify(mockInteractor).close(); } }
34.361111
109
0.7135
b67f8d2f8391ed4410ed82a30e99433fdd82a9fb
5,661
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The contents of this file are subject to the terms of either the Universal Permissive License * v 1.0 as shown at http://oss.oracle.com/licenses/upl * * or the following license: * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of the copyright holder 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 HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openjdk.jmc.joverflow.heap.model; import java.io.IOException; import java.nio.BufferUnderflowException; import org.openjdk.jmc.joverflow.heap.parser.DumpCorruptedException; import org.openjdk.jmc.joverflow.heap.parser.ReadBuffer; import org.openjdk.jmc.joverflow.util.MiscUtils; import org.openjdk.jmc.joverflow.util.StringInterner; /** * Represents a Java object array. */ public class JavaObjectArray extends JavaLazyReadObject { private final int length; public JavaObjectArray(JavaClass clazz, long objOfsInFile, int length, int[] dataChunk, int startPosInChunk, int globalObjectIndex) { super(clazz, objOfsInFile, dataChunk, startPosInChunk, globalObjectIndex); this.length = length; } /** * Returns the total size of this object in the heap. That is the sum of object's data * (workload) size plus all the VM overhead: size of the object header plus the size of array * length field. */ @Override public final int getSize() { JavaClass clz = getClazz(); return MiscUtils.getAlignedObjectSize(clz.getPointerSize() * length + clz.getArrayHeaderSize(), clz.getObjectAlignment()); } @Override public final int getImplInclusiveSize() { return getSize(); } @Override public String valueAsString() { return valueAsString(false); } public String valueAsString(boolean bigLimit) { StringBuilder result; JavaHeapObject[] elements = getElements(); int limit = bigLimit ? 1000 : 32; result = new StringBuilder(limit * 16); String humanFriendlyName = getClazz().getHumanFriendlyName(); result.append(humanFriendlyName); int arrayStartPos = humanFriendlyName.indexOf('['); if (arrayStartPos != -1) { result.insert(arrayStartPos + 1, elements.length); } result.append('{'); int num = 0; for (JavaHeapObject element : elements) { if (num > 0) { result.append(", "); } if (num >= limit || (!bigLimit && result.length() > 74)) { result.append(" ..."); break; } num++; result.append(element != null ? element.valueAsString() : "null"); } result.append('}'); return StringInterner.internString(result.toString()); } public JavaHeapObject[] getElements() { Snapshot snapshot = getClazz().getSnapshot(); byte[] data = getValue(); final int idSize = snapshot.getHprofPointerSize(); JavaHeapObject[] elements = new JavaHeapObject[length]; int index = 0; for (int i = 0; i < elements.length; i++) { long id = objectIdAt(index, data); index += idSize; elements[i] = snapshot.getObjectForId(id); } return elements; } // Use Comparator instead of implementing Comparable if sorting is needed // @Override // public int compareTo(JavaThing other) { // if (other instanceof JavaObjectArray) { // return 0; // } // return super.compareTo(other); // } public int getLength() { return length; } @Override public void visitReferencedObjects(JavaHeapObjectVisitor v) { super.visitReferencedObjects(v); JavaHeapObject[] elements = getElements(); for (JavaHeapObject element : elements) { if (element != null) { v.visit(element); } } } @Override protected final byte[] readValue() throws IOException { if (length == 0) { return Snapshot.EMPTY_BYTE_ARRAY; } ReadBuffer buf = clazz.getReadBuffer(); int idSize = clazz.getHprofPointerSize(); // Skip object ID, stack trace serial number (int), array length (int), // and array class ID long offset = getObjOfsInFile() + 2 * idSize + 8; byte[] res = new byte[length * idSize]; try { buf.get(offset, res); } catch (BufferUnderflowException ex) { throw new DumpCorruptedException.Runtime( "object array size for array ID " + MiscUtils.toHex(readId()) + " at offset " + getObjOfsInFile() + " is " + res.length + " bytes, which exceeds heap dump file size"); } return res; } }
34.10241
109
0.723017
10d92c17d611e64b5a64155351bbab96dab9b200
2,271
package Fundstransfer.ext; import java.util.HashMap; import java.util.Map; import javax.annotation.security.PermitAll; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable; import org.jtwig.JtwigModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jarredweb.webjar.service.api.BasicsService; import Fundstransfer.ctx.AppServices; @Path("/quick") public class QuickResource { private static final Logger LOG = LoggerFactory.getLogger(QuickResource.class); @Inject private AppServices service; @Inject private BasicsService basics; public AppServices getService() { return service; } public void setService(AppServices service) { this.service = service; } public BasicsService getBasics() { return basics; } public void setBasics(BasicsService basics) { this.basics = basics; } @GET @Path("/twig") @Produces(MediaType.TEXT_PLAIN) @PermitAll public Response twigHelloView() { LOG.info("executing twig 'quick-resources'"); JtwigModel context = JtwigModel.newModel().with("var", "Twig World!!"); return Response.ok(new Viewable("/hello", context)).build(); } @GET @Path("/ftl") @Produces(MediaType.TEXT_PLAIN) @PermitAll public Response ftlHelloView() { LOG.info("executing ftl 'quick-resources'"); Map<String, Object> context = new HashMap<>(); context.put("var", "Ftl World!!"); return Response.ok(new Viewable("/hello", context)).build(); } @GET @Path("/blogs") @Produces(MediaType.APPLICATION_JSON) @PermitAll public Response fetchAllBlogs() { LOG.info("executing 'fetchAllBlogs'"); Map<String, Object> context = new HashMap<>(); context.put("blogs", service.getBasicsService().get().fetchBlogs().get()); return Response.ok(context).build(); } @GET @Path("/user/{id}") @Produces(MediaType.APPLICATION_JSON) @PermitAll public Response fetchUserById(@PathParam("id") long id) { LOG.info("executing 'fetchUserById'"); Map<String, Object> context = new HashMap<>(); context.put("user", basics.findAccount(id).get()); return Response.ok(context).build(); } }
24.419355
80
0.730515
8c199e943da490052119574a8333ebf942ab47c2
489
package javassist; import javassist.bytecode.Bytecode; class CtMethod$IntConstParameter extends CtMethod$ConstParameter { int param; CtMethod$IntConstParameter(int i) { this.param = i; } int compile(Bytecode code) throws CannotCompileException { code.addIconst(this.param); return 1; } String descriptor() { return "([Ljava/lang/Object;I)Ljava/lang/Object;"; } String constDescriptor() { return "([Ljava/lang/Object;I)V"; } }
19.56
66
0.672802
cd85382e45e38252b9cf56cd9b1d9f71dc5c08b8
1,523
package com.deange.uwaterlooapi.model.courses; import android.os.Parcel; import android.os.Parcelable; import com.deange.uwaterlooapi.model.BaseModel; import com.google.gson.annotations.SerializedName; public class Reserve extends BaseModel implements Parcelable { @SerializedName("reserve_group") String mReserveGroup; @SerializedName("enrollment_capacity") int mEnrollmentCapacity; @SerializedName("enrollment_total") int mEnrollmentTotal; protected Reserve(final Parcel in) { super(in); mReserveGroup = in.readString(); mEnrollmentCapacity = in.readInt(); mEnrollmentTotal = in.readInt(); } @Override public void writeToParcel(final Parcel dest, final int flags) { super.writeToParcel(dest, flags); dest.writeString(mReserveGroup); dest.writeInt(mEnrollmentCapacity); dest.writeInt(mEnrollmentTotal); } public static final Creator<Reserve> CREATOR = new Creator<Reserve>() { @Override public Reserve createFromParcel(final Parcel in) { return new Reserve(in); } @Override public Reserve[] newArray(final int size) { return new Reserve[size]; } }; /** * Name of the reserved group */ public String getReserveGroup() { return mReserveGroup; } /** * Total enrollment capacity of the group */ public int getEnrollmentCapacity() { return mEnrollmentCapacity; } /** * Total reserve enrollment */ public int getEnrollmentTotal() { return mEnrollmentTotal; } }
21.450704
73
0.704531
9f0cc195c340ff06fe99f16ef41ed2a73d34ca1d
4,096
package org.jboss.eap.example.soap.client; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.ConnectException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.ws.BindingProvider; import javax.xml.ws.handler.MessageContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GenericSoapInvocationHandler<T> implements InvocationHandler { private static final Logger LOG = LoggerFactory .getLogger(GenericSoapInvocationHandler.class); private T soapService; private String username; private String password; private String loginTenant; @SuppressWarnings("unchecked") public static <S> S buildProxy(S soapService, String[] authArgs) { return (S) Proxy.newProxyInstance( soapService.getClass().getClassLoader(), new Class[] { soapService.getClass() }, new GenericSoapInvocationHandler<S>(soapService, authArgs)); } public static void sleep() { try { int retryTime = 5; Thread.sleep((int) (2 * retryTime * Math.random())); } catch (Exception e) { LOG.trace("sleep()", e); } } private GenericSoapInvocationHandler(T soapService, String[] authArgs) { int i = 0; username = (String) authArgs[i++]; password = (String) authArgs[i++]; loginTenant = (String) authArgs[i++]; this.soapService = soapService; setupHTTPHeaders((BindingProvider) soapService); } private void setupHTTPHeaders(BindingProvider bp) { Map<String, Object> req_ctx = bp.getRequestContext(); // Standard bindings bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username); bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password); // Custom Headers Map<String, List<String>> headers = new HashMap<>(); headers.put("my.custom.header.tenantid", Collections.singletonList(loginTenant)); req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { LOG.trace( "invoke(Object HelloServiceService={}, Method method={}, Object[] args={}) - start", soapService, method, args); String methodName = method.getName(); if (methodName.startsWith("sendImmediateMessage")) { return method.invoke(soapService, args); } return callAuthenticatedMethod(method, args); } private Object callAuthenticatedMethod(Method method, Object[] args) throws Throwable { Throwable targetException = null; for (int i = 0; i < 100; i++) { try { return method.invoke(soapService, args); } catch (InvocationTargetException e) { targetException = e.getTargetException(); Throwable targetCause = targetException.getCause(); if (targetCause == null || !(targetCause instanceof ConnectException)) { throw targetException; } LOG.error("callAuthenticatedMethod(Object =" + soapService.getClass() + soapService + ", Method method=" + method + ", Object[] args=" + args + ") - exception ignored - " + soapService.getClass() + " soapService=" + soapService + ", Object HelloServiceService=" + soapService + ", Method method=" + method + ", Object[] args=" + args + ", Exception e=" + targetException); } sleep(); } if (targetException != null) { throw targetException; } return null; } }
37.236364
100
0.604492
646db6af0bd6881383dbd4856c57bb39df592fa0
1,082
package com.aspose.barcode.examples.barcode_image.basic_features; import com.aspose.barcode.examples.Utils; import com.aspose.barcode.generation.BarcodeGenerator; import java.awt.*; import java.io.IOException; public class ColorizeBarcodeImage { public static void main(String[] args) throws IOException { //ExStart: ColorizeBarcodeImage // The path to the resource directory. String dataDir = Utils.getDataDir(ColorizeBarcodeImage.class) + "BarcodeImage/BasicFeatures/"; BarcodeGenerator bb = new BarcodeGenerator(com.aspose.barcode.EncodeTypes.CODE_128,"1234567"); //Set background color of the barcode bb.getParameters().setBackColor(Color.YELLOW); //Set the foreground color of the barcode bb.getParameters().getBarcode().setBarColor(Color.BLUE); //Set border's color bb.getParameters().getBorder().setColor(Color.RED); //Set the code text's color bb.getParameters().getBarcode().getCodeTextParameters().setColor(Color.RED); // Save the image bb.save(dataDir + "colorizeBarcode.png"); //ExEnd: ColorizeBarcodeImage } }
31.823529
96
0.756932
8dfe42568dbd55939d65117bb39c83e8153b00f9
155
package org.apidb.apicommon.model.maintain.users5; import java.util.Date; public interface CutoffDateAware { void setCutoffDate(Date date); }
17.222222
51
0.748387
3e27bd13dd1c344704f73ebe4937a3676589dc0b
3,913
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html */ package org.hibernate.test.jpa.compliance.tck2_2; import org.hibernate.Session; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import org.hibernate.test.jpa.AbstractJPATest; import org.junit.Test; import org.hamcrest.CoreMatchers; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; /** * @author Steve Ebersole */ public class ClosedManagerTests extends AbstractJPATest { @Override public void configure(Configuration cfg) { super.configure( cfg ); cfg.setProperty( AvailableSettings.JPA_CLOSED_COMPLIANCE, "true" ); } @Test public void testQuerySetMaxResults() { final Session session = sessionFactory().openSession(); final Query qry = session.createQuery( "select i from Item i" ); session.close(); assertThat( session.isOpen(), CoreMatchers.is ( false ) ); try { qry.setMaxResults( 1 ); fail( "Expecting call to fail" ); } catch (IllegalStateException expected) { } } @Test public void testQuerySetFirstResult() { final Session session = sessionFactory().openSession(); final Query qry = session.createQuery( "select i from Item i" ); session.close(); assertThat( session.isOpen(), CoreMatchers.is ( false ) ); try { qry.setFirstResult( 1 ); fail( "Expecting call to fail" ); } catch (IllegalStateException expected) { } } @Test public void testQuerySetPositionalParameter() { final Session session = sessionFactory().openSession(); final Query qry = session.createQuery( "select i from Item i where i.id = ?1" ); session.close(); assertThat( session.isOpen(), CoreMatchers.is ( false ) ); try { qry.setParameter( 1, 1 ); fail( "Expecting call to fail" ); } catch (IllegalStateException expected) { } } @Test public void testQuerySetNamedParameter() { final Session session = sessionFactory().openSession(); final Query qry = session.createQuery( "select i from Item i where i.id = :id" ); session.close(); assertThat( session.isOpen(), CoreMatchers.is ( false ) ); try { qry.setParameter( "id", 1 ); fail( "Expecting call to fail" ); } catch (IllegalStateException expected) { } } @Test public void testQueryGetPositionalParameter() { final Session session = sessionFactory().openSession(); final Query qry = session.createQuery( "select i from Item i where i.id = ?1" ); qry.setParameter( 1, 1 ); session.close(); assertThat( session.isOpen(), CoreMatchers.is ( false ) ); try { qry.getParameter( 1 ); fail( "Expecting call to fail" ); } catch (IllegalStateException expected) { } try { qry.getParameter( 1, Integer.class ); fail( "Expecting call to fail" ); } catch (IllegalStateException expected) { } } @Test public void testQueryGetNamedParameter() { final Session session = sessionFactory().openSession(); final Query qry = session.createQuery( "select i from Item i where i.id = :id" ); qry.setParameter( "id", 1 ); session.close(); assertThat( session.isOpen(), CoreMatchers.is ( false ) ); try { qry.getParameter( "id" ); fail( "Expecting call to fail" ); } catch (IllegalStateException expected) { } try { qry.getParameter( "id", Long.class ); fail( "Expecting call to fail" ); } catch (IllegalStateException expected) { } } @Test public void testClose() { final Session session = sessionFactory().openSession(); // 1st call - should be ok session.close(); try { // 2nd should fail (JPA compliance enabled) session.close(); fail(); } catch (IllegalStateException expected) { // expected outcome } } }
23.431138
91
0.691541
80e404c888eb1e6416eed9b9cdbbb99af0e82fc5
5,275
package org.broadband_forum.obbaa.netconf.mn.fwk.server.model.support.annotation; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.ModelNode; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.ModelNodeCreateException; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.ModelNodeId; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.support.ChildContainerHelper; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.support.ConfigLeafAttribute; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.support.CreateStrategy; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.support.HelperDrivenModelNode; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.support.ModelNodeDeleteException; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.support.ModelNodeFactory; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.support.ModelNodeGetException; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.support.ModelNodeHelperRegistry; import org.broadband_forum.obbaa.netconf.mn.fwk.server.model.support.ModelNodeSetException; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; public class AnnotationChildContainerHelper extends AnnotationConstraintHelper implements ChildContainerHelper { private Method m_getterMethod; private Method m_setterMethod; private String m_name; @SuppressWarnings("unused") private CreateStrategy m_createStrategy; private String m_factoryName; private ModelNodeHelperRegistry m_modelNodeHelperRegistry; private SchemaPath m_childSchemaPath; public AnnotationChildContainerHelper(String name, CreateStrategy createStrategy, String factoryName, Method getterMethod, Method setterMethod, SchemaPath childSchemaPath, ModelNodeHelperRegistry modelNodeHelperRegistry) { m_name = name; m_createStrategy = createStrategy; m_factoryName = factoryName; m_getterMethod = getterMethod; m_setterMethod = setterMethod; m_childSchemaPath = childSchemaPath; m_modelNodeHelperRegistry = modelNodeHelperRegistry; } /** * For UT Only * */ protected Method getGetterMethod() { return m_getterMethod; } /** * For UT Only * */ protected Method getSetterMethod() { return m_setterMethod; } public AnnotationChildContainerHelper(Method m) { m_getterMethod = m; } public ModelNode getValue(ModelNode node) throws ModelNodeGetException { try { return (HelperDrivenModelNode) m_getterMethod.invoke(node); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new ModelNodeGetException("Could not get child node from ModelNode: " + node, e); } } public void deleteChild(ModelNode parentNode) throws ModelNodeDeleteException { Object arg = null; try { m_setterMethod.invoke(parentNode, arg); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new ModelNodeDeleteException("could not delete childNode from modelNode" + parentNode, e); } } @SuppressWarnings("unchecked") public ModelNode createChild(ModelNode parentNode, Map<QName, ConfigLeafAttribute> keyAttrs) throws ModelNodeCreateException { ModelNodeFactory factory = m_modelNodeHelperRegistry.getCreateFactory(m_factoryName); ModelNode newNode = null; if (parentNode.hasSchemaMount()) { newNode = factory.getModelNode((Class<? extends ModelNode>) m_getterMethod.getReturnType(), parentNode, new ModelNodeId(parentNode.getModelNodeId()), parentNode.getMountModelNodeHelperRegistry(), parentNode.getMountSubSystemRegistry(), parentNode.getMountRegistry(), keyAttrs); } else { newNode = factory.getModelNode((Class<? extends ModelNode>) m_getterMethod.getReturnType(), parentNode, new ModelNodeId(parentNode.getModelNodeId()), ((HelperDrivenModelNode)parentNode).getModelNodeHelperRegistry(), ((HelperDrivenModelNode)parentNode).getSubSystemRegistry(), ((HelperDrivenModelNode)parentNode).getSchemaRegistry(), keyAttrs); } try { m_setterMethod.invoke(parentNode, newNode); return newNode; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new ModelNodeCreateException("could not create child node from ModelNode:" + parentNode, e); } } @Override public SchemaPath getChildModelNodeSchemaPath() { return m_childSchemaPath; } @Override public ModelNode setValue(ModelNode parentNode, ModelNode childNode) throws ModelNodeSetException { try { m_setterMethod.invoke(parentNode, childNode); return childNode; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new ModelNodeSetException("could not create child node from ModelNode:" + parentNode, e); } } @Override public DataSchemaNode getSchemaNode() { return null; } }
41.535433
226
0.777062
6818ba83b9c799f87491d3a77cbab859be9c29af
1,098
package com.liferay.docs.guestbook.service.permission; import com.liferay.docs.guestbook.model.Guestbook; import com.liferay.docs.guestbook.service.GuestbookLocalServiceUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.security.auth.PrincipalException; import com.liferay.portal.security.permission.PermissionChecker; public class GuestbookPermission { public static void check(PermissionChecker permissionChecker, long guestbookId, String actionId) throws PortalException, SystemException { if (!contains(permissionChecker, guestbookId, actionId)) { throw new PrincipalException(); } } public static boolean contains(PermissionChecker permissionChecker, long guestbookId, String actionId) throws PortalException, SystemException { Guestbook guestbook = GuestbookLocalServiceUtil .getGuestbook(guestbookId); return permissionChecker .hasPermission(guestbook.getGroupId(), Guestbook.class.getName(), guestbook.getGuestbookId(), actionId); } }
32.294118
68
0.806011
944608beb576311c8dc0d51c5cb45639d0bc847b
2,586
package servlet; import database.DbStore; import logic.Store; import model.Role; import model.User; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class UserUpdateServlet extends HttpServlet { private final Store store = DbStore.getInstance(); private List<User> userList = store.findAll(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { req.setAttribute("countries", (ArrayList<String>) store.getCountries()); req.getRequestDispatcher("WEB-INF/views/update.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String name = req.getParameter("name"); String login = req.getParameter("login"); String email = req.getParameter("email"); String password = req.getParameter("password"); String country = req.getParameter("country"); String town = req.getParameter("town"); if (name.equals("") || login.equals("") || email.equals("") || password.equals("") || req.getParameter("role").equals("") || country.equals("") || town.equals("")) { req.setAttribute("createError", "Input all fields"); req.getRequestDispatcher("WEB-INF/views/update.jsp").forward(req, resp); } else { Role role = Role.valueOf(req.getParameter("role")); User userToUpdate = new User(Integer.parseInt(req.getParameter("id")), name, login, email, LocalDate.now(), password, role, country, town ); store.update(userToUpdate); if (req.getSession(false).getAttribute("role").toString().equals("Admin")) { req.setAttribute("usersFromServer", store.findAll()); req.getRequestDispatcher("WEB-INF/views/users.jsp").forward(req, resp); } else { req.setAttribute("user", userToUpdate); req.getRequestDispatcher("WEB-INF/views/onlyuser.jsp").forward(req, resp); } } } }
38.597015
114
0.602475
76b398a548a192a8c679a1eed8572598f96c41ec
2,596
package com.stephenboyer.soapstore.domain; import com.stephenboyer.soapstore.util.Strings; public class Address { // @Id public String id; String address_line_1; String address_line_2; String locality; String administrative_district_level_1; String postal_code; String country; String first_name; String last_name; public Address(String address_line_1, String address_line_2, String locality, String administrative_district_level_1, String postal_code, String country, String first_name, String last_name) { this.address_line_1 = address_line_1; this.address_line_2 = address_line_2; this.locality = locality; this.administrative_district_level_1 = administrative_district_level_1; this.postal_code = postal_code; this.country = country; this.first_name = first_name; this.last_name = last_name; } public String getId(){ return id; } public void setId(String id){ this.id = id; } public String getAddress_line_1() { return address_line_1; } public void setAddress_line_1(String address_line_1) { this.address_line_1 = address_line_1; } public String getAddress_line_2() { return address_line_2; } public void setAddress_line_2(String address_line_2) { this.address_line_2 = address_line_2; } public String getLocality() { return locality; } public void setLocality(String locality) { this.locality = locality; } public String getAdministrative_district_level_1() { return administrative_district_level_1; } public void setAdministrative_district_level_1(String administrative_district_level_1) { this.administrative_district_level_1 = administrative_district_level_1; } public String getPostal_code() { return postal_code; } public void setPostal_code(String postal_code) { this.postal_code = postal_code; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } @Override public String toString() { return Strings.toString(this); } }
24.037037
196
0.675655
40e5e40ec9ed759ffb08046a47f6dd72d04e1752
948
package String_Inheritance; public class Teacher { String id; String Name; String Password; String Email; public void tinfo() { System.out.println("ID of Teacher is :"+" "+ id); System.out.println("Name of Teacher is :"+" "+ Name); System.out.println("Password of Teacher is :"+" "+ Password); System.out.println("Email of Taecher is :"+" "+ Email); } public void dddLecture() { System.out.println(Name+" "+"Can add lectures "); } public void markAttendance() { System.out.println(Name+"'"+"Can Mark Attendance"); } public void viewAttendance() { System.out.println(Name +" "+"Can view Attendance"); } public void prepareAttendanceReport() { System.out.println(Name +" "+"Can prepareAttendanceReport Attendance"); } public void viewAttendanceReport() { System.out.println(Name +" "+"Can view Attendance Report"); } }
21.545455
76
0.617089
4298d8a610488eda32e624a41eebc73a70561e8e
1,972
/** * Copyright 2012-2020 The Feign Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package feign.jackson; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.lang.reflect.Type; import java.util.Collections; import feign.RequestTemplate; import feign.codec.EncodeException; import feign.codec.Encoder; import feign.Util; public class JacksonEncoder implements Encoder { private final ObjectMapper mapper; public JacksonEncoder() { this(Collections.<Module>emptyList()); } public JacksonEncoder(Iterable<Module> modules) { this(new ObjectMapper() .setSerializationInclusion(JsonInclude.Include.NON_NULL) .configure(SerializationFeature.INDENT_OUTPUT, true) .registerModules(modules)); } public JacksonEncoder(ObjectMapper mapper) { this.mapper = mapper; } @Override public void encode(Object object, Type bodyType, RequestTemplate template) { try { JavaType javaType = mapper.getTypeFactory().constructType(bodyType); template.body(mapper.writerFor(javaType).writeValueAsBytes(object), Util.UTF_8); } catch (JsonProcessingException e) { throw new EncodeException(e.getMessage(), e); } } }
34
100
0.763185
a43e7d5fe96731db9d88829c1d0991c12e8e10fa
113
package com.ngames.nclient.gui.element.window; public class ElementWindowHackSettings extends ElementWindow { }
22.6
62
0.840708
cc18299af595e8e37240e8facb13504506c6d936
15,210
package com.emperium.utils; import com.emperium.domain.Measurement; import com.emperium.hibernate.HibernateAnnotationUtil; import com.emperium.model.City; import com.emperium.model.Day; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import org.hibernate.resource.transaction.spi.TransactionStatus; import java.time.LocalDate; import java.util.List; /** * Class that holds all SQL operations. */ public class SQL { private static SQL instance; private SQL(){} public static SQL getInstance() { if(instance == null){ instance = new SQL(); } return instance; } private static final String INSERT_INTO_MEASUREMENT = "INSERT INTO Measurement(time, temperature, humidity, wind, phenomeno, day_id) VALUES" + " (:time, :temperature, :humidity, :wind, :phenomeno, :day_id)"; private final String UPDATE_TEMPERATURE = "UPDATE Measurement SET temperature=:temperature WHERE id=:id"; private final String UPDATE_HUMIDITY = "UPDATE Measurement SET humidity=:humidity WHERE id=:id"; private final String UPDATE_WIND = "UPDATE Measurement SET wind=:wind WHERE id=:id"; private final String UPDATE_PHENOMENO = "UPDATE Measurement SET phenomeno=:phenomeno WHERE id=:id"; private final String SELECT_CITY_PREDICTIONS_BY_DAY = "SELECT C.city, D.day, M.time, M.temperature, M.wind, M.humidity, M.phenomeno FROM Measurement AS M" + " JOIN Day AS D on M.day_id = D.id" + " JOIN City C on D.city_id = C.id where D.day=:day AND C.city=:city"; private final String SELECT_CITY_PREDICTIONS_BY_TIME = "SELECT C.city, D.day, M.time, M.temperature, M.wind, M.humidity, M.phenomeno FROM Measurement AS M" + " JOIN Day AS D on M.day_id = D.id" + " JOIN City C on D.city_id = C.id where D.day=:day AND C.city=:city AND M.time=:time"; private final String SELECT_CITY_PREDICTIONS = "SELECT C.city, D.day, M.time, M.temperature, M.wind, M.humidity, M.phenomeno FROM Measurement AS M" + " JOIN Day AS D on M.day_id = D.id" + " JOIN City AS C on D.city_id = C.id where C.city=:city" + " AND D.day >= current_date and M.id >= (SELECT MeasurementId(city))"; private SessionFactory sessionFactory() { SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory(); return sessionFactory; } private SessionFactory sessFactory = sessionFactory(); /** * Gets the id of a specified city. * * @param city * @return the id */ public int getCityId(String city) { Session session = this.sessFactory.openSession(); Query query = session.createSQLQuery("SELECT id FROM City WHERE city=:city"); query.setParameter("city", city); List<Object> results = query.getResultList(); session.close(); return (int) results.get(0); } /** * Checks if measurements for a specified day are set * * @param day_id the day id * @return true if measurements are set */ public boolean dailyMeasurementsAreSet(int day_id) { Session session = this.sessFactory.openSession(); String hql = "SELECT * FROM Measurement WHERE day_id =:day_id"; Query query = session.createSQLQuery(hql); query.setParameter("day_id", day_id); List<Object[]> results = query.getResultList(); session.close(); return results.isEmpty() ? false : true; } /** * Gets the id of a specified day that already exists in the database. * * @param day the day * @return the id of the day. */ public int getDayId(LocalDate day, int city_id) { String hql = "SELECT id FROM Day WHERE day=:day AND city_id=:city_id"; Session session = this.sessFactory.openSession(); Query query = session.createSQLQuery(hql); query.setParameter("day", day); query.setParameter("city_id", city_id); List<Object> result = query.getResultList(); session.close(); return (int) result.get(0); } /** * Checks if the date for a specified city is already set. * * @param day the day * @param city_id city id * @return true if the date already exists in the database. */ public boolean dayIsSet(LocalDate day, int city_id) { Session session = this.sessFactory.openSession(); String hql = "SELECT day FROM Day WHERE day=:day AND city_id=:city_id"; Query query = session.createSQLQuery(hql); query.setParameter("day", day); query.setParameter("city_id", city_id); List<Object> result = query.getResultList(); session.close(); return !result.isEmpty() ? true : false; } /** * Inserts measurements for a specified day. * * @param measurements measurements * @param dayId day id */ public void setDailyMeasurement(List<Measurement> measurements, int dayId) { for(Measurement measurement: measurements) { Session session = this.sessFactory.openSession(); Transaction tx = session.beginTransaction(); Query query = session.createSQLQuery(INSERT_INTO_MEASUREMENT); query.setParameter("time", measurement.getEventTime()); query.setParameter("temperature", measurement.getTemperature()); query.setParameter("humidity", measurement.getHumidity()); query.setParameter("wind", measurement.getWind()); query.setParameter("phenomeno", measurement.getPhenomeno()); query.setParameter("day_id", dayId); query.executeUpdate(); commitTransaction(tx); session.close(); } } /** * Checks if measurements are the same and updates id necessary. * * @param day_id the day id * @param measurements list of measurements */ public void checkAndUpdateDailyMeasurement(int day_id, List<Measurement> measurements) { Session session = this.sessFactory.openSession(); String sqlQuery = "SELECT * FROM " + "(SELECT * FROM Measurement WHERE day_id = " + day_id + " ORDER BY id DESC LIMIT " + measurements.size() + ") " + "a ORDER BY id;"; Query query = session.createSQLQuery(sqlQuery); List<Object[]> result = query.getResultList(); session.close(); int i = 0; for(Object[] data : result) { if(data[2].equals(measurements.get(i).getTemperature())) { assert true; } else { updateMeasurement(UPDATE_TEMPERATURE, measurements.get(i), data[0], "temperature"); } if(data[3].equals(measurements.get(i).getHumidity())) { assert true; } else { updateMeasurement(UPDATE_HUMIDITY, measurements.get(i), data[0], "humidity"); } if(data[4].equals(measurements.get(i).getWind())) { assert true; } else { updateMeasurement(UPDATE_WIND, measurements.get(i), data[0], "wind"); } if(data[5].equals(measurements.get(i).getPhenomeno())) { assert true; } else { updateMeasurement(UPDATE_PHENOMENO, measurements.get(i), data[0], "phenomeno"); } i++; } if( i < 8){ for (int k = i; k < measurements.size(); k++ ){ Session sess = this.sessFactory.openSession(); Transaction tx = sess.beginTransaction(); Query ms = sess.createSQLQuery(INSERT_INTO_MEASUREMENT); ms.setParameter("time", measurements.get(k).eventTime); ms.setParameter("temperature", measurements.get(k).temperature); ms.setParameter("humidity", measurements.get(k).humidity); ms.setParameter("wind", measurements.get(k).wind); ms.setParameter("phenomeno", measurements.get(k).phenomeno); ms.setParameter("day_id", day_id); ms.executeUpdate(); commitTransaction(tx); sess.close(); } } } /** * Update any of the measurements specified in the parameter if they differ * * @param hql the hql * @param measurement measurement Object * @param id id * @param record record */ private void updateMeasurement(String hql, Measurement measurement, Object id, String record) { Session session = this.sessFactory.openSession(); Object val; switch(record) { case "temperature": val = measurement.getTemperature(); break; case "humidity": val = measurement.getHumidity(); break; case "wind": val = measurement.getWind(); break; default: val = measurement.getPhenomeno(); } Transaction tx = session.beginTransaction(); Query query = session.createSQLQuery(hql); query.setParameter(record, val); query.setParameter("id", id); query.executeUpdate(); commitTransaction(tx); session.close(); } /** * Checks if a specified city is already set in the database. * * @param city city name * @return true if a specified city is set */ public boolean cityIsSet(String city) { Session session = this.sessFactory.openSession(); Query query = session.createSQLQuery("SELECT city FROM City WHERE city=:city"); query.setParameter("city", city); List<Object> results = query.getResultList(); session.close(); return !results.isEmpty() ? true : false; } /** * Deletes the measurements of the previous days. * * @param city_id city id used to query and delete previous measurements */ public void deleteMeasurementsByDayId(int city_id) { Session session = this.sessFactory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); String hql = "DELETE FROM Measurement WHERE day_id BETWEEN (SELECT id FROM Day WHERE city_id=:city_id AND day < current_date ORDER BY id ASC LIMIT 1)" + " AND (SELECT id FROM Day WHERE city_id=:city_id AND day < current_date ORDER BY id DESC LIMIT 1)"; Query query = session.createSQLQuery(hql); query.setParameter("city_id", city_id); query.executeUpdate(); commitTransaction(tx); }catch (Exception e) { if(tx != null) tx.rollback(); }finally { session.close(); } } /** * Deletes days which are earlier than the current day for a specified city * * @param city_id the city id for which days are deleted */ public void deleteDays(int city_id) { Session session = sessFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); String sql = "DELETE from Day where city_id=:city_id AND day < current_date"; Query query = session.createSQLQuery(sql); query.setParameter("city_id", city_id); query.executeUpdate(); commitTransaction(tx); } catch (Exception e) { if(tx != null) tx.rollback(); } finally { session.close(); } } /** * Saves a city to database. * * @param city city name */ public void saveCity(City city) { Session session = this.sessFactory.openSession(); Transaction tx = session.beginTransaction(); session.save(city); commitTransaction(tx); session.close(); } /** * Inserts new days and measurement into an existing City. * * @param day the Day entity * @param city the City entity */ public void insertByCityId(Day day, City city) { Session session = this.sessFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); day.setCity(city); session.save(day); commitTransaction(tx); } catch (Exception e) { e.printStackTrace(); if(tx != null) tx.rollback(); } finally { session.close(); } } /** * Gets a City entity by id. * * @param city_id the city id. * @return the City entity */ public City getCityById(int city_id) { Session session = this.sessFactory.openSession(); City city = null; try{ session = this.sessFactory.openSession(); city = session.load(City.class, city_id); }catch (Exception e){ e.printStackTrace(); } finally { if(session != null && session.isOpen()) { session.close(); } } return city; } /** * Gets the predictions for a day for a specified city. * * @param city city * @param date date * @return result list */ public List<Object[]> getCityDailyPredictions(String city, String date) { Session session = this.sessFactory.openSession(); Query cityQuery = session.createSQLQuery(SELECT_CITY_PREDICTIONS_BY_DAY); cityQuery.setParameter("city", city); cityQuery.setParameter("day", date); List<Object[]> result = cityQuery.list(); session.close(); return result; } /** * Gets the predictions for a specified time of a day, for a specified city. * * @param city city * @param date date * @param time time * @return result list */ public List<Object[]> getCityPredictionsPerHour(String city, String date, String time) { Session session = this.sessFactory.openSession(); Query query = session.createSQLQuery(SELECT_CITY_PREDICTIONS_BY_TIME); query.setParameter("city", city); query.setParameter("day", date); query.setParameter("time", time); List<Object[]> result = query.list(); session.close(); return result; } /** * Gets all the predictions for a specified city, from the time requested and onwards. * * @param city city * @return result list */ public List<Object[]> getCityPredictions(String city) { Session session = this.sessFactory.openSession(); Query query = session.createSQLQuery(SELECT_CITY_PREDICTIONS); query.setParameter("city", city); List<Object[]> result = query.list(); session.close(); return result; } /** * Commits a transaction. * * @param tx transaction object */ private static void commitTransaction(Transaction tx) { if(tx.getStatus().equals(TransactionStatus.ACTIVE)) { tx.commit(); } } }
33.8
164
0.598028
d2f4fadcdf6ef9b52fe24910452eb8fa33decea4
332
package com.codeosseum.ares.matchmaking.faultseeding.twoplayer; import com.codeosseum.ares.matchmaking.foundation.matchmaker.MatchmakingRequest; public class TwoPlayerFaultSeedingMatchmakingRequest extends MatchmakingRequest { public TwoPlayerFaultSeedingMatchmakingRequest(String username) { super(username); } }
33.2
81
0.828313
1f7fe2b07a359cb7b73fbfc2a5fb2294638623a1
279
package com.nh.themvpdesign.di.scopes; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.inject.Scope; /** * Created by dell pc on 11-11-2017. */ @Scope @Retention(RetentionPolicy.CLASS) public @interface ApplicationScope { }
17.4375
44
0.774194
de3917b64f7a2277849094aa164b0a2e7bd8b7d7
1,181
package cc.codeasy.ddd.sample.mall.credit.domain.model; import javax.persistence.Embeddable; import java.util.Objects; @Embeddable public class Amount { Integer amount; protected Amount() { } public Amount(Integer amount) { if (amount == null || amount.intValue() <= 0) throw new IllegalArgumentException("amount should not be null or less than 1."); this.amount = amount; } public Integer getAmount() { return amount; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Amount amount1 = (Amount) o; return amount.equals(amount1.amount); } @Override public int hashCode() { return Objects.hash(amount); } @Override public String toString() { return "Amount{" + "amount=" + amount + '}'; } public Amount add(Amount amount) { return new Amount(this.amount + amount.getAmount()); } public Amount subtract(Amount amount) { return new Amount(this.amount - amount.getAmount()); } }
22.283019
92
0.589331
04befd80dd3e2a3be015997875fe63058f079447
2,273
package me.elsiff.morefish.fishing.competition; import java.time.LocalTime; import java.util.Collection; import javax.annotation.Nonnull; import me.elsiff.morefish.MoreFish; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; public final class FishingCompetitionAutoRunner { private static final long HALF_MINUTE = 600L; private final MoreFish plugin = MoreFish.instance(); private final FishingCompetitionHost competitionHost = plugin.getCompetitionHost(); private Collection<LocalTime> scheduledTimes; private BukkitTask timeCheckingTask; public void disable() { if (timeCheckingTask == null) { throw new IllegalStateException("Auto runner must not be disabled"); } timeCheckingTask.cancel(); timeCheckingTask = null; } public void enable() { if (timeCheckingTask != null) { throw new IllegalStateException("Auto runner must not be already enabled"); } timeCheckingTask = new TimeChecker(this::tryOpenCompetition).runTaskTimer(plugin, 0, HALF_MINUTE); } public boolean isEnabled() { return this.timeCheckingTask != null; } public void setScheduledTimes(@Nonnull Collection<LocalTime> scheduledTimes) { this.scheduledTimes = scheduledTimes; } private void tryOpenCompetition() { FileConfiguration config = plugin.getConfig(); int requiredPlayers = config.getInt("auto-running.required-players"); if (competitionHost.getCompetition().isDisabled() && plugin.getServer().getOnlinePlayers().size() >= requiredPlayers) { long duration = config.getLong("auto-running.timer") * 20L; competitionHost.openCompetitionFor(duration); } } private final class TimeChecker extends BukkitRunnable { private final Runnable work; TimeChecker(@Nonnull Runnable work) { super(); this.work = work; } public void run() { LocalTime currentTime = LocalTime.now().withSecond(0).withNano(0); scheduledTimes.stream().filter(it -> it.equals(currentTime)).forEach(it -> work.run()); } } }
32.942029
127
0.683238
9ecd5e18b98b72310b96c362bc40393dc359e79c
1,576
package sagex.util; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public class ReflectionUtil { public static Class getGenericReturnType(Method method) { Type returnType = method.getGenericReturnType(); if (returnType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) returnType; Type[] typeArguments = type.getActualTypeArguments(); if (typeArguments.length > 0) { return (Class) typeArguments[0]; } } return null; } public static Class getGenericReturnType(Field field) { Type returnType = field.getGenericType(); if (returnType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) returnType; Type[] typeArguments = type.getActualTypeArguments(); if (typeArguments.length > 0) { return (Class) typeArguments[0]; } } return null; } public static Class getGenericReturnType(Type returnType) { if (returnType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) returnType; Type[] typeArguments = type.getActualTypeArguments(); if (typeArguments.length > 0) { if (typeArguments[0] instanceof Class) { return (Class) typeArguments[0]; } } } return null; } }
32.833333
68
0.614848
beabb009811dc3cc978131bf9023fea5b7d08b08
339
package com.unithis.model; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @NoArgsConstructor @Getter @ToString public class ChatRoomRequest { long id; long userId; @Builder public ChatRoomRequest(long id, long userId) { super(); this.id = id; this.userId = userId; } }
14.73913
47
0.749263
325a616ffdb581f9b7e9f749f8d79db9f06289ef
2,565
package com.pierfrancescosoffritti.androidyoutubeplayer.core.sampleapp.examples.chromecastExample.utils; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.Log; import com.google.android.gms.cast.framework.CastButtonFactory; import com.pierfrancescosoffritti.androidyoutubeplayer.core.sampleapp.examples.chromecastExample.ChromeCastExampleActivity; import com.pierfrancescosoffritti.aytplayersample.R; import androidx.annotation.Nullable; import androidx.appcompat.view.ContextThemeWrapper; import androidx.core.content.ContextCompat; import androidx.core.graphics.drawable.DrawableCompat; import androidx.mediarouter.app.MediaRouteButton; public class MediaRouteButtonUtils { static public MediaRouteButton initMediaRouteButton(Context context) { MediaRouteButton mediaRouteButton = new MediaRouteButton(context); CastButtonFactory.setUpMediaRouteButton(context, mediaRouteButton); return mediaRouteButton; } static public void addMediaRouteButtonToPlayerUi( MediaRouteButton mediaRouteButton, int tintColor, @Nullable ChromeCastExampleActivity.MediaRouteButtonContainer disabledContainer, ChromeCastExampleActivity.MediaRouteButtonContainer activatedContainer) { setMediaRouterButtonTint(mediaRouteButton, tintColor); if(disabledContainer != null) { disabledContainer.removeMediaRouteButton(mediaRouteButton); } if(mediaRouteButton.getParent() != null) { return; } activatedContainer.addMediaRouteButton(mediaRouteButton); } static private void setMediaRouterButtonTint(MediaRouteButton mediaRouterButton, int color) { ContextThemeWrapper castContext = new ContextThemeWrapper(mediaRouterButton.getContext(), R.style.Theme_MediaRouter); TypedArray styledAttributes = castContext.obtainStyledAttributes(null, androidx.mediarouter.R.styleable.MediaRouteButton, androidx.mediarouter.R.attr.mediaRouteButtonStyle, 0); Drawable drawable = styledAttributes.getDrawable(androidx.mediarouter.R.styleable.MediaRouteButton_externalRouteEnabledDrawable); if(drawable == null) { Log.e("MediaRouteButtonUtils", "can't apply tint to MediaRouteButton"); return; } styledAttributes.recycle(); DrawableCompat.setTint(drawable, ContextCompat.getColor(mediaRouterButton.getContext(), color)); mediaRouterButton.setRemoteIndicatorDrawable(drawable); } }
43.474576
184
0.782456
c94eec9a08e8ab05b3e6e9b742f2cbd1a9785c52
1,347
package com.alibaba.chaosblade.exec.plugin.jvm.oom.executor.impl; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import com.alibaba.chaosblade.exec.common.aop.EnhancerModel; import com.alibaba.chaosblade.exec.plugin.jvm.JvmConstant; import com.alibaba.chaosblade.exec.plugin.jvm.oom.JvmMemoryArea; import com.alibaba.chaosblade.exec.plugin.jvm.oom.executor.JvmOomExecutor; /** * @author RinaisSuper * @date 2019-04-18 * @email rinalhb@icloud.com */ public class OffHeapJvmOomExecutor extends JvmOomExecutor { @Override public JvmMemoryArea supportArea() { return JvmMemoryArea.OFFHEAP; } private List<ByteBuffer> oomObjects = new ArrayList<ByteBuffer>(); @Override protected void innerRun(EnhancerModel enhancerModel, JvmOomConfiguration jvmOomConfiguration) { oomObjects.add(ByteBuffer.allocateDirect(jvmOomConfiguration.getBlock() * JvmConstant.ONE_MB)); } @Override public void run(EnhancerModel enhancerModel) throws Exception { oomObjects = new ArrayList<ByteBuffer>(); super.run(enhancerModel); } @Override protected void recycleMemory() { this.oomObjects = new ArrayList<ByteBuffer>(); } @Override protected void innerStop(EnhancerModel enhancerModel) { this.oomObjects = null; } }
28.0625
103
0.737194
ea0d61d22b08bb196c234199ec2742a2c1338baf
1,746
/** * Container for a turn restriction * * @author ab */ package cgeo.geocaching.brouter.mapaccess; public final class TurnRestriction { public boolean isPositive; public short exceptions; public int fromLon; public int fromLat; public int toLon; public int toLat; public TurnRestriction next; public static boolean isTurnForbidden(final TurnRestriction first, final int fromLon, final int fromLat, final int toLon, final int toLat, final boolean bikeMode, final boolean carMode) { boolean hasAnyPositive = false; boolean hasPositive = false; boolean hasNegative = false; TurnRestriction tr = first; while (tr != null) { if ((tr.exceptBikes() && bikeMode) || (tr.exceptMotorcars() && carMode)) { tr = tr.next; continue; } if (tr.fromLon == fromLon && tr.fromLat == fromLat) { if (tr.isPositive) { hasAnyPositive = true; } if (tr.toLon == toLon && tr.toLat == toLat) { if (tr.isPositive) { hasPositive = true; } else { hasNegative = true; } } } tr = tr.next; } return !hasPositive && (hasAnyPositive || hasNegative); } public boolean exceptBikes() { return (exceptions & 1) != 0; } public boolean exceptMotorcars() { return (exceptions & 2) != 0; } @Override public String toString() { return "pos=" + isPositive + " fromLon=" + fromLon + " fromLat=" + fromLat + " toLon=" + toLon + " toLat=" + toLat; } }
28.622951
191
0.531501
d0af9b8acfc73fe5060472e0468e40310754f116
962
package ru.nivanov.repository.mapper; import ru.nivanov.dao.AddressDao; import ru.nivanov.dao.factory.DaoFactory; import ru.nivanov.dao.factory.PostgresDaoFactory; import ru.nivanov.entity.Address; import java.util.Collection; /** * Created by Nikolay Ivanov on 17.05.2018. */ public class StringToAddressMapper implements Mapper<String, Address> { private final DaoFactory factory = new PostgresDaoFactory(); private final AddressDao addressDao = factory.getAddressDao(); @Override public Address map(String addr) { Address result = null; Collection<Address> addresses = this.addressDao.getAll(); for (Address loc : addresses) { if (loc.getLocation().equalsIgnoreCase(addr)) { result = loc; break; } } if (result == null) { result = new Address(); result.setLocation("empty"); } return result; } }
27.485714
71
0.640333
e859f02a975a5f6941af2af57107ee78aa685cf9
10,201
package com.hikvision.entity; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class DateUtil { /* * author: haitao zhang des:获取时间 格式:2015-05-03 date:2015-07-27 */ public static java.sql.Date getDate() { java.util.Date uDate = new java.util.Date(); java.sql.Date sDate = new java.sql.Date(uDate.getTime()); return sDate; } public static java.sql.Date getyMdDate(java.util.Date date) { java.sql.Date sDate = new java.sql.Date(date.getTime()); return sDate; } /* * author: haitao zhang des:获取时间 格式:2015-05-03 02:20:20 date:2015-07-27 */ public static String getDateFormat() { java.util.Date uDate = new java.util.Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // java.sql.Date sDate = new java.sql.Date(uDate.getTime()); String str = sf.format(uDate.getTime()); return str; }// public static Date stringCovertDate(String dateString) { Date date = new Date(); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd "); date = sdf.parse(dateString); } catch (ParseException e) { System.out.println(e.getMessage()); } return date; } /* * author: haitao zhang des:获取时间 格式:2015-05-03 02:20:20 date:2015-07-27 */ public static String getDateFormatSSS() { java.util.Date uDate = new java.util.Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); // java.sql.Date sDate = new java.sql.Date(uDate.getTime()); String str = sf.format(uDate.getTime()); return str; }// /* * author: haitao zhang des:获取时间 格式:2015-05-03 02:20:20 date:2015-07-27 */ public static Date getDateFormatdae() { java.util.Date uDate = new java.util.Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); // java.sql.Date sDate = new java.sql.Date(uDate.getTime()); String str = sf.format(uDate.getTime()); return stringCovertDate(str); }// public static String getDateFormatss() { java.util.Date uDate = new java.util.Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // java.sql.Date sDate = new java.sql.Date(uDate.getTime()); String str = sf.format(uDate.getTime()); return str; }// /* * author: kang li des:获取时间 格式:2016-03-23 date:2015-07-27没有分秒 */ public static String getDateFormatWithoutMinutes() { java.util.Date uDate = new java.util.Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); // java.sql.Date sDate = new java.sql.Date(uDate.getTime()); String str = sf.format(uDate.getTime()); return str; } /* * author: haitao zhang des:获取时间戳 格式:1437938224000 date:2015-07-27 */ public static long GetTimestamp() { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Date uDate = new java.util.Date(); String str = sf.format(uDate.getTime()); Timestamp date = java.sql.Timestamp.valueOf(str); long tmp = date.getTime(); return tmp; } /** * 对比时间的大小 * * @param date1 * 对比的时间1 * @param date2 * 对比的时间2 * @return 1,两个时间相等2,date1时间小于date2,date1时间大于date2 */ public static int DateCompareTo(String date1, String date2) { int i = 0; try { String s1 = date1; String s2 = date2; java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Calendar c1 = java.util.Calendar.getInstance(); java.util.Calendar c2 = java.util.Calendar.getInstance(); c1.setTime(df.parse(s1)); c2.setTime(df.parse(s2)); int result = c1.compareTo(c2); if (result == 0) i = 1; else if (result < 0) // System.out.println("c1小于c2"); i = 2; else // System.out.println("c1大于c2"); i = 3; } catch (java.text.ParseException e) { System.err.println("格式不正确"); } return i; } /** * 增加日期 * * @param format * "yyyy-MM-dd" * @param StrDate * "2016-01-11" * @param year * 0 * @param month * 1 * @param day * 0 * @return */ public static String GetSysDate(Date StrDate) { String reStr=""; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date dt = StrDate; Calendar rightNow = Calendar.getInstance(); rightNow.setTime(dt); rightNow.add(Calendar.MONTH, 1); Date dt1 = rightNow.getTime(); reStr = sdf.format(dt1); System.out.print(reStr); } catch (Exception e) { // TODO: handle exception } return formateDate(reStr); } public static String formateDate(String date) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'CST' yyyy", Locale.US); String da = ""; if (date != null) { try { da = sdf.format(df.parse(date)); } catch (ParseException e) { return ""; } } if (da == null) da = ""; return da; } public static String formateDateYYYYMMd(String date) { SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'CST' yyyy", Locale.US); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String da = ""; if (date != null) { try { da = df.format(sdf.parse(date)); } catch (ParseException e) { return ""; } } if (da == null) da = ""; return da; } /*** * 日期月份减一个月 * * @param datetime * 日期(2014-11) * @return 2014-10 */ public static String dateFormat(String datetime) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); Date date = null; try { date = sdf.parse(datetime); } catch (ParseException e) { e.printStackTrace(); } Calendar cl = Calendar.getInstance(); cl.setTime(date); cl.add(Calendar.MONTH, -1); date = cl.getTime(); return sdf.format(date); } public static String dateFormat(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); return sdf.format(date); } /**** * 传入具体日期 ,返回具体日期减一个月。 * * @param date * 日期(2014-04-20) * @return 2014-03-20 * @throws ParseException */ public static String subMonth(String date) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date dt = sdf.parse(date); Calendar rightNow = Calendar.getInstance(); rightNow.setTime(dt); rightNow.add(Calendar.MONTH, -1); Date dt1 = rightNow.getTime(); String reStr = sdf.format(dt1); return reStr; } /**** * 获取月末最后一天 * * @param sDate * 2014-11-24 * @return 30 */ private static String getMonthMaxDay(String sDate) { SimpleDateFormat sdf_full = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); Date date = null; try { date = sdf_full.parse(sDate + "-01"); } catch (ParseException e) { e.printStackTrace(); } cal.setTime(date); int last = cal.getActualMaximum(Calendar.DATE); return String.valueOf(last); } // 判断是否是月末 public static boolean isMonthEnd(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); if (cal.get(Calendar.DATE) == cal.getActualMaximum(Calendar.DAY_OF_MONTH)) return true; else return false; } /*** * 日期减一天、加一天 * * @param option * 传入类型 pro:日期减一天,next:日期加一天 * @param _date * 2014-11-24 * @return 减一天:2014-11-23或(加一天:2014-11-25) */ public static String checkOption(String option, String _date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cl = Calendar.getInstance(); Date date = null; try { date = (Date) sdf.parse(_date); } catch (ParseException e) { e.printStackTrace(); } cl.setTime(date); if ("pre".equals(option)) { // 时间减一天 cl.add(Calendar.DAY_OF_MONTH, -1); } else if ("next".equals(option)) { // 时间加一天 cl.add(Calendar.DAY_OF_YEAR, 1); } else { // do nothing } date = cl.getTime(); return sdf.format(date); } /*** * 判断日期是否为当前月, 是当前月返回当月最小日期和当月目前最大日期以及传入日期上月的最大日和最小日 * 不是当前月返回传入月份的最大日和最小日以及传入日期上月的最大日和最小日 * * @param date * 日期 例如:2014-11 * @return String[] 开始日期,结束日期,上月开始日期,上月结束日期 * @throws ParseException */ public static String[] getNow_Pre_Date(String date) throws ParseException { String[] str_date = new String[4]; Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); SimpleDateFormat sdf_full = new SimpleDateFormat("yyyy-MM-dd"); String stMonth = sdf.format(now); String stdate = "";// 开始日期 String endate = "";// 结束日期 String preDate_start = "";// 上月开始日期 String preDate_end = "";// 上月结束日期 // 当前月 if (date.equals(stMonth)) { stdate = stMonth + "-01"; // 2014-11-01 endate = sdf_full.format(now);// 2014-11-24 preDate_start = subMonth(stdate);// 2014-10-01 preDate_end = subMonth(endate);// 2014-10-24 } else { // 非当前月 String monthMaxDay = getMonthMaxDay(date); stdate = date + "-01";// 2014-10-01 endate = date + "-" + monthMaxDay;// 2014-10-31 preDate_start = subMonth(stdate);// 2014-09-01 preDate_end = subMonth(endate);// 2014-09-30 } str_date[0] = stdate; str_date[1] = endate; str_date[2] = preDate_start; str_date[3] = preDate_end; return str_date; } /** * 增加日期 * * @param 增加的整数 * @param type * 0,增加一天,1增加月份 * @return data */ public static Date addDay(int n, int type) { try { Calendar cd = Calendar.getInstance(); cd.setTime(DateUtil.getDate()); if (type > 0) { cd.add(Calendar.MONTH, n);// 增加一个月 } else { cd.add(Calendar.DATE, n);// 增加一天 } return cd.getTime(); } catch (Exception e) { return null; } } }
25.890863
98
0.606117
f608cd19b0214419e7bcc2bb3a24ff003002e207
898
package me.chanjar.weixin.mp.api.impl; import com.google.inject.Inject; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.test.ApiTestModule; import me.chanjar.weixin.mp.bean.WxMpShakeInfoResult; import me.chanjar.weixin.mp.bean.WxMpShakeQuery; import org.testng.annotations.Guice; import org.testng.annotations.Test; /** * 测试摇一摇周边相关的接口 * * @author rememberber */ @Test(groups = "userAPI") @Guice(modules = ApiTestModule.class) public class WxMpShakeServiceImplTest { @Inject private WxMpService wxService; public void testGetShakeInfo() throws Exception { WxMpShakeQuery wxMpShakeQuery = new WxMpShakeQuery(); wxMpShakeQuery.setTicket("b87db7df490e5cbe4f598272f77f46be"); wxMpShakeQuery.setNeedPoi(1); WxMpShakeInfoResult wxMpShakeInfoResult = this.wxService.getShakeService().getShakeInfo(wxMpShakeQuery); System.out.println(); } }
28.0625
108
0.783964
27250c96a6366bfcc634e5cfdee0ceb8c6bcd79d
638
package L08TextProcessing; import java.util.Scanner; public class L03Substring { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String textToRemove = scanner.nextLine(); String text = scanner.nextLine(); StringBuilder result = new StringBuilder(); result.append(text); int index = result.indexOf(textToRemove); while (index != -1) { result.replace(index, (index + textToRemove.length()), ""); index = result.indexOf(textToRemove); } System.out.println(result); } }
24.538462
72
0.589342
717f6b2ae02f0138c7aaedff64596581b28c48c9
939
package org.usfirst.frc7913.Main.subsystems; import org.usfirst.frc7913.Main.Robot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.motorcontrol.PWMVictorSPX; public class Conveyor extends Subsystem { private PWMVictorSPX motor; public Conveyor() { motor = new PWMVictorSPX(7); } public void disableMotor() { setSpeed(0); } public void setSpeed(double speed) { speed = speed * -1; motor.set(speed); } public Command start(){ setSpeed(0.75); return null; } public Command stop(){ setSpeed(0); return null; } @Override public void periodic() { setSpeed(Robot.io.xboxController.getRightY() * -1); // System.out.println(Robot.io.xboxController.getRightY());; } @Override protected void initDefaultCommand() { } }
21.837209
67
0.637913
fb5855153ce67e84adba0207851197f19f0804c7
1,710
package com.ruoyi.blog.service; import com.ruoyi.blog.mould.*; import com.ruoyi.blog.mould.pam.BlogArticleSearchParam; import java.util.List; public interface IBlogService { //获取菜单列表 List<BlogMenu> listBlogMenus(BlogMenu blogMenu); //获取菜单树 BlogMenu listBlogMenuTree(BlogMenu blogMenu); //通过栏目获取导航树 BlogMenu listBlogMenuTreeByColumnId(Long columnId); //获取外链列表 List<BlogLink> listBlogLinks(BlogLink blogLink); //获取标签列表 List<BlogTag> listBlogTags(BlogTag blogTag); /** * 获取文章列表 * @param blogArticleSearchParam * @return */ List<BlogArticle> listBlogArticles(BlogArticleSearchParam blogArticleSearchParam); //获取文章列表 List<BlogCat> listBlogCats(BlogCat cat); /** * 获取文章 * @param blogArticle * @return */ BlogArticle getBlogArticle(BlogArticle blogArticle); /** * 获取文章列表 * @param blogArticleSearchParam * @return */ List<BlogArticle> listBlogArticlesByCatId(BlogArticleSearchParam blogArticleSearchParam); /** * 获取文章列表 * @param blogArticleSearchParam * @return */ List<BlogArticle> listBlogArticlesByTagId(BlogArticleSearchParam blogArticleSearchParam); BlogTag getBlogTagByTagId(long tagId); BlogCat getBlogCatByCatId(long catId); List<BlogCat> listHotCats(Long str[]); List<BlogTag> listHotTags(Long str[]); List<Long> listArticleIdsByCatId(long catId); List<Long> listArticleIdsByTagId(long tagId); BlogMenu getBlogMenuByMenuUrl(String columnUrl); BlogTag getBlogTagByTagUrl(String tagUrl); BlogCat getBlogCatByCatUrl(String catUrl); BlogArticle getBlogArticleByArticleUrl(String articleUrl ); }
24.084507
93
0.711696
056e8cdd983bfde59c6b56a88f67b3c2ade50b86
12,576
package de.chrgroth.generictypesystem.validation.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import org.junit.Before; import org.junit.Test; import de.chrgroth.generictypesystem.model.DefaultGenericAttributeType; import de.chrgroth.generictypesystem.model.GenericAttribute; import de.chrgroth.generictypesystem.model.GenericItem; import de.chrgroth.generictypesystem.model.GenericStructure; import de.chrgroth.generictypesystem.model.GenericType; import de.chrgroth.generictypesystem.model.GenericUnit; import de.chrgroth.generictypesystem.model.GenericUnits; import de.chrgroth.generictypesystem.model.GenericValue; import de.chrgroth.generictypesystem.model.UnitValue; import de.chrgroth.generictypesystem.validation.BaseValidationServiceTypeAndItemTest; import de.chrgroth.generictypesystem.validation.ValidationError; public class DefaultValidationServiceItemTest extends BaseValidationServiceTypeAndItemTest { private static final String ATTRIBUTE_NAME = "name"; private UnitsLookupTestHelper unitsLookupTestHelper; @Before public void setup() { unitsLookupTestHelper = new UnitsLookupTestHelper(); service = new DefaultValidationService(unitsLookupTestHelper, null); type = new GenericType(0l, "testType", "testGroup", null, null, null, null); item = new GenericItem(0l, type.getId(), null, null, null); } @Test public void nullItemWithNullType() { type = null; item = null; validateItem(new ValidationError("", DefaultValidationServiceMessageKey.GENERAL_TYPE_NOT_PROVIDED)); } @Test public void nullItem() { item = null; validateItem(new ValidationError("", DefaultValidationServiceMessageKey.GENERAL_ITEM_NOT_PROVIDED)); } @Test public void itemWithoutTypeId() { item.setTypeId(null); validateItem(new ValidationError("", DefaultValidationServiceMessageKey.ITEM_TYPE_MANDATORY)); } @Test public void itemWithMismatchingTypeId() { item.setTypeId(type.getId() + 1); validateItem(new ValidationError("", DefaultValidationServiceMessageKey.ITEM_TYPE_DOES_NOT_MATCH)); } @Test public void invalidType() { type.setName(null); validateItem(new ValidationError("", DefaultValidationServiceMessageKey.ITEM_TYPE_INVALID)); } @Test public void noAttributesNoValues() { validateItem(); } @Test public void unitValueForNonUnitBasedAttribute() { attribute(DefaultGenericAttributeType.DOUBLE, null, true, null); UnitValue value = new UnitValue(); value.setUnitsId(0l); value.setUnitId(0l); value.setValue(new GenericValue<>(Double.class, 1.0d)); value(value); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_UNIT_BASED), new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_UNIT_INVALID)); } @Test public void nonUnitValueForUnitBasedAttribute() { GenericAttribute attribute = attribute(DefaultGenericAttributeType.DOUBLE, null, true, null); GenericUnits units = mockUnits(); attribute.setUnitsId(units.getId()); value(60); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_NOT_UNIT_BASED)); } @Test public void validUnitBasedValue() { GenericAttribute attribute = attribute(DefaultGenericAttributeType.DOUBLE, null, true, null); GenericUnits units = mockUnits(); attribute.setUnitsId(units.getId()); UnitValue value = new UnitValue(); value.setUnitsId(0l); value.setUnitId(1l); value.setValue(new GenericValue<>(Double.class, 1.0d)); value(value); validateItem(); } private GenericUnits mockUnits() { GenericUnits units = new GenericUnits(0l, "mock_units", null); units.getUnits().add(new GenericUnit(0l, "seconds", "s", GenericUnits.FACTOR_BASE)); units.getUnits().add(new GenericUnit(1l, "minutes", "m", 60)); unitsLookupTestHelper.register(units); return units; } @Test public void missingMandatoryDoubleValue() { attribute(DefaultGenericAttributeType.DOUBLE, null, true, null); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MANDATORY)); } @Test public void mandatoryDoubleValue() { attribute(DefaultGenericAttributeType.DOUBLE, null, true, null); value(2.0d); validateItem(); } @Test public void missingMandatoryStringValue() { attribute(DefaultGenericAttributeType.STRING, null, true, null); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MANDATORY)); } @Test public void emptyMandatoryStringValue() { attribute(DefaultGenericAttributeType.STRING, null, true, null); value(" "); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MANDATORY)); } @Test public void mandatoryStringValue() { attribute(DefaultGenericAttributeType.STRING, null, true, null); value("foo"); validateItem(); } @Test public void undefinedAttribute() { value("value"); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_ATTRIBUTE_UNDEFINED)); } @Test public void valueTypeMismatch() { attribute(DefaultGenericAttributeType.STRING, null, true, null); value(2.0d); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_TYPE_INVALID, DefaultGenericAttributeType.STRING.toString(), Double.class.getName())); } @Test public void collectionValueTypeMismatch() { attribute(DefaultGenericAttributeType.LIST, DefaultGenericAttributeType.STRING, false, null); value(new HashSet<>()); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_TYPE_INVALID, DefaultGenericAttributeType.LIST.toString(), HashSet.class.getName())); } @Test public void emptyMandatoryList() { attribute(DefaultGenericAttributeType.LIST, DefaultGenericAttributeType.STRING, true, null); value(new ArrayList<>()); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MANDATORY)); } @Test public void listElementTypeMismatch() { attribute(DefaultGenericAttributeType.LIST, DefaultGenericAttributeType.STRING, false, null); value(Arrays.asList(2.0d)); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_LIST_VALUE_TYPE_INVALID, DefaultGenericAttributeType.STRING.toString())); } @Test public void stringUndercut() { GenericAttribute a = attribute(DefaultGenericAttributeType.STRING, null, false, null); a.setMin(10.0d); value("012345"); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MIN_UNDERCUT, new Double(10.0d))); } @Test public void stringExceeded() { GenericAttribute a = attribute(DefaultGenericAttributeType.STRING, null, false, null); a.setMax(10.0d); value("01234567890"); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MAX_EXCEEDED, 10.0d)); } @Test public void stringPatternMismatch() { GenericAttribute a = attribute(DefaultGenericAttributeType.STRING, null, false, null); a.setPattern("\\d+"); value("12345abc"); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_PATTERN_VIOLATED, "\\d+")); } @Test public void enumValid() { GenericAttribute a = attribute(DefaultGenericAttributeType.ENUM, null, false, null); HashSet<String> enumValues = new HashSet<>(); enumValues.add("foo"); a.setEnumValues(enumValues); value("foo"); validateItem(); } @Test public void enumInvalid() { GenericAttribute a = attribute(DefaultGenericAttributeType.ENUM, null, false, null); HashSet<String> enumValues = new HashSet<>(); enumValues.add("foo"); a.setEnumValues(enumValues); value("bar"); validateItem(new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_ENUM_INVALID)); } @Test public void longIntegerMinUndercut() { assertNumericValue(DefaultGenericAttributeType.LONG, 2.0d, null, 1, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MIN_UNDERCUT, 2.0d)); } @Test public void longIntegerMaxExceeded() { assertNumericValue(DefaultGenericAttributeType.LONG, null, 2.0d, 3, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MAX_EXCEEDED, 2.0d)); } @Test public void longLongMinUndercut() { assertNumericValue(DefaultGenericAttributeType.LONG, 2.0d, null, 1l, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MIN_UNDERCUT, 2.0d)); } @Test public void longLongMaxExceeded() { assertNumericValue(DefaultGenericAttributeType.LONG, null, 2.0d, 3l, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MAX_EXCEEDED, 2.0d)); } @Test public void doubleIntegerMinUndercut() { assertNumericValue(DefaultGenericAttributeType.DOUBLE, 2.0d, null, 1, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MIN_UNDERCUT, 2.0d)); } @Test public void doubleIntegerMaxExceeded() { assertNumericValue(DefaultGenericAttributeType.DOUBLE, null, 2.0d, 3, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MAX_EXCEEDED, 2.0d)); } @Test public void doubleLongMinUndercut() { assertNumericValue(DefaultGenericAttributeType.DOUBLE, 2.0d, null, 1l, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MIN_UNDERCUT, 2.0d)); } @Test public void doubleLongMaxExceeded() { assertNumericValue(DefaultGenericAttributeType.DOUBLE, null, 2.0d, 3l, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MAX_EXCEEDED, 2.0d)); } @Test public void doubleFloatMinUndercut() { assertNumericValue(DefaultGenericAttributeType.DOUBLE, 2.0d, null, 1.0f, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MIN_UNDERCUT, 2.0d)); } @Test public void doubleFloatMaxExceeded() { assertNumericValue(DefaultGenericAttributeType.DOUBLE, null, 2.0d, 3.0f, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MAX_EXCEEDED, 2.0d)); } @Test public void doubleDoubleMinUndercut() { assertNumericValue(DefaultGenericAttributeType.DOUBLE, 2.0d, null, 1.0d, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MIN_UNDERCUT, 2.0d)); } @Test public void doubleDoubleMaxExceeded() { assertNumericValue(DefaultGenericAttributeType.DOUBLE, null, 2.0d, 3.0d, new ValidationError(ATTRIBUTE_NAME, DefaultValidationServiceMessageKey.ITEM_VALUE_MAX_EXCEEDED, 2.0d)); } private void assertNumericValue(DefaultGenericAttributeType attributeType, Double min, Double max, Object value, ValidationError... errors) { GenericAttribute a = attribute(attributeType, null, false, null); a.setMin(min); a.setMax(max); value(value); validateItem(errors); } private <T, K, V> GenericAttribute attribute(DefaultGenericAttributeType type, DefaultGenericAttributeType valueType, boolean mandatory, GenericStructure structure) { GenericAttribute a = new GenericAttribute(0l, ATTRIBUTE_NAME, type, valueType, false, mandatory, structure, null, null, null, null, null, null, null, null, null); this.type.getAttributes().add(a); return a; } private void value(Object value) { item.set(ATTRIBUTE_NAME, value); } }
40.178914
180
0.720022
638819f8f84097b351995634cce00b7d9804f5cd
219
package gerrymandering.service; /** * Created by yisuo on 11/9/17. */ public interface EmailService { public void sendInvite(String email); public void sendNotification(String email, String notification); }
19.909091
68
0.739726
4dbbc918c18b0308d3215820ffc9b4692707a0c1
2,627
package br.com.musicas.opus06.morrisonhotel; import org.jfugue.Pattern; public class PianoMaoDireita extends Estrutura{ @Override public void inicio() { partitura.add(new Pattern("V2 I[PIANO] X[Volume]=12000")); partitura.add(new Pattern("Rq Rq Rq Rq"), 1); } @Override public void estrofe() { partitura.add(new Pattern("G6i A6i B6i D6i E6i G6i A6i B6i"), 1); partitura.add(new Pattern("G6i B6i A6i Ri G6i B6i A6i Ri"), 1); partitura.add(new Pattern("A6i B6i G6i D6i E6i G6i B6i A6i"), 1); partitura.add(new Pattern("G6i D6i E6i Ri G6i D6i E6i Ri"), 1); partitura.add(new Pattern("C6i D6i E6i G6i A6i C6i D6i E6i"), 1); partitura.add(new Pattern("C6i A6i G6i E6i D6i C6i E6i D6i"), 1); partitura.add(new Pattern("D6i E6i F#6i A6i B6i D6i E6i F#6i"), 1); partitura.add(new Pattern("C6i D6i G6i E6i G6i Ri D6i E6i"), 1); partitura.add(new Pattern("E6i G6i B6i A6i D6i E6i A6i B6i"), 1); partitura.add(new Pattern("G6i A6i B6i D6i E6i D6i B6i G6i"), 1); } @Override public void refrao() { partitura.add(new Pattern("A6i Ri E6i D6i C6i A6i G6i E6i"), 1); partitura.add(new Pattern("B6i A6i F#6i E6i D6i B6i A6i F#6i"), 1); partitura.add(new Pattern("E6i Ri B6i A6i G6i E6i D6i B6i"), 1); partitura.add(new Pattern("E6i D6i B6i A6i G6i E6i D6i B6i"), 1); } @Override public void solo() { partitura.add(new Pattern("G7i A7i B7i D7i E7i G7i A7i B7i"), 1); partitura.add(new Pattern("D7i E7i D7i B7i A7i G7i E7i D7i"), 1); partitura.add(new Pattern("G7i A7i B7i Ri G7i A7i B7i E7i"), 1); partitura.add(new Pattern("D7i E7i D7i E7i Ri G7i A7i G7i"), 1); partitura.add(new Pattern("A7i B7i E7i G7i A7i B7i D7i E7i"), 1); partitura.add(new Pattern("D7i B7i A7i G7i E7i D7i A7i G7i"), 1); partitura.add(new Pattern("E7i D7i F#7i A7i B7q G7i F#7i"), 1); partitura.add(new Pattern("A7i G7i E7i Ri A7i B7i D7i E7i"), 1); partitura.add(new Pattern("D7i B7i A7i G7i E7i D7i A7i G7i"), 1); partitura.add(new Pattern("E7i A7i B7i D7i E7i G7i A7i G7i"), 1); } @Override public void intro() { partitura.add(new Pattern("C7i E7i G7i Ri C7i E7i G7i A7i"), 1); partitura.add(new Pattern("D7i E7i F#7i A7i B7i F#7i A7i D7i"), 1); partitura.add(new Pattern("G7i A7i B7i Ri E7i C7i D7i A7i"), 1); partitura.add(new Pattern("E7i A7i B7i D7i E7i G7i A7i G7i"), 1); } @Override public void fim() { partitura.add(new Pattern("C7i E7i G7i D7i E7i G7i A7i C7i"), 1); partitura.add(new Pattern("D7i E7i F#7i A7i B7i F#7i A7i D7i"), 1); partitura.add(new Pattern("G5majw"), 1); } }
28.868132
69
0.661591
001645236f56a2fe3e415d9b06b7622d02166f38
211
package com.cardshifter.server.model; public class UserNameAlreadyInUseException extends Exception { UserNameAlreadyInUseException() { super("User name already in use by another client"); } }
21.1
62
0.744076
542f95e948dce87abe0b1ba8f90950f721e6b092
377
package com.Ironhack.AccountService.repository; import com.Ironhack.AccountService.dao.Account; import com.Ironhack.AccountService.enums.Industry; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface AccountRepository extends JpaRepository<Account, Long> { }
29
73
0.848806
6a07ef771e4e27d840744d5ba29b1ff81d7621d1
250
package net.optionfactory.spring.email; import java.util.List; public class EmailSenderAndCopyAddresses { public List<String> ccAddresses; public List<String> bccAddresses; public String sender; public String senderDescription; }
19.230769
42
0.768