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
20bb660e0c32e1b8020f1356964323fa3ff960ee
23,377
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.api.explorer.client; import com.google.api.explorer.client.FullViewPresenter.NavigationItem; import com.google.api.explorer.client.analytics.AnalyticsManager; import com.google.api.explorer.client.auth.AuthView; import com.google.api.explorer.client.base.ApiDirectory.ServiceDefinition; import com.google.api.explorer.client.base.ApiMethod; import com.google.api.explorer.client.base.ApiRequest; import com.google.api.explorer.client.base.ApiResponse; import com.google.api.explorer.client.base.ApiService; import com.google.api.explorer.client.base.NameHelper; import com.google.api.explorer.client.context.ExplorerContext; import com.google.api.explorer.client.context.ListServiceContext.TagProcessor; import com.google.api.explorer.client.embedded.EmbeddedParameterFormPresenter.RequestFinishedCallback; import com.google.api.explorer.client.embedded.EmbeddedView; import com.google.api.explorer.client.history.EmbeddedHistoryItemView; import com.google.api.explorer.client.history.HistoryItem; import com.google.api.explorer.client.history.JsonPrettifier; import com.google.api.explorer.client.navigation.EntryAggregatorView; import com.google.api.explorer.client.navigation.HistoryEntry; import com.google.api.explorer.client.navigation.MethodEntry; import com.google.api.explorer.client.navigation.SectionedAggregator; import com.google.api.explorer.client.navigation.ServiceEntry; import com.google.api.explorer.client.navigation.ServiceEntry.DescriptionTag; import com.google.api.explorer.client.routing.TitleSupplier.Title; import com.google.api.explorer.client.routing.URLManipulator; import com.google.api.explorer.client.routing.UrlBuilder.RootNavigationItem; import com.google.api.explorer.client.routing.handler.HistoryManager.HistoryManagerDelegate; import com.google.api.explorer.client.search.SearchManager.SearchReadyCallback; import com.google.api.explorer.client.search.SearchResult; import com.google.api.explorer.client.search.SearchResult.MethodBundle; import com.google.api.explorer.client.widgets.PlaceholderTextBox; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.resources.client.CssResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DockLayoutPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.InlineHyperlink; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.MenuBar; import com.google.gwt.user.client.ui.MenuItem; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.PushButton; import com.google.gwt.user.client.ui.SuggestBox; import com.google.gwt.user.client.ui.SuggestBox.DefaultSuggestionDisplay; import com.google.gwt.user.client.ui.SuggestBox.SuggestionDisplay; import com.google.gwt.user.client.ui.SuggestOracle; import com.google.gwt.user.client.ui.SuggestOracle.Suggestion; import com.google.gwt.user.client.ui.Widget; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * View of the whole app. * * @author jasonhall@google.com (Jason Hall) */ public class FullView extends Composite implements FullViewPresenter.Display, HistoryManagerDelegate, SearchReadyCallback { private static FullViewUiBinder uiBinder = GWT.create(FullViewUiBinder.class); private static final String REPORT_ERROR_URL = "http://code.google.com/p/google-apis-explorer/" + "issues/entry?template=Defect%20report%20from%20user"; private static final String EXPLORER_HELP_URL = "http://code.google.com/apis/explorer-help"; private static final String EXPLORER_FORUM_URL = "http://code.google.com/apis/explorer-help/forum.html"; private static final String NEW_TAB_TARGET = "_blank"; private static final String SETTINGS_MENU_CSS_RULE = "settingsMenu"; private static final boolean HIDE_AUTH = false; interface FullViewUiBinder extends UiBinder<Widget, FullView> { } interface FullViewStyle extends CssResource { String selectedNavigation(); String searchPlaceholderText(); String methodSubtitle(); } @UiField FullViewStyle style; @UiField DockLayoutPanel dockLayoutPanel; @UiField Image logo; @UiField PushButton backButton; @UiField Widget searchLoadingIndicator; @UiField(provided = true) SuggestBox searchBox; @UiField Panel searchErrorPanel; @UiField SectionedAggregator searchResults; @UiField EntryAggregatorView drillDownNav; @UiField Panel detailHeader; @UiField Panel detailTitleContainer; @UiField Panel authViewPlaceholder; @UiField Panel docsContainer; @UiField Panel detailPane; @UiField Panel preferredServicesMenuItem; @UiField Panel requestHistoryMenuItem; @UiField Panel allServicesMenuItem; @UiField MenuBar settingsMenu; @UiField MenuItem helpItem; @UiField MenuItem forumItem; @UiField MenuItem bugReportItem; private final FullViewPresenter presenter; private final AuthManager authManager; private final AnalyticsManager analytics; public FullView(URLManipulator urlManipulator, AuthManager authManager, AnalyticsManager analytics, SuggestOracle searchKeywords) { this.analytics = analytics; this.presenter = new FullViewPresenter(urlManipulator, this); this.authManager = authManager; PlaceholderTextBox searchBackingTextBox = new PlaceholderTextBox("Search for services, methods, and recent requests..."); this.searchBox = new SuggestBox(searchKeywords, searchBackingTextBox); searchBox.setAutoSelectEnabled(false); initWidget(uiBinder.createAndBindUi(this)); setMenuActions(); // Add a fixed css class name that I can use to be able to style the menu. settingsMenu.setStyleName(SETTINGS_MENU_CSS_RULE + " " + settingsMenu.getStyleName()); // Set the style of the search box. searchBackingTextBox.setPlaceholderTextStyleName(style.searchPlaceholderText()); } /** * Assign the actions to the settings menu items. */ private void setMenuActions() { bugReportItem.setCommand(getOpenUrlAction(REPORT_ERROR_URL)); helpItem.setCommand(getOpenUrlAction(EXPLORER_HELP_URL)); forumItem.setCommand(getOpenUrlAction(EXPLORER_FORUM_URL)); } /** * Create a command that can be bound to a menu item that will open a url in a new tab. */ private Command getOpenUrlAction(final String url) { return new Command() { @Override public void execute() { Window.open(url, NEW_TAB_TARGET, ""); } }; } @UiHandler("preferredServicesMenuItem") void clickPreferred(ClickEvent event) { presenter.clickNavigationItem(NavigationItem.PREFERRED_SERVICES); } @UiHandler("requestHistoryMenuItem") void clickHistory(ClickEvent event) { presenter.clickNavigationItem(NavigationItem.REQUEST_HISTORY); } @UiHandler("allServicesMenuItem") void clickAllVersions(ClickEvent event) { presenter.clickNavigationItem(NavigationItem.ALL_VERSIONS); } @UiHandler("logo") void clickLogo(ClickEvent event) { // Go back to the "home" state of the app when the logo is clicked. presenter.handleClickLogo(); } @UiHandler("backButton") void clickBack(ClickEvent event) { presenter.handleClickBack(); } @UiHandler("searchButton") void clickSearch(ClickEvent event) { presenter.handleSearch(searchBox.getText()); } @UiHandler("searchBox") void searchBoxEnter(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { SuggestionDisplay suggestionDisplay = searchBox.getSuggestionDisplay(); // This should always be true unless GWT changes the type of the suggestion generated by the // SuggestBox. It is too complicated and nasty to switch out the SuggestBox suggestion display // factory, so we're left with this type safety check and broken functionality if GWT changes. Preconditions.checkState(suggestionDisplay instanceof DefaultSuggestionDisplay); // At this point this should always be true. if (suggestionDisplay instanceof DefaultSuggestionDisplay) { DefaultSuggestionDisplay suggestions = (DefaultSuggestionDisplay) suggestionDisplay; if (!suggestions.isSuggestionListShowing()) { presenter.handleSearch(searchBox.getValue()); } } } } @UiHandler("searchBox") void suggestionSelected(SelectionEvent<Suggestion> event) { presenter.handleSearch(event.getSelectedItem().getReplacementString()); } @Override public void setContext(ExplorerContext context) { presenter.setContext(context); // Fill in the entry list widget, only the collections that have entries will be shown drillDownNav.setVisible(context.isEntryListVisible()); drillDownNav.clear(); if (context.isEntryListVisible()) { populateHistoryItems("", context.getHistoryItems(), drillDownNav); populateServiceEntries( sortServices(context.getServicesList()), drillDownNav, context.getServiceTagProcessor()); populateServiceMethods(context.getService(), context.getMethods(), drillDownNav); } // Fill in the detail pane. detailPane.setVisible(context.isHistoryItemVisible() || context.isMethodFormVisible()); detailPane.clear(); if (context.isHistoryItemVisible()) { HistoryItem item = Iterables.getOnlyElement(context.getHistoryItems()); EmbeddedHistoryItemView view = generateHistoryItemView(item); detailPane.add(view); } else if (context.isMethodFormVisible()) { ApiMethod method = context.getMethod(); // Wrap the callback given by the context so that we may also be notified when a request is // finished. Pass through events to the original callback. CallbackWrapper cbWrapper = new CallbackWrapper(); cbWrapper.delegate = context.getRequestFinishedCallback(); cbWrapper.methodName = method.getId(); // Create the view of the request editor and the single history item. EmbeddedView view = new EmbeddedView(authManager, context.getService(), method, context.getMethodParameters(), cbWrapper, HIDE_AUTH, analytics); cbWrapper.localView = view; // If this context came bundled with a history item, that means the navigation references a // previous executed request, and we should show the result. List<HistoryItem> historyItems = context.getHistoryItems(); if (!historyItems.isEmpty()) { view.showHistoryItem(generateHistoryItemView(Iterables.getLast(historyItems))); } detailPane.add(view); } // Show the search results. searchResults.setVisible(context.isSearchResultsVisible()); searchResults.clear(); searchErrorPanel.setVisible(false); if (context.isSearchResultsVisible()) { populateSearchResults(context.getSearchResults(), context.getServiceTagProcessor()); } // Show the auth panel. authViewPlaceholder.setVisible(context.isAuthVisible()); authViewPlaceholder.clear(); if (context.isAuthVisible()) { showAuth(context.getService(), context.getMethod()); } // Show the documentation link. docsContainer.setVisible(context.isDocsLinkVisible()); docsContainer.clear(); if (context.isDocsLinkVisible()) { showDocumentationLink("the " + context.getService().displayTitle(), context.getService().getDocumentationLink()); } // Show the title. boolean showContentTitle = context.getContentTitles() != null; if (showContentTitle) { generateBreadcrumbs(detailTitleContainer, context.getContentTitles()); } // Show the detail header. detailHeader.setVisible(showContentTitle || context.isAuthVisible()); // Show the back button. backButton.setVisible(context.getParentUrl() != null); // Highlight the navigation item which was the root of our navigation. highlightNavigationItem(context.getRootNavigationItem()); } /** * Generate a view of the provided history item. */ private EmbeddedHistoryItemView generateHistoryItemView(HistoryItem item) { EmbeddedHistoryItemView view = new EmbeddedHistoryItemView(item.getRequest()); view.complete(item.getResponse(), item.getEndTime() - item.getStartTime(), JsonPrettifier.LOCAL_LINK_FACTORY); return view; } /** * Generate breadcrumbs into the specified container using the format link > link > text where the * last breadcrumb is always plain text. */ private void generateBreadcrumbs(Panel container, List<Title> titles) { container.clear(); // For all of the titles previous to the last, add a link and a separator. for (Title notLast : titles.subList(0, titles.size() - 1)) { container.add(new InlineHyperlink(notLast.getTitle(), notLast.getFragment())); container.add(new InlineLabel(" > ")); } // Append only the text for the last title. Title lastTitle = Iterables.getLast(titles); container.add(new InlineLabel(lastTitle.getTitle())); if (lastTitle.getSubtitle() != null) { Label subtitle = new InlineLabel(" - " + lastTitle.getSubtitle()); subtitle.addStyleName(style.methodSubtitle()); container.add(subtitle); } } private void showAuth(ApiService service, ApiMethod method) { AuthView auth = new AuthView(authManager, service, analytics); if (method != null) { auth.getPresenter().setStateForMethod(method); } authViewPlaceholder.add(auth); } private void showDocumentationLink(String componentName, String href) { docsContainer.add( new InlineLabel("Learn more about using " + componentName + " by reading the ")); docsContainer.add(new Anchor("documentation", href, NEW_TAB_TARGET)); docsContainer.add(new InlineLabel(".")); } /** * Display the specified service entries in the container provided, while applying the tags * generated by the tag processor. */ private void populateServiceEntries(Iterable<ServiceDefinition> services, EntryAggregatorView toPopulate, Set<TagProcessor> tagProcessors) { for (final ServiceDefinition service : services) { String iconUrl = service.getIcons().getIcon16Url(); String displayName = NameHelper.generateDisplayTitle(service.getTitle(), service.getName()); Set<DescriptionTag> tags = Sets.newHashSet(); for (TagProcessor processor : tagProcessors) { tags.addAll(processor.process(service)); } HasClickHandlers rowHandle = toPopulate.addEntry(new ServiceEntry( iconUrl, displayName, service.getVersion(), service.getDescription(), tags)); rowHandle.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.handleClickService(service); } }); } } /** * Display the spcified history items in the aggregator specified. * * @param prefix Prefix that should be prepended to the history item URL when an item is clicked, * changes based on whether this was a search result or the history item list. * @param historyItems Items which to render and display in the aggregator, * @param aggregator Aggregator that will display rendered history items. */ private void populateHistoryItems( final String prefix, Iterable<HistoryItem> historyItems, EntryAggregatorView aggregator) { for (final HistoryItem item : historyItems) { ApiRequest request = item.getRequest(); HasClickHandlers rowHandler = aggregator.addEntry(new HistoryEntry(request.getMethod() .getId(), request.getHttpMethod().toString() + " " + request.getRequestPath(), item .getEndTime())); rowHandler.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.handleClickHistoryItem(prefix, item); } }); } } /** * Display all of the methods for the specified service in the aggregator provided. */ private void populateServiceMethods( ApiService service, Iterable<ApiMethod> methods, EntryAggregatorView view) { for (final ApiMethod method : methods) { populateMethodEntry(method, null, "", view); } } /** * Add an aggregator line for the particular method specified. When clicked, append the prefix * specified and then the method identifier to the current URL. */ private void populateMethodEntry(final ApiMethod method, @Nullable String serviceTitle, final String prefix, EntryAggregatorView aggregator) { HasClickHandlers rowHandler = aggregator.addEntry( new MethodEntry(method.getId(), serviceTitle, method.getDescription())); rowHandler.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent arg0) { presenter.handleClickMethod(prefix, method); } }); } /** * Take the list of search results and split them into appropriate aggregators hidden under * disclosure panels. */ private void populateSearchResults( Iterable<SearchResult> results, Set<TagProcessor> serviceTagProcessors) { List<MethodBundle> methodResults = Lists.newArrayList(); List<ServiceDefinition> serviceResults = Lists.newArrayList(); List<HistoryItem> historyResults = Lists.newArrayList(); for (SearchResult result : results) { switch(result.getKind()) { case HISTORY_ITEM: historyResults.add(result.getHistoryItem()); break; case METHOD: methodResults.add(result.getMethodBundle()); break; case SERVICE: serviceResults.add(result.getService()); break; default: throw new RuntimeException("Unknown search result type: " + result.toString()); } } if (!serviceResults.isEmpty()) { EntryAggregatorView serviceAggregator = new EntryAggregatorView(); populateServiceEntries(serviceResults, serviceAggregator, serviceTagProcessors); searchResults.addSection("Services", serviceAggregator); } if (!methodResults.isEmpty()) { EntryAggregatorView methodAggregator = new EntryAggregatorView(); for (MethodBundle bundle : methodResults) { String prefix = "m/" + bundle.getService().getName() + "/" + bundle.getService().getVersion() + "/"; String serviceTitle = bundle.getService().displayTitle() + " " + bundle.getService().getVersion(); populateMethodEntry(bundle.getMethod(), serviceTitle, prefix, methodAggregator); } searchResults.addSection("Methods", methodAggregator); } if (!historyResults.isEmpty()) { EntryAggregatorView historyAggregator = new EntryAggregatorView(); populateHistoryItems("h/", historyResults, historyAggregator); searchResults.addSection("History", historyAggregator); } if (serviceResults.isEmpty() && methodResults.isEmpty() && historyResults.isEmpty()) { // There are no results, show the message searchResults.setVisible(false); searchErrorPanel.setVisible(true); } } /** * Highlight the navigation item for the root navigation item specified. */ private void highlightNavigationItem(RootNavigationItem navItem) { preferredServicesMenuItem.removeStyleName(style.selectedNavigation()); requestHistoryMenuItem.removeStyleName(style.selectedNavigation()); allServicesMenuItem.removeStyleName(style.selectedNavigation()); switch(navItem) { case ALL_VERSIONS: allServicesMenuItem.addStyleName(style.selectedNavigation()); break; case PREFERRED_SERVICES: preferredServicesMenuItem.addStyleName(style.selectedNavigation()); break; case REQUEST_HISTORY: requestHistoryMenuItem.addStyleName(style.selectedNavigation()); break; } } @Override public void hideSearchLoadingIndicator() { searchLoadingIndicator.setVisible(false); } @Override public void searchReady() { // Delegate to the presenter presenter.searchReady(); } private List<ServiceDefinition> sortServices(Set<ServiceDefinition> services) { List<ServiceDefinition> serviceList = Lists.newArrayList(services); Collections.sort(serviceList, new Comparator<ServiceDefinition>() { @Override public int compare(ServiceDefinition s1, ServiceDefinition s2) { String s1Title = NameHelper.generateDisplayTitle(s1.getTitle(), s1.getName()); String s2Title = NameHelper.generateDisplayTitle(s2.getTitle(), s2.getName()); return s1Title.toLowerCase().compareTo(s2Title.toLowerCase()); } }); return Collections.unmodifiableList(serviceList); } /** * Wrapper class that is used to siphon off request complete events, while still passing the * original events through to the wrapped delegate class. */ private static class CallbackWrapper implements RequestFinishedCallback { public RequestFinishedCallback delegate; public EmbeddedView localView; public String methodName; private Map<ApiRequest, EmbeddedHistoryItemView> incompleteRequests = Maps.newHashMap(); @Override public void finished(ApiRequest request, ApiResponse response, long startTime, long endTime) { EmbeddedHistoryItemView toComplete = incompleteRequests.get(request); toComplete.complete(response, endTime - startTime, JsonPrettifier.LOCAL_LINK_FACTORY); incompleteRequests.remove(request); delegate.finished(request, response, startTime, endTime); } @Override public void starting(ApiRequest request) { EmbeddedHistoryItemView incomplete = new EmbeddedHistoryItemView(request); incompleteRequests.put(request, incomplete); localView.showHistoryItem(incomplete); delegate.starting(request); } } }
37.583601
102
0.73829
29cac0b08acf971b58805ebf0158f2bbd02fc798
63,384
/* * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.nio.ch; import java.io.FileDescriptor; import java.io.IOException; import java.net.DatagramSocket; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.PortUnreachableException; import java.net.ProtocolFamily; import java.net.SocketAddress; import java.net.SocketOption; import java.net.StandardProtocolFamily; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.channels.AlreadyBoundException; import java.nio.channels.AlreadyConnectedException; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.ClosedChannelException; import java.nio.channels.DatagramChannel; import java.nio.channels.MembershipKey; import java.nio.channels.NotYetConnectedException; import java.nio.channels.SelectionKey; import java.nio.channels.spi.SelectorProvider; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; import sun.net.ResourceManager; import sun.net.ext.ExtendedSocketOptions; import static sun.net.ext.ExtendedSocketOptions.SOCK_DGRAM; /** * An implementation of DatagramChannels. */ // UDP-Socket通道的本地实现 class DatagramChannelImpl extends DatagramChannel implements SelChImpl { /** State (does not necessarily increase monotonically) */ // Socket状态参数 private static final int ST_UNCONNECTED = 0; // 未连接 private static final int ST_CONNECTED = 1; // 已连接 private static final int ST_CLOSING = 2; // 正在断开连接(关闭) private static final int ST_KILLPENDING = 3; // 正在销毁 private static final int ST_KILLED = 4; // 已销毁 // DatagramChannel状态 private int state; /** Our socket adaptor, if any */ // 由当前DatagramChannel通道适配而成的DatagramChannel private DatagramSocket socket; private final FileDescriptor fd; // UDP-Socket在Java层的文件描述符 private final int fdVal; // UDP-Socket在本地(native层)的文件描述符 /** The protocol family of the socket */ // 当前UDP-Socket使用的IP协议 private final ProtocolFamily family; /** Binding and remote address (when connected) */ private InetSocketAddress localAddress; // UDP-Socket绑定的本地地址 private InetSocketAddress remoteAddress; // UDP-Socket连接的远程地址 // 由receive0()方法设置,记录接收到的数据的发送端地址 private SocketAddress sender; /** Used to make native read and write calls */ private static NativeDispatcher nd = new DatagramDispatcher(); // 完成Socket读写的工具类 /** IDs of native threads doing reads and writes, for signalling */ private long readerThread; // 当前通道开始读操作时所在的native线程号 private long writerThread; // 当前通道开始写操作时所在的native线程号 /** Lock held by current reading or connecting thread */ private final ReentrantLock readLock = new ReentrantLock(); /** Lock held by current writing or connecting thread */ private final ReentrantLock writeLock = new ReentrantLock(); /** * Lock held by any thread that modifies the state fields declared below * DO NOT invoke a blocking I/O operation while holding this lock! */ private final Object stateLock = new Object(); /** Multicast support */ // 组播Socket注册表,记录了当前组播Socket在其所有组播小组上的注册信息 private MembershipRegistry registry; /** set true/false when socket is already bound and SO_REUSEADDR is emulated */ private boolean isReuseAddress; /** set true when socket is bound and SO_REUSEADDRESS is emulated */ private boolean reuseAddressEmulated; /** Cached InetAddress and port for unconnected DatagramChannels used by receive0 */ private InetAddress cachedSenderInetAddress; private int cachedSenderPort; static { IOUtil.load(); initIDs(); } /*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */ // 构造DatagramSocket通道,内部初始化了该Socket的文件描述符 public DatagramChannelImpl(SelectorProvider provider) throws IOException { super(provider); ResourceManager.beforeUdpCreate(); try { // 获取当前UDP-Socket使用的IP协议 this.family = Net.isIPv6Available() ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET; // 创建UDP-Socket,并返回其在Java层的文件描述符 this.fd = Net.socket(family, false); // 获取Java层的文件描述符fd在本地(native层)的引用值 this.fdVal = IOUtil.fdVal(fd); } catch(IOException ioe) { ResourceManager.afterUdpClose(); throw ioe; } } // 构造DatagramSocket通道,内部初始化了该Socket的文件描述符,其支持的协议族由参数family指定 public DatagramChannelImpl(SelectorProvider provider, ProtocolFamily family) throws IOException { super(provider); Objects.requireNonNull(family, "'family' is null"); if((family != StandardProtocolFamily.INET) && (family != StandardProtocolFamily.INET6)) { throw new UnsupportedOperationException("Protocol family not supported"); } if(family == StandardProtocolFamily.INET6) { if(!Net.isIPv6Available()) { throw new UnsupportedOperationException("IPv6 not available"); } } ResourceManager.beforeUdpCreate(); try { // 记录当前UDP-Socket使用的IP协议 this.family = family; // 创建UDP-Socket,并返回其在Java层的文件描述符 this.fd = Net.socket(family, false); // 获取Java层的文件描述符fd在本地(native层)的引用值 this.fdVal = IOUtil.fdVal(fd); } catch(IOException ioe) { ResourceManager.afterUdpClose(); throw ioe; } } public DatagramChannelImpl(SelectorProvider provider, FileDescriptor fd) throws IOException { super(provider); // increment UDP count to match decrement when closing ResourceManager.beforeUdpCreate(); // 获取当前UDP-Socket使用的IP协议 this.family = Net.isIPv6Available() ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET; // 记录UDP-Socket在Java层的文件描述符 this.fd = fd; // 获取Java层的文件描述符fd在本地(native层)的引用值 this.fdVal = IOUtil.fdVal(fd); synchronized(stateLock) { this.localAddress = Net.localAddress(fd); } } /*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 适配 ████████████████████████████████████████████████████████████████████████████████┓ */ // 返回由当前UDP-Socket通道适配而成的UDP-Socket @Override public DatagramSocket socket() { synchronized(stateLock) { if(socket == null) { socket = DatagramSocketAdaptor.create(this); } return socket; } } /*▲ 适配 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ socket操作 ████████████████████████████████████████████████████████████████████████████████┓ */ /* * 对UDP-Socket执行【bind】操作。 * * bindpoint: 待绑定的地址(ip+port);如果为null,则绑定到本地环回IP和随机端口 */ @Override public DatagramChannel bind(SocketAddress bindpoint) throws IOException { readLock.lock(); try { writeLock.lock(); try { synchronized(stateLock) { // 确保通道已经开启,否则抛异常 ensureOpen(); // 如果已经绑定过了,则抛出异常 if(localAddress != null) { throw new AlreadyBoundException(); } // 执行绑定操作的内部实现 bindInternal(bindpoint); } } finally { writeLock.unlock(); } } finally { readLock.unlock(); } return this; } /* * 对UDP-Socket执行【connect】操作。 * * 将UDP-Socket连接到远程地址,之后只能向该远程地址发送数据,或从该远程地址接收数据。 * * 注:这与TCP-Socket中的绑定意义完全不同,不会经过握手验证 */ @Override public DatagramChannel connect(SocketAddress sa) throws IOException { InetSocketAddress isa = Net.checkAddress(sa, family); SecurityManager sm = System.getSecurityManager(); if(sm != null) { InetAddress ia = isa.getAddress(); if(ia.isMulticastAddress()) { sm.checkMulticast(ia); } else { sm.checkConnect(ia.getHostAddress(), isa.getPort()); sm.checkAccept(ia.getHostAddress(), isa.getPort()); } } readLock.lock(); try { writeLock.lock(); try { synchronized(stateLock) { // 确保通道已经开启,否则抛异常 ensureOpen(); // 如果已经连接,则抛异常 if(state == ST_CONNECTED) { throw new AlreadyConnectedException(); } // 客户端Socket向指定地址处的指定协议族的远端Socket发起连接(如果采用阻塞模式,会一直等待,直到成功或出现异常) int n = Net.connect(family, fd, isa.getAddress(), isa.getPort()); if(n<=0) { throw new Error(); // Can't happen } // 记录连接到的远程地址 remoteAddress = isa; // 标记已连接 state = ST_CONNECTED; // 刷新(记录)本地地址 localAddress = Net.localAddress(fd); // flush any packets already received. boolean blocking = isBlocking(); // 如果通道是阻塞的,则将其临时修改为非阻塞 if(blocking) { IOUtil.configureBlocking(fd, false); } try { /* * 接收远端的UDP数据包,相当于一个测试连接的过程. * 由于已经设置成了非阻塞模式,所以没有可读数据时立即返回null,退出循环。 */ ByteBuffer buf = ByteBuffer.allocate(100); while(receive(buf) != null) { buf.clear(); } } finally { // 恢复通道为之前的阻塞模式 if(blocking) { IOUtil.configureBlocking(fd, true); } } } } finally { writeLock.unlock(); } } finally { readLock.unlock(); } return this; } /* * 对UDP-Socket执行【disconnect】操作,即断开连接。 */ @Override public DatagramChannel disconnect() throws IOException { readLock.lock(); try { writeLock.lock(); try { synchronized(stateLock) { // 只有通道未关闭,且处于连接状态时,才有必要去断开连接 if(!isOpen() || (state != ST_CONNECTED)) { return this; } // disconnect socket boolean isIPv6 = (family == StandardProtocolFamily.INET6); // 断开连接的内部实现 disconnect0(fd, isIPv6); // 清空远程地址 remoteAddress = null; // 标记UDP-Socket为未连接状态 state = ST_UNCONNECTED; // 刷新(记录)本地地址 localAddress = Net.localAddress(fd); } } finally { writeLock.unlock(); } } finally { readLock.unlock(); } return this; } /* * 对UDP-Socket执行【bind】操作。 * * bindpoint: 待绑定的地址(ip+port);如果为null,则绑定到本地环回IP和随机端口 */ private void bindInternal(SocketAddress bindpoint) throws IOException { assert Thread.holdsLock(stateLock) && (localAddress == null); InetSocketAddress isa; // bindpoint为null,则绑定到本地环回IP和随机端口 if(bindpoint == null) { // only Inet4Address allowed with IPv4 socket if(family == StandardProtocolFamily.INET) { isa = new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0); } else { isa = new InetSocketAddress(0); } } else { isa = Net.checkAddress(bindpoint, family); } SecurityManager sm = System.getSecurityManager(); if(sm != null) { sm.checkListen(isa.getPort()); } // 为指定协议族的Socket绑定IP地址与端口号 Net.bind(family, fd, isa.getAddress(), isa.getPort()); // 从指定的Socket文件描述符中解析出本地Socket地址后返回 localAddress = Net.localAddress(fd); } /*▲ socket操作 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 关闭 ████████████████████████████████████████████████████████████████████████████████┓ */ /** * Invoked by implCloseChannel to close the channel. * * This method waits for outstanding I/O operations to complete. When in * blocking mode, the socket is pre-closed and the threads in blocking I/O * operations are signalled to ensure that the outstanding I/O operations * complete quickly. * * The socket is closed by this method when it is not registered with a * Selector. Note that a channel configured blocking may be registered with * a Selector. This arises when a key is canceled and the channel configured * to blocking mode before the key is flushed from the Selector. */ // 实现对"可选择"通道的关闭操作 @Override protected void implCloseSelectableChannel() throws IOException { assert !isOpen(); boolean blocking; boolean interrupted = false; /* set state to ST_CLOSING and invalid membership keys */ synchronized(stateLock) { assert state<ST_CLOSING; blocking = isBlocking(); // 标记通道进入关闭状态 state = ST_CLOSING; /* if member of any multicast groups then invalidate the keys */ if(registry != null) { registry.invalidateAll(); } } /* wait for any outstanding I/O operations to complete */ // 对于阻塞式通道,需要等到该通道上其他阻塞操作结束之后才能进行关闭 if(blocking) { synchronized(stateLock) { assert state == ST_CLOSING; long reader = readerThread; long writer = writerThread; // 如果该通道上存在其他阻塞的读/写操作,则唤醒那些阻塞的操作,以促使它们结束运行 if(reader != 0 || writer != 0) { nd.preClose(fd); if(reader != 0) { // 唤醒阻塞的reader线程 NativeThread.signal(reader); } if(writer != 0) { // 唤醒阻塞的writer线程 NativeThread.signal(writer); } // wait for blocking I/O operations to end while(readerThread != 0 || writerThread != 0) { try { stateLock.wait(); } catch(InterruptedException e) { interrupted = true; } } } } // 对于非阻塞通道,确保其他读写操作已经完成 } else { // non-blocking mode: wait for read/write to complete readLock.lock(); try { writeLock.lock(); writeLock.unlock(); } finally { readLock.unlock(); } } // set state to ST_KILLPENDING synchronized(stateLock) { assert state == ST_CLOSING; state = ST_KILLPENDING; } /* close socket if not registered with Selector */ // 如果通道已经没有在任何选择器上注册,则销毁它 if(!isRegistered()) { kill(); } // 恢复中断状态 if(interrupted) { Thread.currentThread().interrupt(); } } // 销毁当前通道,即释放对Socket文件描述符的引用 @Override public void kill() throws IOException { synchronized(stateLock) { if(state == ST_KILLPENDING) { // 通道进入销毁状态 state = ST_KILLED; try { // 释放对本地文件描述符的引用 nd.close(fd); } finally { // notify resource manager ResourceManager.afterUdpClose(); } } } } /*▲ 关闭 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 数据传输 ████████████████████████████████████████████████████████████████████████████████┓ */ // 向target处的远端(目的地)发送src中存储的数据,返回写入的字节数量 @Override public int send(ByteBuffer src, SocketAddress target) throws IOException { Objects.requireNonNull(src); // 获取远程地址 InetSocketAddress isa = Net.checkAddress(target, family); writeLock.lock(); try { boolean blocking = isBlocking(); int n = 0; try { /* * 标记可能阻塞的IO操作的开始:需要为阻塞通道所在的线程设置中断回调,该回调在遇到线程中断时会关闭通道; * 不必保证已连接,返回远程连接地址。 */ SocketAddress remote = beginWrite(blocking, false); // 如果存在远程连接地址 if(remote != null) { // 如果发送的目标地址跟远程连接地址不匹配,则抛异常 if(!target.equals(remote)) { throw new AlreadyConnectedException(); } do { /* * 从缓冲区src读取,读到的内容向文件描述符fd(关联的socket)中追加后,返回写入的字节数量。 * 注:这里只是将数据写入到了本地fd中,因为在connect()中,已经将本地fd与远程建立了联系。 *   不要忘记,fd在底层代表的是本地Socket。 */ n = IOUtil.write(fd, src, -1, nd); } while((n == IOStatus.INTERRUPTED) && isOpen()); // 未连接 } else { SecurityManager sm = System.getSecurityManager(); if(sm != null) { InetAddress ia = isa.getAddress(); if(ia.isMulticastAddress()) { sm.checkMulticast(ia); } else { sm.checkConnect(ia.getHostAddress(), isa.getPort()); } } do { // 向isa处的远端(目的地)发送src中存储的数据(一次可能发不完) n = send(fd, src, isa); } while((n == IOStatus.INTERRUPTED) && isOpen()); } } finally { /* * 标记可能阻塞的IO操作的结束:需要移除为阻塞通道所在的线程设置的中断回调; * 对于阻塞通道,还需要唤醒其他阻塞在关闭操作上的线程。 */ endWrite(blocking, n>0); assert IOStatus.check(n); } return IOStatus.normalize(n); } finally { writeLock.unlock(); } } // 从远端UDP-Socket中接收数据并存入dst,返回实际接收到的字节数 @Override public SocketAddress receive(ByteBuffer dst) throws IOException { if(dst.isReadOnly()) { throw new IllegalArgumentException("Read-only buffer"); } readLock.lock(); try { boolean blocking = isBlocking(); int n = 0; ByteBuffer bb = null; try { /* * 标记可能阻塞的IO操作的开始:需要为阻塞通道所在的线程设置中断回调,该回调在遇到线程中断时会关闭通道; * 不必保证已连接,返回远程连接地址。 */ SocketAddress remote = beginRead(blocking, false); // 如果远程地址不为null,说明远端与当前Socket建立了连接 boolean connected = (remote != null); SecurityManager sm = System.getSecurityManager(); // 如果建立了连接,或者存在安全管理器 if(connected || (sm == null)) { // connected or no security manager do { // 从远端UDP-Socket接收数据并存入dst中,返回实际接收到的字节数;connected指示两端的Socket是否建立了连接 n = receive(fd, dst, connected); } while((n == IOStatus.INTERRUPTED) && isOpen()); if(n == IOStatus.UNAVAILABLE) { return null; } // 如果没有建立连接,且没有安全管理器 } else { /* Cannot receive into user's buffer when running with a security manager and not connected */ // 获取缓冲区长度(还剩多少空间) int size = dst.remaining(); // 获取一块容量至少为size个字节的直接缓冲区 bb = Util.getTemporaryDirectBuffer(size); for(; ; ) { do { // 从远端UDP-Socket接收数据并存入bb中,返回实际接收到的字节数;connected指示两端的Socket是否建立了连接 n = receive(fd, bb, connected); } while((n == IOStatus.INTERRUPTED) && isOpen()); if(n == IOStatus.UNAVAILABLE) { return null; } // 记录接收到的数据的发送端地址 InetSocketAddress isa = (InetSocketAddress) sender; try { sm.checkAccept(isa.getAddress().getHostAddress(), isa.getPort()); } catch(SecurityException se) { // Ignore packet bb.clear(); n = 0; continue; } // 将bb从写模式切换为读模式 bb.flip(); // 将bb中的数据存入dst dst.put(bb); break; } } assert sender != null; // 返回接收到的数据的发送端地址,该地址信息由receive0()方法设置 return sender; } finally { if(bb != null) { // 采用FILO的形式(入栈模式)将bb放入Buffer缓存池以待复用 Util.releaseTemporaryDirectBuffer(bb); } /* * 标记可能阻塞的IO操作的结束:需要移除为阻塞通道所在的线程设置的中断回调; * 对于阻塞通道,还需要唤醒其他阻塞在关闭操作上的线程。 */ endRead(blocking, n>0); assert IOStatus.check(n); } } finally { readLock.unlock(); } } // 向target处的远端(目的地)发送src中存储的数据(一次可能发不完),返回实际传输的字节数 private int send(FileDescriptor fd, ByteBuffer src, InetSocketAddress target) throws IOException { // 如果src是直接缓冲区,则可以直接调用本地发送方法 if(src instanceof DirectBuffer) { // 通过本地Socket(由fd指代),将bb中的数据发送到远端target处的UDP-Socket,返回实际传输的字节数 return sendFromNativeBuffer(fd, src, target); } // Substitute a native buffer int pos = src.position(); int lim = src.limit(); assert (pos<=lim); int rem = (pos<=lim ? lim - pos : 0); // 获取一块容量至少为rem个字节的直接缓冲区 ByteBuffer bb = Util.getTemporaryDirectBuffer(rem); try { // 向bb中存入src中的数据 bb.put(src); // 从写模式翻转为读模式 bb.flip(); /* Do not update src until we see how many bytes were written */ // 暂时先让src的游标维持原状 src.position(pos); // 通过本地Socket(由fd指代),将bb中的数据发送到远端target处的UDP-Socket,返回实际传输的字节数 int n = sendFromNativeBuffer(fd, bb, target); // 如果成功发送了一部分字节,则同步更新src的游标 if(n>0) { src.position(pos + n); } // 返回实际发送的字节数 return n; } finally { // 采用FILO的形式(入栈模式)将bb放入Buffer缓存池以待复用 Util.releaseTemporaryDirectBuffer(bb); } } // 通过本地Socket(由fd指代),将bb中的数据发送到远端target处的UDP-Socket,返回实际传输的字节数 private int sendFromNativeBuffer(FileDescriptor fd, ByteBuffer bb, InetSocketAddress target) throws IOException { int pos = bb.position(); int lim = bb.limit(); assert (pos<=lim); // 计算有多少待发送的字节 int rem = (pos<=lim ? lim - pos : 0); boolean preferIPv6 = (family != StandardProtocolFamily.INET); int written; try { // 通过本地Socket,将bb中的数据发送到远端target处的UDP-Socket,返回实际传输的字节数 written = send0(preferIPv6, fd, ((DirectBuffer) bb).address() + pos, rem, target.getAddress(), target.getPort()); } catch(PortUnreachableException pue) { if(isConnected()) { throw pue; } written = rem; } // 将bb中的游标前进,表示跳过已经写入的字节 if(written>0) { bb.position(pos + written); } return written; } // 从远端UDP-Socket接收数据并存入dst中,返回实际接收到的字节数;connected指示两端的Socket是否建立了连接 private int receive(FileDescriptor fd, ByteBuffer dst, boolean connected) throws IOException { int pos = dst.position(); int lim = dst.limit(); assert (pos<=lim); // 计算dst的剩余空间 int rem = (pos<=lim ? lim - pos : 0); // 如果dst已经是直接缓冲区,且有剩余空间,则直接接收数据 if(dst instanceof DirectBuffer && rem>0) { // 从远端UDP-Socket接收数据并存入bb中,返回实际接收到的字节数;connected指示两端的Socket是否建立了连接 return receiveIntoNativeBuffer(fd, dst, rem, pos, connected); } /* * Substitute a native buffer. * If the supplied buffer is empty we must instead use a nonempty buffer, * otherwise the call will not block waiting for a datagram on some platforms. */ // 至少准备拥有一个字节的缓冲区 int newSize = Math.max(rem, 1); // 获取一块容量至少为newSize个字节的直接缓冲区 ByteBuffer bb = Util.getTemporaryDirectBuffer(newSize); try { // 从远端UDP-Socket接收数据并存入bb中,返回实际接收到的字节数;connected指示两端的Socket是否建立了连接 int n = receiveIntoNativeBuffer(fd, bb, newSize, 0, connected); // 将bb从写模式切换到读模式 bb.flip(); // 将bb中的数据存入dst if(n>0 && rem>0) { dst.put(bb); } // 返回实际接收的字节数 return n; } finally { // 采用FILO的形式(入栈模式)将bb放入Buffer缓存池以待复用 Util.releaseTemporaryDirectBuffer(bb); } } // 从远端UDP-Socket接收数据并存入bb中,返回实际接收到的字节数;connected指示两端的Socket是否建立了连接 private int receiveIntoNativeBuffer(FileDescriptor fd, ByteBuffer bb, int rem, int pos, boolean connected) throws IOException { // 从远端UDP-Socket接收数据并存入bb中,返回实际接收到的字节数 int n = receive0(fd, ((DirectBuffer) bb).address() + pos, rem, connected); // 更新bb中的游标 if(n>0) { bb.position(pos + n); } return n; } /*▲ 数据传输 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 读/写操作 ████████████████████████████████████████████████████████████████████████████████┓ */ // 从UDP-Socket中读取数据,并存入dst,返回成功读到的字节数;如果是阻塞通道,会在没有可读数据时陷入阻塞 @Override public int read(ByteBuffer dst) throws IOException { Objects.requireNonNull(dst); readLock.lock(); try { boolean blocking = isBlocking(); int n = 0; try { // 标记可能阻塞的IO操作的开始:需要为阻塞通道所在的线程设置中断回调,该回调在遇到线程中断时会关闭通道;必须保证已连接 beginRead(blocking, true); do { // 从文件描述符fd(关联的socket)中起始位置处读取,读到的内容存入dst后,返回读到的字节数量 n = IOUtil.read(fd, dst, -1, nd); // 不会理会中断标记,会继续读取 } while((n == IOStatus.INTERRUPTED) && isOpen()); } finally { /* * 标记可能阻塞的IO操作的结束:需要移除为阻塞通道所在的线程设置的中断回调; * 对于阻塞通道,还需要唤醒其他阻塞在关闭操作上的线程。 */ endRead(blocking, n>0); assert IOStatus.check(n); } return IOStatus.normalize(n); } finally { readLock.unlock(); } } //【散射】从UDP-Socket中读取数据,并存入dsts中offset处起的length个缓冲区中,返回成功读到的字节数;如果是阻塞通道,会在没有可读数据时陷入阻塞 @Override public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { Objects.checkFromIndexSize(offset, length, dsts.length); readLock.lock(); try { boolean blocking = isBlocking(); long n = 0; try { // 标记可能阻塞的IO操作的开始:需要为阻塞通道所在的线程设置中断回调,该回调在遇到线程中断时会关闭通道;必须保证已连接 beginRead(blocking, true); do { // 从文件描述符fd(关联的socket)中读取,读到的内容依次存入dsts中offset处起的length个缓冲区中,返回读到的字节数量 n = IOUtil.read(fd, dsts, offset, length, nd); // 不会理会中断标记,会继续读取 } while((n == IOStatus.INTERRUPTED) && isOpen()); } finally { /* * 标记可能阻塞的IO操作的结束:需要移除为阻塞通道所在的线程设置的中断回调; * 对于阻塞通道,还需要唤醒其他阻塞在关闭操作上的线程。 */ endRead(blocking, n>0); assert IOStatus.check(n); } return IOStatus.normalize(n); } finally { readLock.unlock(); } } // 从src中读取数据,读到的内容向当前UDP-Socket通道中写入 @Override public int write(ByteBuffer src) throws IOException { Objects.requireNonNull(src); writeLock.lock(); try { boolean blocking = isBlocking(); int n = 0; try { // 标记可能阻塞的IO操作的开始:需要为阻塞通道所在的线程设置中断回调,该回调在遇到线程中断时会关闭通道;必须保证已连接 beginWrite(blocking, true); do { // 从缓冲区src读取,读到的内容向文件描述符fd(关联的socket)中追加后,返回写入的字节数量 n = IOUtil.write(fd, src, -1, nd); } while((n == IOStatus.INTERRUPTED) && isOpen()); } finally { /* * 标记可能阻塞的IO操作的结束:需要移除为阻塞通道所在的线程设置的中断回调; * 对于阻塞通道,还需要唤醒其他阻塞在关闭操作上的线程。 */ endWrite(blocking, n>0); assert IOStatus.check(n); } return IOStatus.normalize(n); } finally { writeLock.unlock(); } } //【聚集】从srcs中offset处起的length个缓冲区读取数据,读到的内容向当前UDP-Socket通道中写入 @Override public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { Objects.checkFromIndexSize(offset, length, srcs.length); writeLock.lock(); try { boolean blocking = isBlocking(); long n = 0; try { // 标记可能阻塞的IO操作的开始:需要为阻塞通道所在的线程设置中断回调,该回调在遇到线程中断时会关闭通道;必须保证已连接 beginWrite(blocking, true); do { // 从srcs[offset, offset+length-1]中各个缓冲区读取数据,读到的内容向文件描述符fd(关联的socket)中起始位置处写入后,返回写入的字节数量 n = IOUtil.write(fd, srcs, offset, length, nd); } while((n == IOStatus.INTERRUPTED) && isOpen()); } finally { /* * 标记可能阻塞的IO操作的结束:需要移除为阻塞通道所在的线程设置的中断回调; * 对于阻塞通道,还需要唤醒其他阻塞在关闭操作上的线程。 */ endWrite(blocking, n>0); assert IOStatus.check(n); } return IOStatus.normalize(n); } finally { writeLock.unlock(); } } /** * Poll this channel's socket for reading up to the given timeout. * * @return {@code true} if the socket is polled */ /* * 注册监听可读事件(Net.POLLIN),当通道内有数据可读时,当前Socket会收到通知。 * timeout是允许可阻塞socket等待可读数据的时间。 * 返回值指示是否在阻塞时间内收到了"可读取数据"的信号。 */ boolean pollRead(long timeout) throws IOException { boolean blocking = isBlocking(); assert Thread.holdsLock(blockingLock()) && blocking; readLock.lock(); try { boolean polled = false; try { // 标记可能阻塞的IO操作的开始:需要为阻塞通道所在的线程设置中断回调,该回调在遇到线程中断时会关闭通道;不必保证已连接 beginRead(blocking, false); // 注册Net.POLLIN事件,远端发来"有可读数据"的消息时,会通知当前Socket int events = Net.poll(fd, Net.POLLIN, timeout); polled = (events != 0); } finally { /* * 标记可能阻塞的IO操作的结束:需要移除为阻塞通道所在的线程设置的中断回调; * 对于阻塞通道,还需要唤醒其他阻塞在关闭操作上的线程。 */ endRead(blocking, polled); } return polled; } finally { readLock.unlock(); } } /*▲ 读/写操作 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 监听参数/事件 ████████████████████████████████████████████████████████████████████████████████┓ */ /** * Translates an interest operation set into a native poll event set */ /* * 翻译Datagram通道监听的事件,返回对ops的翻译结果 * * 方向:Java层 --> native层 *    SelectionKey.XXX --> Net.XXX */ public int translateInterestOps(int ops) { int newOps = 0; if((ops & SelectionKey.OP_READ) != 0) { newOps |= Net.POLLIN; } if((ops & SelectionKey.OP_WRITE) != 0) { newOps |= Net.POLLOUT; } if((ops & SelectionKey.OP_CONNECT) != 0) { newOps |= Net.POLLIN; } return newOps; } /*▲ 监听参数/事件 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 就绪参数/事件 ████████████████████████████████████████████████████████████████████████████████┓ */ /* *【增量更新】已就绪事件 * * 将本地(native)反馈的就绪信号ops翻译并存储到Java层的就绪事件readyOps中, * 返回值指示上一次反馈的事件与本次反馈的事件是否发生了改变。 * * 通道收到有效的反馈事件后,会【增量更新】上次记录的已就绪事件, * 如果本地(native)反馈了错误或挂起信号,则将已就绪事件直接设置为通道注册的监听事件。 * * 方向:native层 --> Java层 *    Net.XXX --> SelectionKey.XXX * * 参见:SelectionKeyImpl#readyOps */ public boolean translateAndUpdateReadyOps(int ops, SelectionKeyImpl ski) { return translateReadyOps(ops, ski.nioReadyOps(), ski); } /* *【覆盖更新】已就绪事件 * * 将本地(native)反馈的就绪信号ops翻译并存储到Java层的就绪事件readyOps中, * 返回值指示上一次反馈的事件与本次反馈的事件是否发生了改变。 * * 通道收到有效的反馈事件后,会【覆盖】(selectionKey中)上次记录的已就绪事件, * 如果本地(native)反馈了错误或挂起信号,则将已就绪事件直接设置为通道注册的监听事件。 * * 方向:native层 --> Java层 *    Net.XXX --> SelectionKey.XXX * * 参见:SelectionKeyImpl#readyOps */ public boolean translateAndSetReadyOps(int ops, SelectionKeyImpl ski) { return translateReadyOps(ops, 0, ski); } /** * Translates native poll revent set into a ready operation set */ /* *【增量更新】已就绪事件(基于initialOps叠加) * * 将本地(native)反馈的就绪信号ops翻译并存储到Java层的就绪事件readyOps中, * 返回值指示上一次反馈的事件与本次反馈的事件是否发生了改变。 * * 通道收到有效的反馈事件后,会将其【叠加】在initialOps上,换句话说是对已就绪事件的增量更新。 * 如果本地(native)反馈了错误或挂起信号,则将已就绪事件直接设置为通道注册的监听事件 * * 方向:native层 --> Java层 *    Net.XXX --> SelectionKey.XXX * * 参见:SelectionKeyImpl#readyOps */ public boolean translateReadyOps(int ops, int initialOps, SelectionKeyImpl selectionKey) { // 不合规的文件描述符 if((ops & Net.POLLNVAL) != 0) { /* * This should only happen if this channel is pre-closed while a selection operation is in progress * ## Throw an error if this channel has not been pre-closed */ return false; } // 获取注册的监听事件:SelectionKey.XXX(不会验证当前"选择键"是否有效) int intOps = selectionKey.nioInterestOps(); // 获取已就绪事件 int oldOps = selectionKey.nioReadyOps(); int newOps = initialOps; // 本地(native)反馈了错误或挂起的信号 if((ops & (Net.POLLERR | Net.POLLHUP)) != 0) { newOps = intOps; // 直接将通道注册的监听事件设置为已就绪事件 selectionKey.nioReadyOps(newOps); return (newOps & ~oldOps) != 0; } // 该通道监听了"可读"事件,且通道内有数据可读 if(((ops & Net.POLLIN) != 0) && ((intOps & SelectionKey.OP_READ) != 0)) { newOps |= SelectionKey.OP_READ; } // 该通道监听了"可写"事件,且可以向通道写入数据 if(((ops & Net.POLLOUT) != 0) && ((intOps & SelectionKey.OP_WRITE) != 0)) { newOps |= SelectionKey.OP_WRITE; } // 将newOps设置为已就绪事件 selectionKey.nioReadyOps(newOps); return (newOps & ~oldOps) != 0; } /*▲ 就绪参数/事件 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ Socket配置参数 ████████████████████████████████████████████████████████████████████████████████┓ */ // 设置指定名称的Socket配置参数 @Override public <T> DatagramChannel setOption(SocketOption<T> name, T value) throws IOException { Objects.requireNonNull(name); if(!supportedOptions().contains(name)) { throw new UnsupportedOperationException("'" + name + "' not supported"); } synchronized(stateLock) { // 确保通道已经开启,否则抛异常 ensureOpen(); if(name == StandardSocketOptions.IP_TOS || name == StandardSocketOptions.IP_MULTICAST_TTL || name == StandardSocketOptions.IP_MULTICAST_LOOP) { // options are protocol dependent Net.setSocketOption(fd, family, name, value); return this; } if(name == StandardSocketOptions.IP_MULTICAST_IF) { if(value == null) { throw new IllegalArgumentException("Cannot set IP_MULTICAST_IF to 'null'"); } NetworkInterface interf = (NetworkInterface) value; if(family == StandardProtocolFamily.INET6) { int index = interf.getIndex(); if(index == -1) { throw new IOException("Network interface cannot be identified"); } Net.setInterface6(fd, index); } else { // need IPv4 address to identify interface Inet4Address target = Net.anyInet4Address(interf); if(target == null) { throw new IOException("Network interface not configured for IPv4"); } // 以int形式返回指定的IP4地址 int targetAddress = Net.inet4AsInt(target); Net.setInterface4(fd, targetAddress); } return this; } if(name == StandardSocketOptions.SO_REUSEADDR && Net.useExclusiveBind() && localAddress != null) { reuseAddressEmulated = true; this.isReuseAddress = (Boolean) value; } // remaining options don't need any special handling Net.setSocketOption(fd, Net.UNSPEC, name, value); return this; } } // 获取指定名称的Socket配置参数 @Override @SuppressWarnings("unchecked") public <T> T getOption(SocketOption<T> name) throws IOException { Objects.requireNonNull(name); if(!supportedOptions().contains(name)) { throw new UnsupportedOperationException("'" + name + "' not supported"); } synchronized(stateLock) { // 确保通道已经开启,否则抛异常 ensureOpen(); if(name == StandardSocketOptions.IP_TOS || name == StandardSocketOptions.IP_MULTICAST_TTL || name == StandardSocketOptions.IP_MULTICAST_LOOP) { return (T) Net.getSocketOption(fd, family, name); } if(name == StandardSocketOptions.IP_MULTICAST_IF) { if(family == StandardProtocolFamily.INET) { int address = Net.getInterface4(fd); if(address == 0) { return null; // default interface } // 将int形式的IP4地址以InetAddress返回 InetAddress ia = Net.inet4FromInt(address); NetworkInterface ni = NetworkInterface.getByInetAddress(ia); if(ni == null) { throw new IOException("Unable to map address to interface"); } return (T) ni; } else { int index = Net.getInterface6(fd); if(index == 0) { return null; // default interface } NetworkInterface ni = NetworkInterface.getByIndex(index); if(ni == null) { throw new IOException("Unable to map index to interface"); } return (T) ni; } } if(name == StandardSocketOptions.SO_REUSEADDR && reuseAddressEmulated) { return (T) Boolean.valueOf(isReuseAddress); } // no special handling return (T) Net.getSocketOption(fd, Net.UNSPEC, name); } } // 获取当前通道支持的Socket配置参数集合 @Override public final Set<SocketOption<?>> supportedOptions() { return DefaultOptionsHolder.defaultOptions; } /*▲ Socket配置参数 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 中断回调 ████████████████████████████████████████████████████████████████████████████████┓ */ /** * Marks the beginning of a read operation that might block. * * @param blocking true if configured blocking * @param mustBeConnected true if the socket must be connected * * @return remote address if connected * * @throws ClosedChannelException if the channel is closed * @throws NotYetConnectedException if mustBeConnected and not connected * @throws IOException if socket not bound and cannot be bound */ /* * 标记可能阻塞的IO操作的开始:需要为阻塞通道所在的线程设置中断回调,该回调在遇到线程中断时会关闭通道; * mustBeConnected指示是否必须保证已连接,返回远程连接地址。 */ private SocketAddress beginRead(boolean blocking, boolean mustBeConnected) throws IOException { // 如果通道处于阻塞模式,则设置一个线程中断回调,以便可以利用"中断"操作来退出阻塞 if(blocking) { begin(); } SocketAddress remote; synchronized(stateLock) { // 确保通道已经开启,否则抛异常 ensureOpen(); remote = remoteAddress; if((remote == null) && mustBeConnected) { throw new NotYetConnectedException(); } if(localAddress == null) { bindInternal(null); } if(blocking) { // 记录当前通道开始读操作时所在的native线程引用 readerThread = NativeThread.current(); } } return remote; } /** * Marks the end of a read operation that may have blocked. * * @throws AsynchronousCloseException if the channel was closed asynchronously */ /* * 标记可能阻塞的IO操作的结束:需要移除为阻塞通道所在的线程设置的中断回调; * 对于阻塞通道,还需要唤醒其他阻塞在关闭操作上的线程。 */ private void endRead(boolean blocking, boolean completed) throws AsynchronousCloseException { // 如果不是阻塞型通道,直接返回 if(!blocking) { return; } synchronized(stateLock) { // 结束读操作,置空线程号 readerThread = 0; // notify any thread waiting in implCloseSelectableChannel if(state == ST_CLOSING) { stateLock.notifyAll(); } } // 清除之前设置的线程中断回调 end(completed); } /** * Marks the beginning of a write operation that might block. * * @param blocking true if configured blocking * @param mustBeConnected true if the socket must be connected * * @return remote address if connected * * @throws ClosedChannelException if the channel is closed * @throws NotYetConnectedException if mustBeConnected and not connected * @throws IOException if socket not bound and cannot be bound */ /* * 标记可能阻塞的IO操作的开始:需要为阻塞通道所在的线程设置中断回调,该回调在遇到线程中断时会关闭通道; * mustBeConnected指示是否必须保证已连接,返回远程连接地址。 */ private SocketAddress beginWrite(boolean blocking, boolean mustBeConnected) throws IOException { // 如果通道处于阻塞模式,则设置一个线程中断回调,以便可以利用"中断"操作来退出阻塞 if(blocking) { begin(); } SocketAddress remote; synchronized(stateLock) { // 确保通道已经开启,否则抛异常 ensureOpen(); remote = remoteAddress; if((remote == null) && mustBeConnected) { throw new NotYetConnectedException(); } if(localAddress == null) { bindInternal(null); } if(blocking) { // 记录当前通道开始写操作时所在的native线程引用 writerThread = NativeThread.current(); } } return remote; } /** * Marks the end of a write operation that may have blocked. * * @throws AsynchronousCloseException if the channel was closed asynchronously */ /* * 标记可能阻塞的IO操作的结束:需要移除为阻塞通道所在的线程设置的中断回调; * 对于阻塞通道,还需要唤醒其他阻塞在关闭操作上的线程。 */ private void endWrite(boolean blocking, boolean completed) throws AsynchronousCloseException { if(!blocking) { return; } synchronized(stateLock) { // 结束写操作,置空线程号 writerThread = 0; // notify any thread waiting in implCloseSelectableChannel if(state == ST_CLOSING) { stateLock.notifyAll(); } } // 清除之前设置的线程中断回调 end(completed); } /*▲ 中断回调 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 阻塞 ████████████████████████████████████████████████████████████████████████████████┓ */ // 是否设置当前通道为阻塞模式 @Override protected void implConfigureBlocking(boolean block) throws IOException { readLock.lock(); try { writeLock.lock(); try { synchronized(stateLock) { // 确保通道已经开启,否则抛异常 ensureOpen(); // 是否阻塞(block)文件描述符fd关联的通道 IOUtil.configureBlocking(fd, block); } } finally { writeLock.unlock(); } } finally { readLock.unlock(); } } /*▲ 阻塞 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 状态 ████████████████████████████████████████████████████████████████████████████████┓ */ // 判断当前通道是否已建立连接 @Override public boolean isConnected() { synchronized(stateLock) { return (state == ST_CONNECTED); } } /** @throws ClosedChannelException if channel is closed */ // 确保通道已经开启,否则抛异常 private void ensureOpen() throws ClosedChannelException { if(!isOpen()) { throw new ClosedChannelException(); } } /*▲ 状态 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 地址信息 ████████████████████████████████████████████████████████████████████████████████┓ */ // 获取绑定的本地地址 @Override public SocketAddress getLocalAddress() throws IOException { synchronized(stateLock) { // 确保通道已经开启,否则抛异常 ensureOpen(); /* Perform security check before returning address */ // 对指定的地址进行安全校验 return Net.getRevealedLocalAddress(localAddress); } } // 获取绑定的本地地址 InetSocketAddress localAddress() { synchronized(stateLock) { return localAddress; } } // 获取连接的远程地址 @Override public SocketAddress getRemoteAddress() throws IOException { synchronized(stateLock) { // 确保通道已经开启,否则抛异常 ensureOpen(); return remoteAddress; } } // 获取连接的远程地址 InetSocketAddress remoteAddress() { synchronized(stateLock) { return remoteAddress; } } /*▲ 地址信息 ████████████████████████████████████████████████████████████████████████████████┛ */ /*▼ 组播操作 ████████████████████████████████████████████████████████████████████████████████┓ */ /* * 将当前组播Socket加入到group处的组播小组中,后续它将接收到该小组中的数据;interf是用来接收消息的网络接口(网卡) * 注:不会过滤消息 */ @Override public MembershipKey join(InetAddress group, NetworkInterface interf) throws IOException { return innerJoin(group, interf, null); } /* * 将当前组播Socket加入到group处的组播小组中,后续它将接收到该小组中的数据;interf是用来接收消息的网络接口(网卡) * 注:如果source不为null,则会过滤消息,即只处理源地址是source的那些数据包 */ @Override public MembershipKey join(InetAddress group, NetworkInterface interf, InetAddress source) throws IOException { Objects.requireNonNull(source); return innerJoin(group, interf, source); } /** * Joins channel's socket to the given group/interface and optional source address. */ /* * 将当前组播Socket加入到group处的组播小组中,后续它将接收到该小组中的数据;interf是用来接收消息的网络接口(网卡) * 注:如果source不为null,则会过滤消息,即只处理源地址是source的那些数据包 */ private MembershipKey innerJoin(InetAddress group, NetworkInterface interf, InetAddress source) throws IOException { if(!group.isMulticastAddress()) { throw new IllegalArgumentException("Group not a multicast address"); } /* check multicast address is compatible with this socket */ // 校验组播小组的地址类型是否与当前UDP-Socket使用的IP协议匹配 if(group instanceof Inet4Address) { if(family == StandardProtocolFamily.INET6 && !Net.canIPv6SocketJoinIPv4Group()) { throw new IllegalArgumentException("IPv6 socket cannot join IPv4 multicast group"); } } else if(group instanceof Inet6Address) { if(family != StandardProtocolFamily.INET6) { throw new IllegalArgumentException("Only IPv6 sockets can join IPv6 multicast group"); } } else { throw new IllegalArgumentException("Address type not supported"); } /* check source address */ // 校验过滤地址 if(source != null) { if(source.isAnyLocalAddress()) { throw new IllegalArgumentException("Source address is a wildcard address"); } if(source.isMulticastAddress()) { throw new IllegalArgumentException("Source address is multicast address"); } if(source.getClass() != group.getClass()) { throw new IllegalArgumentException("Source address is different type to group"); } } SecurityManager sm = System.getSecurityManager(); if(sm != null) { sm.checkMulticast(group); } synchronized(stateLock) { // 确保通道已经开启,否则抛异常 ensureOpen(); /* check the registry to see if we are already a member of the group */ // 如果组播Socket注册表还未初始化,则先构造组播Socket注册表的实例,此时,当前Socket还未注册到组播小组 if(registry == null) { registry = new MembershipRegistry(); // 如果组播Socket注册表已经初始化过了,接下来要检查当前Socket是否已经注册到了组播小组 } else { /* return existing membership key */ // 检查注册信息,如果当前组播Socket已经在相同的环境下注册过了,则直接返回 MembershipKey key = registry.checkMembership(group, interf, source); if(key != null) { return key; } } MembershipKeyImpl key; // 如果需要支持IP6协议;或者,支持join6()方法处理IP4地址 if((family == StandardProtocolFamily.INET6) && ((group instanceof Inet6Address) || Net.canJoin6WithIPv4Group())) { // 获取网络接口的索引 int index = interf.getIndex(); if(index == -1) { throw new IOException("Network interface cannot be identified"); } /* need multicast and source address as byte arrays */ // 组播小组地址 byte[] groupAddress = Net.inet6AsByteArray(group); // 过滤消息的地址 byte[] sourceAddress = (source == null) ? null : Net.inet6AsByteArray(source); /* join the group */ int n = Net.join6(fd, groupAddress, index, sourceAddress); if(n == IOStatus.UNAVAILABLE) { throw new UnsupportedOperationException(); } // 新建一个组播小组成员,并存储组播小组成员的注册信息 key = new MembershipKeyImpl.Type6(this, group, interf, source, groupAddress, index, sourceAddress); // 支持IP4地址 } else { /* need IPv4 address to identify interface */ // 返回从给定的网络接口上找到的首个绑定的IP4地址 Inet4Address target = Net.anyInet4Address(interf); if(target == null) { throw new IOException("Network interface not configured for IPv4"); } // 组播小组地址 int groupAddress = Net.inet4AsInt(group); // 接收消息的地址 int targetAddress = Net.inet4AsInt(target); // 过滤消息的地址 int sourceAddress = (source == null) ? 0 : Net.inet4AsInt(source); /* join the group */ int n = Net.join4(fd, groupAddress, targetAddress, sourceAddress); if(n == IOStatus.UNAVAILABLE) { throw new UnsupportedOperationException(); } // 新建一个组播小组成员,并存储组播小组成员的注册信息 key = new MembershipKeyImpl.Type4(this, group, interf, source, groupAddress, targetAddress, sourceAddress); } // 将组播小组成员加入组播注册表 registry.add(key); return key; } } // 从组播注册表中移除指定的组播小组成员;实际操作是将目标组播Socket从所在的组播小组中移除 void drop(MembershipKeyImpl key) { assert key.channel() == this; synchronized(stateLock) { // 如果组播小组成员key已经无效,则直接返回 if(!key.isValid()) { return; } try { if(key instanceof MembershipKeyImpl.Type6) { MembershipKeyImpl.Type6 key6 = (MembershipKeyImpl.Type6) key; Net.drop6(fd, key6.groupAddress(), key6.index(), key6.source()); } else { MembershipKeyImpl.Type4 key4 = (MembershipKeyImpl.Type4) key; Net.drop4(fd, key4.groupAddress(), key4.interfaceAddress(), key4.source()); } } catch(IOException ioe) { // should not happen throw new AssertionError(ioe); } // 将组播小组成员key设置为无效 key.invalidate(); // 移除一条组播小组成员信息 registry.remove(key); } } /** * Block datagrams from given source if a memory to receive all datagrams. */ // 屏蔽source处发来的消息,即禁止从source处接收消息;如果该组播小组已经设置了过滤,则抛异常 void block(MembershipKeyImpl key, InetAddress source) throws IOException { assert key.channel() == this; assert key.sourceAddress() == null; synchronized(stateLock) { // 如果组播小组成员key已经无效,则直接返回 if(!key.isValid()) { throw new IllegalStateException("key is no longer valid"); } if(source.isAnyLocalAddress()) { throw new IllegalArgumentException("Source address is a wildcard address"); } if(source.isMulticastAddress()) { throw new IllegalArgumentException("Source address is multicast address"); } if(source.getClass() != key.group().getClass()) { throw new IllegalArgumentException("Source address is different type to group"); } int n; if(key instanceof MembershipKeyImpl.Type6) { MembershipKeyImpl.Type6 key6 = (MembershipKeyImpl.Type6) key; n = Net.block6(fd, key6.groupAddress(), key6.index(), Net.inet6AsByteArray(source)); } else { MembershipKeyImpl.Type4 key4 = (MembershipKeyImpl.Type4) key; n = Net.block4(fd, key4.groupAddress(), key4.interfaceAddress(), Net.inet4AsInt(source)); } if(n == IOStatus.UNAVAILABLE) { // ancient kernel throw new UnsupportedOperationException(); } } } /** * Unblock given source. */ // 解除对source地址的屏蔽,即允许接收source处的消息 void unblock(MembershipKeyImpl key, InetAddress source) { assert key.channel() == this; assert key.sourceAddress() == null; synchronized(stateLock) { // 如果组播小组成员key已经无效,则直接返回 if(!key.isValid()) { throw new IllegalStateException("key is no longer valid"); } try { if(key instanceof MembershipKeyImpl.Type6) { MembershipKeyImpl.Type6 key6 = (MembershipKeyImpl.Type6) key; Net.unblock6(fd, key6.groupAddress(), key6.index(), Net.inet6AsByteArray(source)); } else { MembershipKeyImpl.Type4 key4 = (MembershipKeyImpl.Type4) key; Net.unblock4(fd, key4.groupAddress(), key4.interfaceAddress(), Net.inet4AsInt(source)); } } catch(IOException ioe) { // should not happen throw new AssertionError(ioe); } } } /*▲ 组播操作 ████████████████████████████████████████████████████████████████████████████████┛ */ // 返回通道在Java层的文件描述符 public FileDescriptor getFD() { return fd; } // 返回通道在本地(native层)的文件描述符 public int getFDVal() { return fdVal; } private static native void initIDs(); private static native void disconnect0(FileDescriptor fd, boolean isIPv6) throws IOException; private native int send0(boolean preferIPv6, FileDescriptor fd, long address, int len, InetAddress addr, int port) throws IOException; private native int receive0(FileDescriptor fd, long address, int len, boolean connected) throws IOException; @SuppressWarnings("deprecation") protected void finalize() throws IOException { // fd is null if constructor threw exception if(fd != null) { close(); } } private static class DefaultOptionsHolder { static final Set<SocketOption<?>> defaultOptions = defaultOptions(); private static Set<SocketOption<?>> defaultOptions() { HashSet<SocketOption<?>> set = new HashSet<>(); set.add(StandardSocketOptions.SO_SNDBUF); set.add(StandardSocketOptions.SO_RCVBUF); set.add(StandardSocketOptions.SO_REUSEADDR); if(Net.isReusePortAvailable()) { set.add(StandardSocketOptions.SO_REUSEPORT); } set.add(StandardSocketOptions.SO_BROADCAST); set.add(StandardSocketOptions.IP_TOS); set.add(StandardSocketOptions.IP_MULTICAST_IF); set.add(StandardSocketOptions.IP_MULTICAST_TTL); set.add(StandardSocketOptions.IP_MULTICAST_LOOP); set.addAll(ExtendedSocketOptions.options(SOCK_DGRAM)); return Collections.unmodifiableSet(set); } } }
34.040816
155
0.497649
9e4cdf3f46733f5bfcfa350d415560f5ab75db8a
3,534
/* * Copyright 2015 - 2021 TU Dortmund * * 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 de.learnlib.alex.data.entities.actions.web; import com.fasterxml.jackson.annotation.JsonTypeName; import de.learnlib.alex.common.utils.LoggerMarkers; import de.learnlib.alex.data.entities.ExecuteResult; import de.learnlib.alex.data.entities.WebElementLocator; import de.learnlib.alex.learning.services.connectors.WebSiteConnector; import javax.persistence.DiscriminatorValue; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.validation.constraints.NotNull; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; /** * Action to move the mouse to an element or a screen position, e.g. in order to make invisible elements visible or to * scroll on the page. */ @Entity @DiscriminatorValue("web_moveMouse") @JsonTypeName("web_moveMouse") public class MoveMouseAction extends WebSymbolAction { /** * The selector of the element. */ @Embedded private WebElementLocator node; /** * The amount in px to move the mouse in x direction from the current position. */ @NotNull private int offsetX; /** * The amount in px to move the mouse in y direction from the current position. */ @NotNull private int offsetY; @Override protected ExecuteResult execute(WebSiteConnector connector) { final WebElementLocator nodeWithVariables = node == null ? null : new WebElementLocator(insertVariableValues(node.getSelector()), node.getType()); try { final Actions actions = new Actions(connector.getDriver()); if (nodeWithVariables == null || nodeWithVariables.getSelector().trim().equals("")) { actions.moveByOffset(offsetX, offsetY).build().perform(); logger.info(LoggerMarkers.LEARNER, "Moved the mouse to the position ({}, {}) ", offsetX, offsetY); } else { final WebElement element = connector.getElement(nodeWithVariables); actions.moveToElement(element, offsetX, offsetY).build().perform(); logger.info(LoggerMarkers.LEARNER, "Moved the mouse to the element '{}'", nodeWithVariables); } return getSuccessOutput(); } catch (Exception e) { logger.info(LoggerMarkers.LEARNER, "Could not move the mouse to the element '{}' or the position ({}, {})", nodeWithVariables, offsetX, offsetY); return getFailedOutput(); } } public int getOffsetY() { return offsetY; } public void setOffsetY(int offsetY) { this.offsetY = offsetY; } public WebElementLocator getNode() { return node; } public void setNode(WebElementLocator node) { this.node = node; } public int getOffsetX() { return offsetX; } public void setOffsetX(int offsetX) { this.offsetX = offsetX; } }
33.028037
119
0.677985
253a93a676135a383fd1ed3b0df60734934452a4
788
package se.l4.graphql.binding.resolver.directive; import java.util.function.Consumer; import graphql.schema.GraphQLFieldDefinition; import se.l4.graphql.binding.resolver.DataFetchingSupplier; public interface GraphQLDirectiveFieldEncounter<A> extends GraphQLDirectiveApplyEncounter<A> { /** * Get the field on which the directive is being applied. * * @return */ GraphQLFieldDefinition getField(); /** * Transform the field using the given builder. * * @param consumer */ void transformField(Consumer<GraphQLFieldDefinition.Builder> consumer); /** * Get the supplier currently used. * * @return */ DataFetchingSupplier<?> getSupplier(); /** * Update the supplier. * * @param supplier */ void setSupplier(DataFetchingSupplier<?> supplier); }
20.205128
72
0.734772
2b31faad15a56b8f2732ae538a6722c05782006c
557
package cz.mg.vulkan; public class VkDescriptorSetLayoutCreateFlags extends VkFlags { public VkDescriptorSetLayoutCreateFlags() { } protected VkDescriptorSetLayoutCreateFlags(VkMemory vkmemory) { super(vkmemory); } protected VkDescriptorSetLayoutCreateFlags(VkMemory vkmemory, long vkaddress) { super(vkmemory, vkaddress); } public VkDescriptorSetLayoutCreateFlags(VkPointer pointer) { super(pointer); } public VkDescriptorSetLayoutCreateFlags(int value) { setValue(value); } }
22.28
83
0.716338
5460ea042b881f30e7ce56852849aceb814b584e
978
package com.yourtion.leetcode.daily.m07.d09; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.stream.Stream; import static org.junit.jupiter.params.provider.Arguments.arguments; @DisplayName("每日一题 - 20200709") class SolutionTest { static Stream<Arguments> testDataProvider() { return Stream.of( arguments(new String[]{"looked", "just", "like", "her", "brother"}, "jesslookedjustliketimherbrother", 7) ); } @ParameterizedTest() @MethodSource("testDataProvider") void respace(String[] dic, String source, int res) { System.out.printf("runTest: %s %s , res: %d", Arrays.toString(dic), source, res); Assertions.assertEquals(res, new Solution().respace(dic, source)); } }
33.724138
121
0.715746
afbb8aff6adba0ac048c364348ff627d4878e843
1,256
package cn.obcp.user.controller; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.SessionException; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import cn.obcp.base.RetData; import cn.obcp.base.utils.StringUtils; import cn.obcp.cache.ICache; import cn.obcp.user.domain.TUserExtend; import springfox.documentation.annotations.ApiIgnore; // ##remain#import# /** * <pre> * 用户登录记录的Controller * 该代码通过mgicode代码生成器生成 * </pre> */ @Controller @ApiIgnore @RequestMapping("/v1/") public class LoginController { @Autowired private ICache redisUtils; @RequestMapping("logout") public RetData logout() { try { Subject subject = SecurityUtils.getSubject(); TUserExtend userExtend = (TUserExtend) SecurityUtils.getSubject().getPrincipal(); if (null != userExtend && StringUtils.isNotNullOrEmpty(userExtend.getUserToken())) { redisUtils.delete(userExtend.getUserToken());// 删除token缓存 } return RetData.succuess(); } catch (SessionException e) { return RetData.succuess(); } catch (Exception e) { return RetData.succuess(); } } }
26.166667
87
0.76035
6d78b9ad1838c9dda15b5b23d995e4e56d5c55f1
1,893
package org.innovateuk.ifs.management.competition.setup.core.form; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.springframework.web.multipart.MultipartFile; import javax.validation.constraints.NotNull; public class TermsAndConditionsForm extends CompetitionSetupForm { @NotNull(message = "validation.termsandconditionsform.field.required") private Long termsAndConditionsId; private MultipartFile termsAndConditionsDoc; public Long getTermsAndConditionsId() { return termsAndConditionsId; } public void setTermsAndConditionsId(Long termsAndConditionsId) { this.termsAndConditionsId = termsAndConditionsId; } public MultipartFile getTermsAndConditionsDoc() { return termsAndConditionsDoc; } public void setTermsAndConditionsDoc(MultipartFile termsAndConditionsDoc) { this.termsAndConditionsDoc = termsAndConditionsDoc; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TermsAndConditionsForm that = (TermsAndConditionsForm) o; return new EqualsBuilder() .append(termsAndConditionsId, that.termsAndConditionsId) .append(termsAndConditionsDoc, that.termsAndConditionsDoc) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(termsAndConditionsId) .append(termsAndConditionsDoc) .toHashCode(); } @Override public String toString() { return "TermsAndConditionsForm{" + "termsAndConditionsId=" + termsAndConditionsId + ", termsAndConditionsDoc=" + termsAndConditionsDoc + '}'; } }
31.032787
79
0.685156
e6cab116dae71b143cb8c113df71461fa5f8a667
562
package com.peregud.patternbuilder; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public final class PersonGeneratorUtil { private PersonGeneratorUtil() { } public static List<Person> createPersonList(List<Person> list) { return list.stream() .sorted(Comparator.comparing(Person::getFirstName) .thenComparing(Person::getLastName)) .distinct() .filter(Person::underAge) .collect(Collectors.toList()); } }
26.761905
68
0.633452
4db15c6494763bb79a4a71f4e2056d891c1880de
569
package io.lktk; import java.nio.ByteBuffer; class JNI { static native long create_hasher(); static native void destroy_hasher(long hasher); static native void blake3_hasher_init(long hasher); static native void blake3_hasher_init_keyed(long hasher, ByteBuffer byteBuff); static native void blake3_hasher_init_derive_key(long hasher, String context); static native void blake3_hasher_update(long hasher, ByteBuffer byteBuff, int input_len); static native void blake3_hasher_finalize(long hasher, ByteBuffer byteBuff, int out_len); }
28.45
93
0.782074
8502c618c895271f14b206956b0f36a003a45821
11,763
/* * Copyright (c) 2014 Optimal Payments * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.paysafe.customervault; import com.google.gson.annotations.Expose; import com.paysafe.common.CardExpiry; import com.paysafe.common.Error; import com.paysafe.common.Id; import com.paysafe.common.impl.BaseBuilder; import com.paysafe.common.impl.BaseDomainObject; import com.paysafe.common.impl.GenericBuilder; import com.paysafe.common.impl.NestedBuilder; // TODO: Auto-generated Javadoc /** * The Class Card. * @author manisha.rani * @since * 25-02-2016. */ public class Card implements BaseDomainObject { /** The id. */ private Id<Card> id; /** The nick name. */ @Expose private String nickName; /** The status. */ @Expose private Status status; /** The merchant ref num. */ @Expose private String merchantRefNum; /** The holder name. */ @Expose private String holderName; /** The card num. */ @Expose private String cardNum; /** The card bin. */ private String cardBin; /** The last digits. */ private String lastDigits; /** The card expiry. */ @Expose private CardExpiry cardExpiry; /** The card type. */ private String cardType; /** The billing address id. */ @Expose private Id<Address> billingAddressId; /** The default card indicator. */ private Boolean defaultCardIndicator; /** The payment token. */ @Expose private String paymentToken; /** The single use token. */ @Expose private String singleUseToken; /** The error. */ private Error error; /** The profile id. */ @Expose private Id<Profile> profileId; /** * Gets the id. * * @return the id */ public final Id<Card> getId() { return id; } /** * Sets the id. * * @param id the new id */ public final void setId(final Id<Card> id) { this.id = id; } /** * Gets the nick name. * * @return the nick name */ public final String getNickName() { return nickName; } /** * Sets the nick name. * * @param nickName the new nick name */ public final void setNickName(final String nickName) { this.nickName = nickName; } /** * Gets the status. * * @return the status */ public final Status getStatus() { return status; } /** * Sets the status. * * @param status the new status */ public final void setStatus(final Status status) { this.status = status; } /** * Gets the merchant ref num. * * @return the merchant ref num */ public final String getMerchantRefNum() { return merchantRefNum; } /** * Sets the merchant ref num. * * @param merchantRefNum the new merchant ref num */ public final void setMerchantRefNum(final String merchantRefNum) { this.merchantRefNum = merchantRefNum; } /** * Gets the holder name. * * @return the holder name */ public final String getHolderName() { return holderName; } /** * Sets the holder name. * * @param holderName the new holder name */ public final void setHolderName(final String holderName) { this.holderName = holderName; } /** * Gets the card num. * * @return the card num */ public final String getCardNum() { return cardNum; } /** * Sets the card num. * * @param cardNum the new card num */ public final void setCardNum(final String cardNum) { this.cardNum = cardNum; } /** * Gets the card bin. * * @return the card bin */ public final String getCardBin() { return cardBin; } /** * Sets the card bin. * * @param cardBin the new card bin */ public final void setCardBin(final String cardBin) { this.cardBin = cardBin; } /** * Gets the last digits. * * @return the last digits */ public final String getLastDigits() { return lastDigits; } /** * Sets the last digits. * * @param lastDigits the new last digits */ public final void setLastDigits(final String lastDigits) { this.lastDigits = lastDigits; } /** * Gets the card expiry. * * @return the card expiry */ public final CardExpiry getCardExpiry() { return cardExpiry; } /** * Sets the card expiry. * * @param cardExpiry the new card expiry */ public final void setCardExpiry(final CardExpiry cardExpiry) { this.cardExpiry = cardExpiry; } /** * Gets the card type. * * @return the card type */ public final String getCardType() { return cardType; } /** * Sets the card type. * * @param cardType the new card type */ public final void setCardType(final String cardType) { this.cardType = cardType; } /** * Gets the billing address id. * * @return the billing address id */ public final Id<Address> getBillingAddressId() { return billingAddressId; } /** * Sets the billing address id. * * @param billingAddressId the new billing address id */ public final void setBillingAddressId(final Id<Address> billingAddressId) { this.billingAddressId = billingAddressId; } /** * Gets the default card indicator. * * @return the default card indicator */ public final Boolean getDefaultCardIndicator() { return defaultCardIndicator; } /** * Sets the default card indicator. * * @param defaultCardIndicator the new default card indicator */ public final void setDefaultCardIndicator(final Boolean defaultCardIndicator) { this.defaultCardIndicator = defaultCardIndicator; } /** * Gets the payment token. * * @return the payment token */ public final String getPaymentToken() { return paymentToken; } /** * Sets the payment token. * * @param paymentToken the new payment token */ public final void setPaymentToken(final String paymentToken) { this.paymentToken = paymentToken; } /** * Gets the single use token. * * @return the single use token */ public final String getSingleUseToken() { return singleUseToken; } /** * Sets the single use token. * * @param singleUseToken the new single use token */ public final void setSingleUseToken(final String singleUseToken) { this.singleUseToken = singleUseToken; } /* (non-Javadoc) * @see com.optimalpayments.common.impl.BaseDomainObject#getError() */ @Override public final Error getError() { return error; } /** * Sets the error. * * @param error the new error */ public final void setError(final Error error) { this.error = error; } /** * Gets the profile id. * * @return the profile id */ public final Id<Profile> getProfileId() { return profileId; } /** * Sets the profile id. * * @param profileId the new profile id */ public final void setProfileId(final Id<Profile> profileId) { this.profileId = profileId; } /** * Get a card builder. * * @return CardBuilder */ public static final CardBuilder builder() { return new CardBuilder(); } /** * The builder class for Card. */ public static class CardBuilder extends BaseBuilder<Card> { /** The card. */ private final Card card = new Card(); /** The card expiry builder. */ private CardExpiry.CardExpiryBuilder<CardBuilder> cardExpiryBuilder; /** * Build this card object. * * @return Card */ @Override public final Card build() { if (null != cardExpiryBuilder) { card.setCardExpiry(cardExpiryBuilder.build()); } return card; } /** * Set the id property. * * @param id the id * @return CardBuilder */ public final CardBuilder id(final Id<Card> id) { card.setId(id); return this; } /** * Set the nickName property. * * @param nickName the nick name * @return CardBuilder */ public final CardBuilder nickName(final String nickName) { card.setNickName(nickName); return this; } /** * Set the merchantRefNum property. * * @param merchantRefNum the merchant ref num * @return CardBuilder */ public final CardBuilder merchantRefNum(final String merchantRefNum) { card.setMerchantRefNum(merchantRefNum); return this; } /** * Set the holderName property. * * @param holderName the holder name * @return CardBuilder */ public final CardBuilder holderName(final String holderName) { card.setHolderName(holderName); return this; } /** * Set the cardNum property. * * @param cardNum the card num * @return CardBuilder */ public final CardBuilder cardNum(final String cardNum) { card.setCardNum(cardNum); return this; } /** * Build a cardExpiry within this card. * * @return CardExpiry.CardExpiryBuilder< CardBuilder > */ public final CardExpiry.CardExpiryBuilder<CardBuilder> cardExpiry() { if (null == cardExpiryBuilder) { cardExpiryBuilder = new CardExpiry.CardExpiryBuilder<CardBuilder>(this); } return cardExpiryBuilder; } /** * Set the billingAddressId property. * * @param billingAddressId the billing address id * @return CardBuilder */ public final CardBuilder billingAddressId(final Id<Address> billingAddressId) { card.setBillingAddressId(billingAddressId); return this; } /** * Set the profileId property. * * @param profileId the profile id * @return CardBuilder */ public final CardBuilder profileId(final Id<Profile> profileId) { card.setProfileId(profileId); return this; } } /** * The builder class for Card. * * @param <BLDRT> the generic type */ public static class CardBuilderSingleUse<BLDRT extends GenericBuilder> extends NestedBuilder<Card, BLDRT> { /** The card. */ private final Card card = new Card(); /** * Instantiates a new card builder single use. * * @param parent the parent */ public CardBuilderSingleUse(BLDRT parent) { super(parent); } /* (non-Javadoc) * @see com.optimalpayments.common.impl.BaseBuilder#build() */ @Override public Card build() { return card; } /** * Single use token. * * @param singleUseToken the single use token * @return CardBuilderSingleUse */ public final CardBuilderSingleUse<BLDRT> singleUseToken(final String singleUseToken) { card.setSingleUseToken(singleUseToken); return this; } } }
21.387273
100
0.637762
73b733b1fe5b31c65db35cc73b698496f7e7d94a
8,139
package twg2.parser.textParser; import twg2.functions.predicates.CharPredicate; /** The conditional read methods for a {@link TextParser} * @see TextParser * @author TeamworkGuy2 * @since 2013-12-10 */ public interface TextParserConditionals { /** Read the next character from the line * @param ch the character to match * @return true if the next char was read and matched the specified char, false if not (and the line buffer is left unmodified) */ public boolean nextIf(char ch); /** Read a matching string from the line * @param str the string to match * @return true if the entire string was matched, false if not (and the line buffer is left unmodified) */ public boolean nextIf(String str); /** Read the next character if the current character at the current line offset equals the specified character * @param ch the character to compare to the current line character * @param dst the destination to store the read character in * @return 1 if a matching character is read, 0 if not */ public int nextIf(char ch, Appendable dst); /** Read the next character if the current character at the current line offset equals the specified character * @param ch the first character to compare to the current line character * @param ch2 the second character to compare to the current line character * @param dst the destination to store the read character in * @return 1 if a matching character is read, 0 if not */ public int nextIf(char ch, char ch2, Appendable dst); /** Read the next character if the current character at the current line offset equals the specified character * @param ch the character to compare to the current line character * @param count the maximum number of matching characters to read, or 0 to * read as many matching characters as possible * @param dst the destination to store the read character in * @return 1 if a matching character is read, 0 if not */ public int nextIf(char ch, int count, Appendable dst); /** Read the next character if the current character at the current line offset equals the specified character * @param ch the first character to compare to the current line character * @param ch2 the second character to compare to the current line character * @param count the maximum number of matching characters to read, or 0 to * read as many matching characters as possible * @param dst the destination to store the read character in * @return 1 if a matching character is read, 0 if not */ public int nextIf(char ch, char ch2, int count, Appendable dst); /** Read as many characters as match from the current line * @param chars the list of valid characters that can be read * @param dst the destination to store the parsed text in * @return the number of characters read */ public int nextIf(char[] chars, Appendable dst); /** {@link #nextIf(char[], Appendable)} */ public int nextIf(char[] chars, int off, int len, Appendable dst); /** Read as many characters as match, up to {@code count} number of characters, from the current line * @param chars the list of valid characters that can be read * @param count the maximum number of matching characters to read, or 0 to * read as many matching characters as possible * @param dst the destination to store the parsed text in * @return the number of characters read */ public int nextIf(char[] chars, int count, Appendable dst); /** {@link #nextIf(char[], int, Appendable)} */ public int nextIf(char[] chars, int off, int len, int count, Appendable dst); /** Read as many characters as match, up to {@code count}, from the current line * @param condition the condition to check each character against * @param count the maximum number of matching characters to read, or 0 to * read as many matching characters as possible * @param dst the destination to store the parsed text in * @return the number of characters read */ public int nextIf(CharPredicate condition, int count, Appendable dst); /** Read as many characters as do not match, up to {@code count}, from the current line * @param ch the character to compare to the current line character * @param count the maximum number of matching characters to read, or 0 to * read as many matching characters as possible * @param dst the destination to store the read character in * @return the number of matching characters read */ public int nextIfNot(char ch, int count, Appendable dst); /** Read as many characters as do not match, up to {@code count}, from the current line * @param ch the first character to compare to the current line character * @param ch2 the second character to compare to the current line character * @param count the maximum number of matching characters to read, or 0 to * read as many matching characters as possible * @param dst the destination to store the read character in * @return the number of matching characters read */ public int nextIfNot(char ch, char ch2, int count, Appendable dst); /** Read as many characters as do not match, up to {@code count}, from the current line * @param ch the first character to compare to the current line character * @param ch2 the second character to compare to the current line character * @param ch3 the third character to compare to the current line character * @param count the maximum number of matching characters to read, or 0 to * read as many matching characters as possible * @param dst the destination to store the read character in * @return the number of matching characters read */ public int nextIfNot(char ch, char ch2, char ch3, int count, Appendable dst); /** Read as many characters as do not match, up to {@code count}, from the current line * @param chars the list of valid invalid characters to stop reading at * @param count the maximum number of characters to read, or 0 to read as * many matching characters as possible * @param dst the destination to store the parsed text in * @return the number of characters read */ public int nextIfNot(char[] chars, int count, Appendable dst); /** {@link #nextIfNot(char[], int, Appendable)} */ public int nextIfNot(char[] chars, int off, int len, int count, Appendable dst); /** Read as many characters as match, up to {@code count}, from the current line * until a {@code endCh} is encountered, only if it is not proceeded by {@code escCh} * @param dropEscChars true to not append escape characters to {@code dst}, false add all matching characters to dst */ public int nextIfNotPrecededBy(char endCh, char escCh, boolean dropEscChars, int count, Appendable dst); /** Read as many characters as match, up to {@code count}, from the current line * until an {@code endCh} is encountered, only if it is not proceeded by {@code escCh} * or until {@code stopCh} is encountered regardless of preceding character * @param dropEscChars true to not append escape characters to {@code dst}, false add all matching characters to dst */ public int nextIfNotPrecededBy(char endCh, char escCh, char stopCh, boolean dropEscChars, int count, Appendable dst); /** {@link #nextIfNotPrecededBy(char, char, char, boolean, int, Appendable)} */ public int nextIfNotPrecededBy(char endCh, char escCh, char stopCh1, char stopCh2, boolean dropEscChars, int count, Appendable dst); /** {@link #nextIfNotPrecededBy(char, char, char, boolean, int, Appendable)} */ public int nextIfNotPrecededBy(char endCh, char escCh, char stopCh1, char stopCh2, char stopCh3, boolean dropEscChars, int count, Appendable dst); /** Read as many characters as match between two inclusive values, up to {@code count}, from the current line * @param lower the lower inclusive character * @param upper the upper inclusive character * @param count the maximum number of matching characters to read, or 0 to * read as many matching characters as possible * @param dst optional destination to store read characters in * @return the number of characters read */ public int nextBetween(char lower, char upper, int count, Appendable dst); }
43.758065
147
0.739526
417538f56cf7eb6f73109f42681a70b5b3c7721d
9,737
/* * 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 com.glaf.matrix.data.query; import java.util.List; import com.glaf.core.query.BaseQuery; public class TableColumnQuery extends BaseQuery { private static final long serialVersionUID = 1L; protected String columnName; protected String columnNameLike; protected List<String> columnNames; protected String discriminator; protected String name; protected String namedColumnSetId; protected String namedColumnSetIdLike; protected List<String> namedColumnSetIds; protected String nameLike; protected String tableName; protected String tableNameLike; protected List<String> tableNames; protected String tableId; protected List<String> tableIds; protected String targetId; protected String titleLike; public TableColumnQuery() { } public TableColumnQuery columnName(String columnName) { if (columnName == null) { throw new RuntimeException("columnName is null"); } this.columnName = columnName; return this; } public TableColumnQuery columnNameLike(String columnNameLike) { if (columnNameLike == null) { throw new RuntimeException("columnName is null"); } this.columnNameLike = columnNameLike; return this; } public TableColumnQuery columnNames(List<String> columnNames) { if (columnNames == null) { throw new RuntimeException("columnNames is empty "); } this.columnNames = columnNames; return this; } public TableColumnQuery discriminator(String discriminator) { if (discriminator == null) { throw new RuntimeException("discriminator is null"); } this.discriminator = discriminator; return this; } public String getColumnName() { return columnName; } public String getColumnNameLike() { if (columnNameLike != null && columnNameLike.trim().length() > 0) { if (!columnNameLike.startsWith("%")) { columnNameLike = "%" + columnNameLike; } if (!columnNameLike.endsWith("%")) { columnNameLike = columnNameLike + "%"; } } return columnNameLike; } public List<String> getColumnNames() { return columnNames; } public String getDiscriminator() { return discriminator; } public String getName() { return name; } public String getNamedColumnSetId() { return namedColumnSetId; } public String getNamedColumnSetIdLike() { if (namedColumnSetIdLike != null && namedColumnSetIdLike.trim().length() > 0) { if (!namedColumnSetIdLike.startsWith("%")) { namedColumnSetIdLike = "%" + namedColumnSetIdLike; } if (!namedColumnSetIdLike.endsWith("%")) { namedColumnSetIdLike = namedColumnSetIdLike + "%"; } } return namedColumnSetIdLike; } public List<String> getNamedColumnSetIds() { return namedColumnSetIds; } public String getNameLike() { if (nameLike != null && nameLike.trim().length() > 0) { if (!nameLike.startsWith("%")) { nameLike = "%" + nameLike; } if (!nameLike.endsWith("%")) { nameLike = nameLike + "%"; } } return nameLike; } public String getOrderBy() { if (sortField != null) { String a_x = " asc "; if (getSortOrder() != null) { a_x = " desc "; } if ("tableName".equals(sortField)) { orderBy = "E.TABLENAME_" + a_x; } if ("columnName".equals(sortField)) { orderBy = "E.COLUMNNAME_" + a_x; } if ("name".equals(sortField)) { orderBy = "E.NAME_" + a_x; } if ("title".equals(sortField)) { orderBy = "E.TITLE_" + a_x; } if ("length".equals(sortField)) { orderBy = "E.LENGTH_" + a_x; } if ("scale".equals(sortField)) { orderBy = "E.SCALE_" + a_x; } if ("precision".equals(sortField)) { orderBy = "E.PRECISION_" + a_x; } if ("ordinal".equals(sortField)) { orderBy = "E.ORDINAL_" + a_x; } if ("javaType".equals(sortField)) { orderBy = "E.JAVATYPE_" + a_x; } } return orderBy; } public String getSortField() { return sortField; } public String getSortOrder() { return sortOrder; } public String getTableId() { return tableId; } public List<String> getTableIds() { return tableIds; } public String getTableName() { return tableName; } public String getTableNameLike() { if (tableNameLike != null && tableNameLike.trim().length() > 0) { if (!tableNameLike.startsWith("%")) { tableNameLike = "%" + tableNameLike; } if (!tableNameLike.endsWith("%")) { tableNameLike = tableNameLike + "%"; } } return tableNameLike; } public List<String> getTableNames() { return tableNames; } public String getTargetId() { return targetId; } public String getTitleLike() { if (titleLike != null && titleLike.trim().length() > 0) { if (!titleLike.startsWith("%")) { titleLike = "%" + titleLike; } if (!titleLike.endsWith("%")) { titleLike = titleLike + "%"; } } return titleLike; } @Override public void initQueryColumns() { super.initQueryColumns(); addColumn("id", "ID_"); addColumn("tableName", "TABLENAME_"); addColumn("columnName", "COLUMNNAME_"); addColumn("name", "NAME_"); addColumn("title", "TITLE_"); addColumn("length", "LENGTH_"); addColumn("scale", "SCALE_"); addColumn("precision", "PRECISION_"); addColumn("nullable", "NULLABLE_"); addColumn("ordinal", "ORDINAL_"); addColumn("javaType", "JAVATYPE_"); } public TableColumnQuery name(String name) { if (name == null) { throw new RuntimeException("name is null"); } this.name = name; return this; } public TableColumnQuery namedColumnSetId(String namedColumnSetId) { if (namedColumnSetId == null) { throw new RuntimeException("namedColumnSetId is null"); } this.namedColumnSetId = namedColumnSetId; return this; } public TableColumnQuery namedColumnSetIdLike(String namedColumnSetIdLike) { if (namedColumnSetIdLike == null) { throw new RuntimeException("namedColumnSetId is null"); } this.namedColumnSetIdLike = namedColumnSetIdLike; return this; } public TableColumnQuery namedColumnSetIds(List<String> namedColumnSetIds) { if (namedColumnSetIds == null) { throw new RuntimeException("namedColumnSetIds is empty "); } this.namedColumnSetIds = namedColumnSetIds; return this; } public TableColumnQuery nameLike(String nameLike) { if (nameLike == null) { throw new RuntimeException("name is null"); } this.nameLike = nameLike; return this; } public void setColumnName(String columnName) { this.columnName = columnName; } public void setColumnNameLike(String columnNameLike) { this.columnNameLike = columnNameLike; } public void setColumnNames(List<String> columnNames) { this.columnNames = columnNames; } public void setDiscriminator(String discriminator) { this.discriminator = discriminator; } public void setName(String name) { this.name = name; } public void setNamedColumnSetId(String namedColumnSetId) { this.namedColumnSetId = namedColumnSetId; } public void setNamedColumnSetIdLike(String namedColumnSetIdLike) { this.namedColumnSetIdLike = namedColumnSetIdLike; } public void setNamedColumnSetIds(List<String> namedColumnSetIds) { this.namedColumnSetIds = namedColumnSetIds; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public void setSortField(String sortField) { this.sortField = sortField; } public void setTableId(String tableId) { this.tableId = tableId; } public void setTableIds(List<String> tableIds) { this.tableIds = tableIds; } public void setTableName(String tableName) { this.tableName = tableName; } public void setTableNameLike(String tableNameLike) { this.tableNameLike = tableNameLike; } public void setTableNames(List<String> tableNames) { this.tableNames = tableNames; } public void setTargetId(String targetId) { this.targetId = targetId; } public void setTitleLike(String titleLike) { this.titleLike = titleLike; } public TableColumnQuery tableId(String tableId) { if (tableId == null) { throw new RuntimeException("tableId is null"); } this.tableId = tableId; return this; } public TableColumnQuery tableName(String tableName) { if (tableName == null) { throw new RuntimeException("tableName is null"); } this.tableName = tableName; return this; } public TableColumnQuery tableNameLike(String tableNameLike) { if (tableNameLike == null) { throw new RuntimeException("tableName is null"); } this.tableNameLike = tableNameLike; return this; } public TableColumnQuery tableNames(List<String> tableNames) { if (tableNames == null) { throw new RuntimeException("tableNames is empty "); } this.tableNames = tableNames; return this; } public TableColumnQuery targetId(String targetId) { if (targetId == null) { throw new RuntimeException("targetId is null"); } this.targetId = targetId; return this; } public TableColumnQuery titleLike(String titleLike) { if (titleLike == null) { throw new RuntimeException("title is null"); } this.titleLike = titleLike; return this; } }
23.690998
81
0.701345
dbc34423f6787c4904b30c9861f391b71e4b40ca
837
package employeeRegister.web.mbeans; import employeeRegister.service.EmployeeService; import javax.enterprise.context.RequestScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import java.io.IOException; @Named @RequestScoped public class RemoveEmployeeBean { private EmployeeService employeeService; public RemoveEmployeeBean() { } @Inject public RemoveEmployeeBean(EmployeeService employeeService) { this.employeeService = employeeService; } public void removeEmployee(String id) throws IOException { this.employeeService.removeEmployee(id); ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); externalContext.redirect("/"); } }
26.15625
97
0.770609
67e197a043be4e1d5f647762bb2215698446a6fd
7,036
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math4.userguide.clustering; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import org.apache.commons.math4.ml.clustering.CentroidCluster; import org.apache.commons.math4.ml.clustering.Clusterable; import org.apache.commons.math4.ml.clustering.KMeansPlusPlusClusterer; import org.apache.commons.math4.userguide.ExampleUtils; import org.apache.commons.math4.userguide.ExampleUtils.ExampleFrame; /** * This example shows how clustering can be applied to images. */ @SuppressWarnings("serial") public class ImageClusteringExample { public static class Display extends ExampleFrame { private BufferedImage referenceImage; private BufferedImage clusterImage; private Raster referenceRaster; private ImagePainter painter; private JSpinner clusterSizeSpinner; public Display() throws Exception { setTitle("Commons-Math: Image Clustering Example"); setSize(900, 350); setLayout(new FlowLayout()); Box bar = Box.createHorizontalBox(); referenceImage = ExampleUtils.resizeImage( ImageIO.read(new File("resources/ColorfulBird.jpg")), 350, 240, BufferedImage.TYPE_INT_RGB); referenceRaster = referenceImage.getData(); clusterImage = new BufferedImage(referenceImage.getWidth(), referenceImage.getHeight(), BufferedImage.TYPE_INT_RGB); JLabel picLabel = new JLabel(new ImageIcon(referenceImage)); bar.add(picLabel); painter = new ImagePainter(clusterImage.getWidth(), clusterImage.getHeight()); bar.add(painter); JPanel controlBox = new JPanel(); controlBox.setLayout(new GridLayout(5, 1)); controlBox.setBorder(BorderFactory.createLineBorder(Color.black, 1)); JPanel sizeBox = new JPanel(); JLabel sizeLabel = new JLabel("Clusters:"); sizeBox.add(sizeLabel); SpinnerNumberModel model = new SpinnerNumberModel(3, 2, 10, 1); clusterSizeSpinner = new JSpinner(model); sizeLabel.setLabelFor(clusterSizeSpinner); sizeBox.add(clusterSizeSpinner); controlBox.add(sizeBox, BorderLayout.NORTH); JButton startButton = new JButton("Cluster"); startButton.setActionCommand("cluster"); controlBox.add(startButton, BorderLayout.CENTER); bar.add(controlBox); add(bar); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clusterImage(); } }); } private void clusterImage() { List<PixelClusterable> pixels = new ArrayList<PixelClusterable>(); for (int row = 0; row < referenceImage.getHeight(); row++) { for (int col = 0; col < referenceImage.getWidth(); col++) { pixels.add(new PixelClusterable(col, row)); } } int clusterSize = ((Number) clusterSizeSpinner.getValue()).intValue(); KMeansPlusPlusClusterer<PixelClusterable> clusterer = new KMeansPlusPlusClusterer<PixelClusterable>(clusterSize); List<CentroidCluster<PixelClusterable>> clusters = clusterer.cluster(pixels); WritableRaster raster = clusterImage.getRaster(); for (CentroidCluster<PixelClusterable> cluster : clusters) { double[] color = cluster.getCenter().getPoint(); for (PixelClusterable pixel : cluster.getPoints()) { raster.setPixel(pixel.x, pixel.y, color); } } Display.this.repaint(); } private class PixelClusterable implements Clusterable { private final int x; private final int y; private double[] color; public PixelClusterable(int x, int y) { this.x = x; this.y = y; this.color = null; } @Override public double[] getPoint() { if (color == null) { color = referenceRaster.getPixel(x, y, (double[]) null); } return color; } } private class ImagePainter extends Component { private int width; private int height; public ImagePainter(int width, int height) { this.width = width; this.height = height; } public Dimension getPreferredSize() { return new Dimension(width, height); } @Override public Dimension getMinimumSize() { return getPreferredSize(); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } public void paint(Graphics g) { g.drawImage(clusterImage, 0, 0, this); } } } public static void main(String[] args) throws Exception { ExampleUtils.showExampleFrame(new Display()); } }
34.490196
90
0.603184
70cf8df0f7121b5c09fb9c5068720e01d78fb2d7
1,453
package net.minestom.script.utils; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.minestom.server.entity.Entity; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.Player; import org.apache.commons.text.WordUtils; import org.jetbrains.annotations.NotNull; import java.util.Objects; public class EntityUtils { @NotNull public static Component getDisplayComponent(@NotNull Entity entity) { Component component; if (entity instanceof Player) { final Player player = (Player) entity; component = Objects.requireNonNullElseGet(player.getDisplayName(), () -> Component.text(player.getUsername(), NamedTextColor.GRAY)); } else { final EntityType entityType = entity.getEntityType(); final String displayableEntityType = getDisplayableEntityType(entityType); component = Component.text(displayableEntityType, NamedTextColor.GRAY) .append(Component.text("[" + entity.getUuid() + "]", NamedTextColor.DARK_GRAY)); } return component.hoverEvent(entity).insertion(entity.getUuid().toString()); } @NotNull public static String getDisplayableEntityType(@NotNull EntityType entityType) { final String name = entityType.toString().replace("_", ""); return WordUtils.capitalizeFully(name); } }
38.236842
100
0.701308
08c136e89c2a49d3f224590bb324db098939a58a
5,120
/* * Copyright (C) 2020 ActiveJ LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.activej.csp.binary; import io.activej.async.function.AsyncSupplier; import io.activej.async.process.AbstractAsyncCloseable; import io.activej.async.process.AsyncCloseable; import io.activej.bytebuf.ByteBuf; import io.activej.bytebuf.ByteBufs; import io.activej.common.exception.MalformedDataException; import io.activej.common.exception.TruncatedDataException; import io.activej.common.exception.UnexpectedDataException; import io.activej.csp.ChannelSupplier; import io.activej.promise.Promise; import org.jetbrains.annotations.NotNull; import java.util.Iterator; import java.util.List; import static io.activej.common.function.FunctionEx.identity; public abstract class BinaryChannelSupplier extends AbstractAsyncCloseable { protected final ByteBufs bufs; protected BinaryChannelSupplier(ByteBufs bufs) { this.bufs = bufs; } protected BinaryChannelSupplier() { this.bufs = new ByteBufs(); } public ByteBufs getBufs() { return bufs; } public abstract Promise<Void> needMoreData(); public abstract Promise<Void> endOfStream(); public static BinaryChannelSupplier ofList(List<ByteBuf> iterable) { return of(ChannelSupplier.ofList(iterable)); } public static BinaryChannelSupplier ofIterator(Iterator<ByteBuf> iterator) { return of(ChannelSupplier.ofIterator(iterator)); } public static BinaryChannelSupplier of(ChannelSupplier<ByteBuf> input) { return new BinaryChannelSupplier() { @Override public Promise<Void> needMoreData() { return input.get() .map(buf -> { if (buf != null) { bufs.add(buf); return null; } else { throw new TruncatedDataException("Unexpected end-of-stream"); } }); } @Override public Promise<Void> endOfStream() { if (!bufs.isEmpty()) { bufs.recycle(); Exception exception = new UnexpectedDataException("Unexpected data after end-of-stream"); input.closeEx(exception); return Promise.ofException(exception); } return input.get() .map(buf -> { if (buf == null) { return null; } else { buf.recycle(); Exception exception = new UnexpectedDataException("Unexpected data after end-of-stream"); input.closeEx(exception); throw exception; } }); } @Override protected void onClosed(@NotNull Exception e) { input.closeEx(e); } }; } public static BinaryChannelSupplier ofProvidedBufs(ByteBufs bufs, AsyncSupplier<Void> get, AsyncSupplier<Void> complete, AsyncCloseable closeable) { return new BinaryChannelSupplier(bufs) { @Override public Promise<Void> needMoreData() { return get.get(); } @Override public Promise<Void> endOfStream() { return complete.get(); } @Override protected void onClosed(@NotNull Exception e) { closeable.closeEx(e); } }; } public final <T> Promise<T> decode(ByteBufsDecoder<T> decoder) { return doDecode(decoder, this); } private @NotNull <T> Promise<T> doDecode(ByteBufsDecoder<T> decoder, AsyncCloseable closeable) { while (true) { if (!bufs.isEmpty()) { T result; try { result = decoder.tryDecode(bufs); } catch (MalformedDataException e) { closeEx(e); return Promise.ofException(e); } if (result != null) { return Promise.of(result); } } Promise<Void> moreDataPromise = needMoreData(); if (moreDataPromise.isResult()) continue; return moreDataPromise .whenException(closeable::closeEx) .then(() -> doDecode(decoder, closeable)); } } public final <T> Promise<T> decodeRemaining(ByteBufsDecoder<T> decoder) { return decode(decoder) .then(result -> { if (!bufs.isEmpty()) { Exception exception = new UnexpectedDataException("Unexpected data after end-of-stream"); closeEx(exception); throw exception; } return endOfStream().map($ -> result); }); } public final <T> ChannelSupplier<T> decodeStream(ByteBufsDecoder<T> decoder) { return ChannelSupplier.of( () -> doDecode(decoder, e -> { if (e instanceof TruncatedDataException && bufs.isEmpty()) return; closeEx(e); }) .map(identity(), e -> { if (e instanceof TruncatedDataException && bufs.isEmpty()) return null; throw e; }), this); } @SuppressWarnings("UnusedReturnValue") public Promise<Void> bindTo(BinaryChannelInput input) { return input.set(this); } @Override protected void onCleanup() { bufs.recycle(); } }
27.089947
97
0.69043
3243e9360746f6200496c55010508b57f743adaf
1,190
package com.crud.tasks.trello.validator; import com.crud.tasks.domain.TrelloBoard; import com.crud.tasks.domain.TrelloCard; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.List; import static java.util.stream.Collectors.toList; @Component public class TrelloValidator { private static final Logger LOGGER = LoggerFactory.getLogger(TrelloValidator.class); public List<TrelloBoard> validateTrelloBoards(final List<TrelloBoard> trelloBoards) { LOGGER.info("Starting filtering boards.."); List<TrelloBoard> filteredBoards = trelloBoards.stream() .filter(trelloBoard -> !trelloBoard.getName().equalsIgnoreCase("test")) .collect(toList()); LOGGER.info("Boards has been filtered. Current list size: " + filteredBoards.size()); return filteredBoards; } public void validateCard(final TrelloCard trelloCard) { if (trelloCard.getName().contains("test")) { LOGGER.info("Someone is testing my application"); } else { LOGGER.info("Seems that my application is used in proper way."); } } }
34
93
0.701681
90a6682352b783b9663490f8a96add57a0adf9b3
8,739
/* * Copyright 2019 IIT Software GmbH * * IIT Software GmbH licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.swiftmq.impl.queue.standard.cluster; import com.swiftmq.impl.queue.standard.SwiftletContext; import com.swiftmq.jms.MessageImpl; import com.swiftmq.jms.QueueImpl; import com.swiftmq.jms.XidImpl; import com.swiftmq.swiftlet.queue.AbstractQueue; import com.swiftmq.swiftlet.queue.QueueException; import com.swiftmq.swiftlet.store.CompositeStoreTransaction; import com.swiftmq.tools.concurrent.AsyncCompletionCallback; public class ClusteredQueue extends AbstractQueue { SwiftletContext ctx = null; DispatchPolicy dispatchPolicy = null; CompositeStoreTransaction compositeTx = null; public ClusteredQueue(SwiftletContext ctx, DispatchPolicy dispatchPolicy) { this.ctx = ctx; this.dispatchPolicy = dispatchPolicy; if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/created"); } public AbstractQueue selectBaseQueue() { String queueName = dispatchPolicy.getNextReceiveQueue(); if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/selectBaseQueue, nextReceiveQueue=" + queueName); if (queueName == null) return super.selectBaseQueue(); return ctx.queueManager.getQueueForInternalUse(queueName); } public boolean hasReceiver(MessageImpl message) { return false; } public void lockQueue(Object txId) { ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/lockQueue, cTxId=" + cTxId); cTxId.lockQueue(); } public void unlockQueue(Object txId, boolean markAsyncActive) { ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/unlockQueue, cTxId=" + cTxId); cTxId.unlockQueue(markAsyncActive); } public void unmarkAsyncActive(Object txId) { ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/unmarkAsyncActive, cTxId=" + cTxId); cTxId.unmarkAsyncActive(); } public void setCompositeStoreTransaction(Object txId, CompositeStoreTransaction ct) { ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/setCompositeStoreTransaction, cTxId=" + cTxId); cTxId.setCompositeStoreTransaction(ct); } public CompositeStoreTransaction getCompositeStoreTransaction(Object txId) { ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; return cTxId.getCompositeStoreTransaction(); } public Object createPullTransaction() throws QueueException { throw new QueueException("Operation not supported!"); } public Object createPushTransaction() throws QueueException { ClusteredTransactionId txId = null; if (dispatchPolicy.isMessageBasedDispatch()) { txId = new ClusteredTransactionId(ctx, true); } else { String queueName = dispatchPolicy.getNextSendQueue(); if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/createPushTransaction, nextSendQueue=" + queueName); if (queueName == null) throw new QueueException("Unable to select a physical destination queue for this clustered queue!"); AbstractQueue queue = ctx.queueManager.getQueueForInternalUse(queueName, true); txId = new ClusteredTransactionId(ctx, queue, queue.createPushTransaction(), new QueueImpl(queueName)); } return txId; } public void putMessage(Object txId, MessageImpl message) throws QueueException { ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; if (cTxId.isMessageBasedDispatch()) { if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/putMessage, message based dispatch ..."); String queueName = dispatchPolicy.getNextSendQueue(message); if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/putMessage, nextSendQueue=" + queueName); if (queueName == null) throw new QueueException("Unable to select a physical destination queue for this clustered queue!"); try { cTxId.putMessage(queueName, message); } catch (Exception e) { throw new QueueException(e.toString()); } } else { try { cTxId.putMessage(message); } catch (Exception e) { throw new QueueException(e.toString()); } } } public void commit(Object txId) throws QueueException { if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/commit, txId=" + txId); ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; ((ClusteredQueueFlowController) getFlowController()).setLastDelay(cTxId.commit()); } public void commit(final Object txId, AsyncCompletionCallback callback) { if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/commit (callback), txId=" + txId); final ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; cTxId.commit(new AsyncCompletionCallback(callback) { public synchronized void done(boolean success) { Long fcDelay = (Long) getResult(); if (fcDelay != null) { if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/commit (callback), txId=" + txId + ", newDelay=" + fcDelay); ((ClusteredQueueFlowController) getFlowController()).setLastDelay(fcDelay.longValue()); } } }); } public void rollback(Object txId, boolean b) throws QueueException { if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/rollback, txId=" + txId + ", b=" + b); ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; cTxId.rollback(b); } public void rollback(Object txId, boolean b, AsyncCompletionCallback callback) { if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/rollback, txId=" + txId + ", b=" + b); ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; cTxId.rollback(b, callback); } public void prepare(Object txId, XidImpl xid) throws QueueException { if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/prepare, txId=" + txId + ", xid=" + xid); ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; cTxId.prepare(xid); } public void commit(Object txId, XidImpl xid) throws QueueException { if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/commit, txId=" + txId + ", xid=" + xid); ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; ((ClusteredQueueFlowController) getFlowController()).setLastDelay(cTxId.commit(xid)); } public void rollback(Object txId, XidImpl xid, boolean b) throws QueueException { if (ctx.queueSpace.enabled) ctx.queueSpace.trace(getQueueName(), toString() + "/commit, txId=" + txId + ", xid=" + xid + ", b=" + b); ClusteredTransactionId cTxId = (ClusteredTransactionId) txId; cTxId.rollback(xid, b); } public void deleteContent() throws QueueException { } public void startQueue() throws QueueException { } public void stopQueue() throws QueueException { } public String toString() { return "clustered queue, name=" + getQueueName(); } }
43.695
136
0.665065
b0fc95e6acecd85123ec3f5a414ba3d55ff43488
46,086
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Argument; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.provider.impl.DemoServiceImpl; import org.apache.dubbo.registry.client.migration.MigrationInvoker; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.listener.ListenerInvokerWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker; import org.apache.dubbo.rpc.protocol.injvm.InjvmProtocol; import org.apache.curator.test.TestingServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.BROADCAST_CLUSTER; import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LIVENESS_PROBE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METADATA_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PORT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METRICS_PORT; import static org.apache.dubbo.common.constants.CommonConstants.METRICS_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY; import static org.apache.dubbo.common.constants.CommonConstants.READINESS_PROBE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFER_ASYNC_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFER_BACKGROUND_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFER_THREAD_NUM_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.STARTUP_PROBE; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.URL_MERGE_PROCESSOR_KEY; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST; import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PUBLISH_INSTANCE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PUBLISH_INTERFACE_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.rpc.Constants.DEFAULT_STUB_EVENT; import static org.apache.dubbo.rpc.Constants.LOCAL_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.apache.dubbo.rpc.Constants.SCOPE_KEY; import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; public class ReferenceConfigTest { private TestingServer zkServer; private String zkUrl; private String registryUrl; @BeforeEach public void setUp() throws Exception { DubboBootstrap.reset(); int zkServerPort = NetUtils.getAvailablePort(NetUtils.getRandomPort()); this.zkServer = new TestingServer(zkServerPort, true); this.zkServer.start(); this.zkUrl = "zookeeper://localhost:" + zkServerPort; this.registryUrl = "registry://localhost:" + zkServerPort + "?registry=zookeeper"; // preload ReferenceConfig preloadReferenceConfig = new ReferenceConfig(); ApplicationModel.defaultModel().getApplicationConfigManager(); DubboBootstrap.getInstance(); } @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); zkServer.stop(); Mockito.framework().clearInlineMocks(); } /** * Test whether the configuration required for the aggregation service reference meets expectations */ @Test public void testAppendConfig() { ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); applicationConfig.setVersion("v1"); applicationConfig.setOwner("owner1"); applicationConfig.setOrganization("bu1"); applicationConfig.setArchitecture("architecture1"); applicationConfig.setEnvironment("test"); applicationConfig.setCompiler("javassist"); applicationConfig.setLogger("log4j"); applicationConfig.setDumpDirectory("/"); applicationConfig.setQosEnable(false); applicationConfig.setQosHost("127.0.0.1"); applicationConfig.setQosPort(77777); applicationConfig.setQosAcceptForeignIp(false); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); applicationConfig.setParameters(parameters); applicationConfig.setShutwait("5"); applicationConfig.setMetadataType("local"); applicationConfig.setRegisterConsumer(false); applicationConfig.setRepository("repository1"); applicationConfig.setEnableFileCache(false); applicationConfig.setPublishInstance(false); applicationConfig.setPublishInterface(false); applicationConfig.setProtocol("dubbo"); applicationConfig.setMetadataServicePort(88888); applicationConfig.setLivenessProbe("livenessProbe"); applicationConfig.setReadinessProbe("readinessProb"); applicationConfig.setStartupProbe("startupProbe"); ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setClient("netty"); referenceConfig.setGeneric(Boolean.FALSE.toString()); referenceConfig.setProtocol("dubbo"); referenceConfig.setInit(true); referenceConfig.setLazy(false); referenceConfig.setInjvm(false); referenceConfig.setReconnect("reconnect"); referenceConfig.setSticky(false); referenceConfig.setStub(DEFAULT_STUB_EVENT); referenceConfig.setRouter("default"); referenceConfig.setReferAsync(true); MonitorConfig monitorConfig = new MonitorConfig(); applicationConfig.setMonitor(monitorConfig); MetricsConfig metricsConfig = new MetricsConfig(); metricsConfig.setProtocol("metricProtocol"); metricsConfig.setPort("55555"); ModuleConfig moduleConfig = new ModuleConfig(); moduleConfig.setMonitor("default"); moduleConfig.setName("module1"); moduleConfig.setOrganization("application1"); moduleConfig.setVersion("v1"); moduleConfig.setOwner("owner1"); ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setClient("netty"); consumerConfig.setThreadpool("fixed"); consumerConfig.setCorethreads(200); consumerConfig.setQueues(500); consumerConfig.setThreads(300); consumerConfig.setShareconnections(10); consumerConfig.setUrlMergeProcessor("default"); consumerConfig.setReferThreadNum(20); consumerConfig.setReferBackground(false); referenceConfig.setConsumer(consumerConfig); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); methodConfig.setStat(1); methodConfig.setRetries(0); methodConfig.setExecutes(10); methodConfig.setDeprecated(false); methodConfig.setSticky(false); methodConfig.setReturn(false); methodConfig.setService("service"); methodConfig.setServiceId(DemoService.class.getName()); methodConfig.setParentPrefix("demo"); referenceConfig.setMethods(Collections.singletonList(methodConfig)); referenceConfig.setInterface(DemoService.class); referenceConfig.getInterfaceClass(); referenceConfig.setCheck(false); RegistryConfig registry = new RegistryConfig(); registry.setAddress(zkUrl); applicationConfig.setRegistries(Collections.singletonList(registry)); applicationConfig.setRegistryIds(registry.getId()); moduleConfig.setRegistries(Collections.singletonList(registry)); referenceConfig.setRegistry(registry); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); dubboBootstrap.application(applicationConfig) .reference(referenceConfig) .registry(registry) .metrics(metricsConfig) .module(moduleConfig) .initialize(); referenceConfig.init(); ServiceMetadata serviceMetadata = referenceConfig.getServiceMetadata(); // verify additional side parameter Assertions.assertEquals(CONSUMER_SIDE, serviceMetadata.getAttachments().get(SIDE_KEY)); // verify additional interface parameter Assertions.assertEquals(DemoService.class.getName(), serviceMetadata.getAttachments().get(INTERFACE_KEY)); // verify additional metadata-type parameter Assertions.assertEquals(DEFAULT_METADATA_STORAGE_TYPE, serviceMetadata.getAttachments().get(METADATA_KEY)); // verify additional register.ip parameter Assertions.assertEquals(NetUtils.getLocalHost(), serviceMetadata.getAttachments().get(REGISTER_IP_KEY)); // verify additional runtime parameters Assertions.assertEquals(Version.getProtocolVersion(), serviceMetadata.getAttachments().get(DUBBO_VERSION_KEY)); Assertions.assertEquals(Version.getVersion(), serviceMetadata.getAttachments().get(RELEASE_KEY)); Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(TIMESTAMP_KEY)); Assertions.assertEquals(String.valueOf(ConfigUtils.getPid()), serviceMetadata.getAttachments().get(PID_KEY)); // verify additional metric config Assertions.assertEquals(metricsConfig.getProtocol(), serviceMetadata.getAttachments().get(METRICS_PROTOCOL)); Assertions.assertEquals(metricsConfig.getPort(), serviceMetadata.getAttachments().get(METRICS_PORT)); // verify additional application config Assertions.assertEquals(applicationConfig.getName(), serviceMetadata.getAttachments().get(APPLICATION_KEY)); Assertions.assertEquals(applicationConfig.getOwner(), serviceMetadata.getAttachments().get("owner")); Assertions.assertEquals(applicationConfig.getVersion(), serviceMetadata.getAttachments().get(APPLICATION_VERSION_KEY)); Assertions.assertEquals(applicationConfig.getOrganization(), serviceMetadata.getAttachments().get("organization")); Assertions.assertEquals(applicationConfig.getArchitecture(), serviceMetadata.getAttachments().get("architecture")); Assertions.assertEquals(applicationConfig.getEnvironment(), serviceMetadata.getAttachments().get("environment")); Assertions.assertEquals(applicationConfig.getCompiler(), serviceMetadata.getAttachments().get("compiler")); Assertions.assertEquals(applicationConfig.getLogger(), serviceMetadata.getAttachments().get("logger")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registries")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registry.ids")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("monitor")); Assertions.assertEquals(applicationConfig.getDumpDirectory(), serviceMetadata.getAttachments().get(DUMP_DIRECTORY)); Assertions.assertEquals(applicationConfig.getQosEnable().toString(), serviceMetadata.getAttachments().get(QOS_ENABLE)); Assertions.assertEquals(applicationConfig.getQosHost(), serviceMetadata.getAttachments().get(QOS_HOST)); Assertions.assertEquals(applicationConfig.getQosPort().toString(), serviceMetadata.getAttachments().get(QOS_PORT)); Assertions.assertEquals(applicationConfig.getQosAcceptForeignIp().toString(), serviceMetadata.getAttachments().get(ACCEPT_FOREIGN_IP)); Assertions.assertEquals(applicationConfig.getParameters().get("key1"), serviceMetadata.getAttachments().get("key1")); Assertions.assertEquals(applicationConfig.getParameters().get("key2"), serviceMetadata.getAttachments().get("key2")); Assertions.assertEquals(applicationConfig.getShutwait(), serviceMetadata.getAttachments().get("shutwait")); Assertions.assertEquals(applicationConfig.getMetadataType(), serviceMetadata.getAttachments().get(METADATA_KEY)); Assertions.assertEquals(applicationConfig.getRegisterConsumer().toString(), serviceMetadata.getAttachments().get("register.consumer")); Assertions.assertEquals(applicationConfig.getRepository(), serviceMetadata.getAttachments().get("repository")); Assertions.assertEquals(applicationConfig.getEnableFileCache().toString(), serviceMetadata.getAttachments().get(REGISTRY_LOCAL_FILE_CACHE_ENABLED)); Assertions.assertEquals(applicationConfig.getPublishInstance().toString(), serviceMetadata.getAttachments().get(REGISTRY_PUBLISH_INSTANCE_KEY)); Assertions.assertEquals(applicationConfig.getPublishInterface().toString(), serviceMetadata.getAttachments().get(REGISTRY_PUBLISH_INTERFACE_KEY)); Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(REGISTRY_PUBLISH_INTERFACE_KEY)); Assertions.assertEquals(applicationConfig.getMetadataServicePort().toString(), serviceMetadata.getAttachments().get(METADATA_SERVICE_PORT_KEY)); Assertions.assertEquals(applicationConfig.getLivenessProbe(), serviceMetadata.getAttachments().get(LIVENESS_PROBE_KEY)); Assertions.assertEquals(applicationConfig.getReadinessProbe(), serviceMetadata.getAttachments().get(READINESS_PROBE_KEY)); Assertions.assertEquals(applicationConfig.getStartupProbe(), serviceMetadata.getAttachments().get(STARTUP_PROBE)); // verify additional module config Assertions.assertEquals(moduleConfig.getName(), serviceMetadata.getAttachments().get("module")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("monitor")); Assertions.assertEquals(moduleConfig.getOrganization(), serviceMetadata.getAttachments().get("module.organization")); Assertions.assertEquals(moduleConfig.getOwner(), serviceMetadata.getAttachments().get("module.owner")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registries")); Assertions.assertEquals(moduleConfig.getVersion(), serviceMetadata.getAttachments().get("module.version")); // verify additional consumer config Assertions.assertEquals(consumerConfig.getClient(), serviceMetadata.getAttachments().get("client")); Assertions.assertEquals(consumerConfig.getThreadpool(), serviceMetadata.getAttachments().get("threadpool")); Assertions.assertEquals(consumerConfig.getCorethreads().toString(), serviceMetadata.getAttachments().get("corethreads")); Assertions.assertEquals(consumerConfig.getQueues().toString(), serviceMetadata.getAttachments().get("queues")); Assertions.assertEquals(consumerConfig.getThreads().toString(), serviceMetadata.getAttachments().get("threads")); Assertions.assertEquals(consumerConfig.getShareconnections().toString(), serviceMetadata.getAttachments().get("shareconnections")); Assertions.assertEquals(consumerConfig.getUrlMergeProcessor(), serviceMetadata.getAttachments().get(URL_MERGE_PROCESSOR_KEY)); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey(REFER_THREAD_NUM_KEY)); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey(REFER_BACKGROUND_KEY)); // verify additional reference config Assertions.assertEquals(referenceConfig.getClient(), serviceMetadata.getAttachments().get("client")); Assertions.assertEquals(referenceConfig.getGeneric(), serviceMetadata.getAttachments().get("generic")); Assertions.assertEquals(referenceConfig.getProtocol(), serviceMetadata.getAttachments().get("protocol")); Assertions.assertEquals(referenceConfig.isInit().toString(), serviceMetadata.getAttachments().get("init")); Assertions.assertEquals(referenceConfig.getLazy().toString(), serviceMetadata.getAttachments().get("lazy")); Assertions.assertEquals(referenceConfig.isInjvm().toString(), serviceMetadata.getAttachments().get("injvm")); Assertions.assertEquals(referenceConfig.getReconnect(), serviceMetadata.getAttachments().get("reconnect")); Assertions.assertEquals(referenceConfig.getSticky().toString(), serviceMetadata.getAttachments().get("sticky")); Assertions.assertEquals(referenceConfig.getStub(), serviceMetadata.getAttachments().get("stub")); Assertions.assertEquals(referenceConfig.getProvidedBy(), serviceMetadata.getAttachments().get("provided-by")); Assertions.assertEquals(referenceConfig.getRouter(), serviceMetadata.getAttachments().get("router")); Assertions.assertEquals(referenceConfig.getReferAsync().toString(), serviceMetadata.getAttachments().get(REFER_ASYNC_KEY)); // verify additional method config Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("name")); Assertions.assertEquals(methodConfig.getStat().toString(), serviceMetadata.getAttachments().get("sayName.stat")); Assertions.assertEquals(methodConfig.getRetries().toString(), serviceMetadata.getAttachments().get("sayName.retries")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.reliable")); Assertions.assertEquals(methodConfig.getExecutes().toString(), serviceMetadata.getAttachments().get("sayName.executes")); Assertions.assertEquals(methodConfig.getDeprecated().toString(), serviceMetadata.getAttachments().get("sayName.deprecated")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.stick")); Assertions.assertEquals(methodConfig.isReturn().toString(), serviceMetadata.getAttachments().get("sayName.return")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.service")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.service.id")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.parent.prefix")); // verify additional revision and methods parameter Assertions.assertEquals(Version.getVersion(referenceConfig.getInterfaceClass(), referenceConfig.getVersion()), serviceMetadata.getAttachments().get(REVISION_KEY)); Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(METHODS_KEY)); Assertions.assertEquals(DemoService.class.getMethods().length, StringUtils.split((String) serviceMetadata.getAttachments().get(METHODS_KEY), ',').length); dubboBootstrap.stop(); } @Test public void testShouldJvmRefer() { Map<String, String> parameters = new HashMap<>(); ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); // verify that if injvm is configured as true, local references should be made referenceConfig.setInjvm(true); Assertions.assertTrue(referenceConfig.shouldJvmRefer(parameters)); // verify that if injvm is configured as false, local references should not be made referenceConfig.setInjvm(false); Assertions.assertFalse(referenceConfig.shouldJvmRefer(parameters)); // verify that if url is configured, local reference should not be made referenceConfig.setInjvm(null); referenceConfig.setUrl("dubbo://127.0.0.1:20880/DemoService"); parameters.put(INTERFACE_KEY, DemoService.class.getName()); Assertions.assertFalse(referenceConfig.shouldJvmRefer(parameters)); parameters.clear(); // verify that if scope is configured as local, local references should be made referenceConfig.setInjvm(null); referenceConfig.setUrl(null); parameters.put(SCOPE_KEY, SCOPE_LOCAL); Assertions.assertTrue(referenceConfig.shouldJvmRefer(parameters)); parameters.clear(); // verify that if url protocol is configured as injvm, local references should be made referenceConfig.setInjvm(null); referenceConfig.setUrl(null); parameters.put(LOCAL_PROTOCOL, "true"); Assertions.assertTrue(referenceConfig.shouldJvmRefer(parameters)); parameters.clear(); // verify that if generic is configured as true, local references should not be made referenceConfig.setInjvm(null); referenceConfig.setUrl(null); parameters.put(GENERIC_KEY, "true"); Assertions.assertFalse(referenceConfig.shouldJvmRefer(parameters)); parameters.clear(); // verify that if the service has been exposed, and the cluster is not configured with broadcast, local reference should be made referenceConfig.setInjvm(null); referenceConfig.setUrl(null); ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("dubbo://127.0.0.1/DemoService") .addParameter(INTERFACE_KEY, DemoService.class.getName()); parameters.put(INTERFACE_KEY, DemoService.class.getName()); Exporter<?> exporter = InjvmProtocol.getInjvmProtocol().export(proxy.getInvoker(service, DemoService.class, url)); InjvmProtocol.getInjvmProtocol().getExporterMap().put(DemoService.class.getName(), exporter); Assertions.assertTrue(referenceConfig.shouldJvmRefer(parameters)); // verify that if the service has been exposed, and the cluster is configured with broadcast, local reference should not be made parameters.put(CLUSTER_KEY, BROADCAST_CLUSTER); Assertions.assertFalse(referenceConfig.shouldJvmRefer(parameters)); parameters.clear(); InjvmProtocol.getInjvmProtocol().destroy(); } @Test public void testCreateInvokerForLocalRefer() { ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setScope(LOCAL_KEY); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); applicationConfig.setParameters(parameters); referenceConfig.setInterface(DemoService.class); referenceConfig.getInterfaceClass(); referenceConfig.setCheck(false); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); dubboBootstrap.application(applicationConfig) .reference(referenceConfig) .initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof ListenerInvokerWrapper); Assertions.assertTrue(((ListenerInvokerWrapper<?>) referenceConfig.getInvoker()).getInvoker() instanceof InjvmInvoker); URL url = ((ListenerInvokerWrapper<?>) referenceConfig.getInvoker()).getInvoker().getUrl(); Assertions.assertEquals("application1", url.getParameter("application")); Assertions.assertEquals("value1", url.getParameter("key1")); Assertions.assertEquals("value2", url.getParameter("key2")); dubboBootstrap.stop(); } /** * Verify the configuration of the registry protocol for remote reference */ @Test public void testCreateInvokerForRemoteRefer() { ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setGeneric(Boolean.FALSE.toString()); referenceConfig.setProtocol("dubbo"); referenceConfig.setInit(true); referenceConfig.setLazy(false); referenceConfig.setInjvm(false); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); applicationConfig.setParameters(parameters); referenceConfig.refreshed.set(true); referenceConfig.setInterface(DemoService.class); referenceConfig.getInterfaceClass(); referenceConfig.setCheck(false); RegistryConfig registry = new RegistryConfig(); registry.setAddress(zkUrl); applicationConfig.setRegistries(Collections.singletonList(registry)); applicationConfig.setRegistryIds(registry.getId()); referenceConfig.setRegistry(registry); dubboBootstrap .application(applicationConfig) .reference(referenceConfig) .initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof MigrationInvoker); dubboBootstrap.destroy(); } /** * Verify that the registry url is directly configured for remote reference */ @Test public void testCreateInvokerWithRegistryUrlForRemoteRefer() { ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setGeneric(Boolean.FALSE.toString()); referenceConfig.setProtocol("dubbo"); referenceConfig.setInit(true); referenceConfig.setLazy(false); referenceConfig.setInjvm(false); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); applicationConfig.setParameters(parameters); referenceConfig.refreshed.set(true); referenceConfig.setInterface(DemoService.class); referenceConfig.getInterfaceClass(); referenceConfig.setCheck(false); referenceConfig.setUrl(registryUrl); dubboBootstrap .application(applicationConfig) .reference(referenceConfig) .initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof MigrationInvoker); dubboBootstrap.destroy(); } @Test @Disabled("Disabled due to Github Actions environment") public void testInjvm() throws Exception { ApplicationConfig application = new ApplicationConfig(); application.setName("test-protocol-random-port"); application.setEnableFileCache(false); ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(application); RegistryConfig registry = new RegistryConfig(); registry.setAddress(zkUrl); ProtocolConfig protocol = new ProtocolConfig(); protocol.setName("dubbo"); ServiceConfig<DemoService> demoService; demoService = new ServiceConfig<>(); demoService.setInterface(DemoService.class); demoService.setRef(new DemoServiceImpl()); demoService.setRegistry(registry); demoService.setProtocol(protocol); ReferenceConfig<DemoService> rc = new ReferenceConfig<>(); rc.setRegistry(registry); rc.setInterface(DemoService.class.getName()); rc.setScope(SCOPE_REMOTE); try { System.setProperty("java.net.preferIPv4Stack", "true"); demoService.export(); rc.get(); Assertions.assertFalse(LOCAL_PROTOCOL.equalsIgnoreCase( rc.getInvoker().getUrl().getProtocol())); } finally { System.clearProperty("java.net.preferIPv4Stack"); rc.destroy(); demoService.unexport(); } // Manually trigger dubbo resource recycling. DubboBootstrap.getInstance().destroy(); } /** * unit test for dubbo-1765 */ @Test public void test1ReferenceRetry() { ApplicationConfig application = new ApplicationConfig(); application.setName("test-reference-retry"); application.setEnableFileCache(false); ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(application); RegistryConfig registry = new RegistryConfig(); registry.setAddress(zkUrl); ProtocolConfig protocol = new ProtocolConfig(); protocol.setName("injvm"); ReferenceConfig<DemoService> rc = new ReferenceConfig<>(); rc.setRegistry(registry); rc.setInterface(DemoService.class.getName()); boolean success = false; DemoService demoService = null; try { demoService = rc.get(); success = true; } catch (Exception e) { // ignore } Assertions.assertFalse(success); Assertions.assertNull(demoService); try { System.setProperty("java.net.preferIPv4Stack", "true"); ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("dubbo://127.0.0.1/DemoService") .addParameter(INTERFACE_KEY, DemoService.class.getName()); InjvmProtocol.getInjvmProtocol().export(proxy.getInvoker(service, DemoService.class, url)); demoService = rc.get(); success = true; } catch (Exception e) { // ignore } finally { rc.destroy(); InjvmProtocol.getInjvmProtocol().destroy(); System.clearProperty("java.net.preferIPv4Stack"); } Assertions.assertTrue(success); Assertions.assertNotNull(demoService); } @Test public void testMetaData() { ReferenceConfig config = new ReferenceConfig(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); // test merged and override consumer attributes ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setAsync(true); consumerConfig.setActives(10); config.setConsumer(consumerConfig); config.setAsync(false);// override metaData = config.getMetaData(); Assertions.assertEquals(2, metaData.size()); Assertions.assertEquals("" + consumerConfig.getActives(), metaData.get("actives")); Assertions.assertEquals("" + config.isAsync(), metaData.get("async")); } @Test public void testGetPrefixes() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setInterface(DemoService.class); List<String> prefixes = referenceConfig.getPrefixes(); Assertions.assertTrue(prefixes.contains("dubbo.reference." + referenceConfig.getInterface())); long start = System.currentTimeMillis(); for (int i = 0; i < 1000; i++) { referenceConfig.getPrefixes(); } long end = System.currentTimeMillis(); System.out.println("ReferenceConfig get prefixes cost: " + (end - start)); } @Test public void testLargeReferences() throws InterruptedException { int amount = 10000; ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("test-app"); MetadataReportConfig metadataReportConfig = new MetadataReportConfig(); metadataReportConfig.setAddress("metadata://"); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); configCenterConfig.setAddress("diamond://"); testInitReferences(0, amount, applicationConfig, metadataReportConfig, configCenterConfig); ApplicationModel.defaultModel().getApplicationConfigManager().clear(); testInitReferences(0, 1, applicationConfig, metadataReportConfig, configCenterConfig); ApplicationModel.defaultModel().getApplicationConfigManager().clear(); long t1 = System.currentTimeMillis(); int nThreads = 8; ExecutorService executorService = Executors.newFixedThreadPool(nThreads); for (int i = 0; i < nThreads; i++) { int perCount = (int) (1.0 * amount / nThreads); int start = perCount * i; int end = start + perCount; if (i == nThreads - 1) { end = amount; } int finalEnd = end; System.out.println(String.format("start thread %s: range: %s - %s, count: %s", i, start, end, (end - start))); executorService.submit(() -> { testInitReferences(start, finalEnd, applicationConfig, metadataReportConfig, configCenterConfig); }); } executorService.shutdown(); executorService.awaitTermination(100, TimeUnit.SECONDS); long t2 = System.currentTimeMillis(); long cost = t2 - t1; System.out.println("Init large references cost: " + cost + "ms"); Assertions.assertEquals(amount, DubboBootstrap.getInstance().getConfigManager().getReferences().size()); Assertions.assertTrue(cost < 1000, "Init large references too slowly: " + cost); //test equals testSearchReferences(); } private void testSearchReferences() { long t1 = System.currentTimeMillis(); Collection<ReferenceConfigBase<?>> references = DubboBootstrap.getInstance().getConfigManager().getReferences(); List<ReferenceConfigBase<?>> results = references.stream().filter(rc -> rc.equals(references.iterator().next())) .collect(Collectors.toList()); long t2 = System.currentTimeMillis(); long cost = t2 - t1; System.out.println("Search large references cost: " + cost + "ms"); Assertions.assertEquals(1, results.size()); Assertions.assertTrue(cost < 1000, "Search large references too slowly: " + cost); } private long testInitReferences(int start, int end, ApplicationConfig applicationConfig, MetadataReportConfig metadataReportConfig, ConfigCenterConfig configCenterConfig) { // test add large number of references long t1 = System.currentTimeMillis(); try { for (int i = start; i < end; i++) { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setInterface("com.test.TestService" + i); referenceConfig.setApplication(applicationConfig); referenceConfig.setMetadataReportConfig(metadataReportConfig); referenceConfig.setConfigCenter(configCenterConfig); DubboBootstrap.getInstance().reference(referenceConfig); //ApplicationModel.defaultModel().getConfigManager().getConfigCenters(); } } catch (Throwable e) { e.printStackTrace(); } long t2 = System.currentTimeMillis(); return t2 - t1; } @Test public void testConstructWithReferenceAnnotation() throws NoSuchFieldException { Reference reference = getClass().getDeclaredField("innerTest").getAnnotation(Reference.class); ReferenceConfig referenceConfig = new ReferenceConfig(reference); Assertions.assertEquals(1, referenceConfig.getMethods().size()); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getName(), "sayHello"); Assertions.assertEquals(1300, (int) (referenceConfig.getMethods().get(0)).getTimeout()); Assertions.assertEquals(4, (int) (referenceConfig.getMethods().get(0)).getRetries()); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getLoadbalance(), "random"); Assertions.assertEquals(3, (int) (referenceConfig.getMethods().get(0)).getActives()); Assertions.assertEquals(5, (int) (referenceConfig.getMethods().get(0)).getExecutes()); Assertions.assertTrue((referenceConfig.getMethods().get(0)).isAsync()); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getOninvokeMethod(), "i"); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getOnreturnMethod(), "r"); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getOnthrowMethod(), "t"); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getCache(), "c"); } @Test public void testDifferentClassLoader() throws Exception { ApplicationConfig applicationConfig = new ApplicationConfig("TestApp"); ApplicationModel applicationModel = new ApplicationModel(FrameworkModel.defaultModel()); applicationConfig.getConfigManager().setApplication(applicationConfig); ModuleModel moduleModel = new ModuleModel(applicationModel); DemoService demoService = new DemoServiceImpl(); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(DemoService.class); serviceConfig.setRegistry(new RegistryConfig(zkUrl)); serviceConfig.setScopeModel(moduleModel); serviceConfig.setRef(demoService); serviceConfig.export(); String basePath = DemoService.class.getProtectionDomain().getCodeSource().getLocation().getFile(); basePath = java.net.URLDecoder.decode(basePath, "UTF-8"); TestClassLoader classLoader1 = new TestClassLoader(basePath); TestClassLoader classLoader2 = new TestClassLoader(basePath); Class<?> class1 = classLoader1.loadClass(DemoService.class.getName(), false); Class<?> class2 = classLoader2.loadClass(DemoService.class.getName(), false); Assertions.assertNotEquals(class1, class2); ReferenceConfig<DemoService> referenceConfig1 = new ReferenceConfig<>(); referenceConfig1.setInterface(class1); referenceConfig1.setRegistry(new RegistryConfig(zkUrl)); referenceConfig1.setScopeModel(moduleModel); referenceConfig1.setScope("remote"); Object demoService1 = referenceConfig1.get(); for (Class<?> anInterface : demoService1.getClass().getInterfaces()) { Assertions.assertNotEquals(DemoService.class, anInterface); } Assertions.assertTrue(Arrays.stream(demoService1.getClass().getInterfaces()).anyMatch((clazz) -> clazz.getClassLoader().equals(classLoader1))); java.lang.reflect.Method callBean1 = demoService1.getClass().getDeclaredMethod("callInnerClass"); callBean1.setAccessible(true); Object result1 = callBean1.invoke(demoService1); Assertions.assertNotEquals(result1.getClass(), DemoService.InnerClass.class); Assertions.assertEquals(classLoader1, result1.getClass().getClassLoader()); ReferenceConfig<DemoService> referenceConfig2 = new ReferenceConfig<>(); referenceConfig2.setInterface(class2); referenceConfig2.setRegistry(new RegistryConfig(zkUrl)); referenceConfig2.setScopeModel(moduleModel); referenceConfig2.setScope("remote"); Object demoService2 = referenceConfig2.get(); for (Class<?> anInterface : demoService2.getClass().getInterfaces()) { Assertions.assertNotEquals(DemoService.class, anInterface); } Assertions.assertTrue(Arrays.stream(demoService2.getClass().getInterfaces()).anyMatch((clazz) -> clazz.getClassLoader().equals(classLoader2))); java.lang.reflect.Method callBean2 = demoService2.getClass().getDeclaredMethod("callInnerClass"); callBean2.setAccessible(true); Object result2 = callBean2.invoke(demoService2); Assertions.assertNotEquals(callBean1, callBean2); Assertions.assertNotEquals(result2.getClass(), DemoService.InnerClass.class); Assertions.assertEquals(classLoader2, result2.getClass().getClassLoader()); Assertions.assertNotEquals(result1.getClass(), result2.getClass()); applicationModel.destroy(); } @Reference(methods = {@Method(name = "sayHello", timeout = 1300, retries = 4, loadbalance = "random", async = true, actives = 3, executes = 5, deprecated = true, sticky = true, oninvoke = "instance.i", onthrow = "instance.t", onreturn = "instance.r", cache = "c", validation = "v", arguments = {@Argument(index = 24, callback = true, type = "sss")})}) private InnerTest innerTest; private class InnerTest { } private static class TestClassLoader extends ClassLoader { private String basePath; public TestClassLoader(String basePath) { this.basePath = basePath; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { byte[] bytes = loadClassData(name); return defineClass(name, bytes, 0, bytes.length); } catch (Exception e) { throw new ClassNotFoundException(); } } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> loadedClass = this.findLoadedClass(name); if (loadedClass != null) { return loadedClass; } else { try { if (name.startsWith("org.apache.dubbo.config")) { Class<?> aClass = this.findClass(name); if (resolve) { this.resolveClass(aClass); } return aClass; } else { return super.loadClass(name, resolve); } } catch (Exception e) { return super.loadClass(name, resolve); } } } public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; FileInputStream fileInputStream; byte[] classBytes; fileInputStream = new FileInputStream(path); int length = fileInputStream.available(); classBytes = new byte[length]; fileInputStream.read(classBytes); fileInputStream.close(); return classBytes; } } }
49.501611
176
0.709825
0485947716d221d79bf72648603faaa63ca89cc1
2,526
package edu.drexel.se577.grouptwo.viz.visualization; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.WritableRaster; import java.io.File; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Random; import javax.imageio.ImageIO; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import edu.drexel.se577.grouptwo.viz.dataset.Attribute; public class XYScatterPlotFrame extends Visualization.Scatter { private XYScatterPlotFrame() { super("fake", null, new Attribute.Int("X", 0,0),new Attribute.Int("Y", 0,0)); } public static XYDataset createDataset() { XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries series1 = new XYSeries("Object1"); double[] key = new double[25], value = new double[25]; Random generator = new Random(); for(int i = 0; i<25; i++) { key[i] = i; value[i]=generator.nextDouble(); series1.add(key[i], value[i]); } dataset.addSeries(series1); return dataset; } private static File createChartPanel() { String chartTitle = "Object1 XY Scatter Plot"; String xAxisLabel = "Key"; String yAxisLabel = "Value"; XYDataset dataset = createDataset(); JFreeChart chart = ChartFactory.createXYAreaChart(chartTitle, xAxisLabel, yAxisLabel, dataset); int width = 500; int height = 300; File file = null; try { file = new File("xyScatterTest.png"); ChartUtilities.saveChartAsPNG(file, chart, width, height); }catch(Exception e) { e.printStackTrace(); } return file; } @Override public List<DataPoint> data() { // TODO: implement return Collections.emptyList(); } @Override public Visualization.Image render() { // TODO Auto-generated method stub File file = createChartPanel(); BufferedImage bufferedImage; ImageImpl image = null; try { bufferedImage = ImageIO.read(file); WritableRaster raster = bufferedImage .getRaster(); DataBufferByte data = (DataBufferByte) raster.getDataBuffer(); image = new ImageImpl("png", data.getData()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return image; } @Override public String getName() { // TODO Auto-generated method stub return null; } }
26.3125
97
0.713381
3aa3216ef3bc43e40a2fa93d6fc835ac10b6a474
4,663
/* * This file is part of Velocity Punishment, which is licensed under the MIT license. * * Copyright (c) 2022 JvstvsHD * * 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.jvstvshd.velocitypunishment.api.punishment.util; import org.jetbrains.annotations.NotNull; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; /** * An interface used to retrieve player names und uuids used for storing them in a database. * To retrieve a player's uuid, for example, there are three different ways:<br> * 1.: {@link #getPlayerUuid(String)}: returns the uuid of the player via {@link Optional} or {@link Optional#empty()} if this player is not online/cached/etc.<br> * 2.: {@link #queryPlayerUuid(String, Executor)} queries the player uuid via the mojang api or some internal methods.<br> * 3.: {@link #getOrQueryPlayerName(UUID, Executor)}: a combination of the first two possibilities. If the Optional returned by {@link #getPlayerUuid(String)} was empty, * {@link #getOrQueryPlayerUuid(String, Executor)} is called. The result of this operation will be returned. */ public interface PlayerResolver { /** * Retrieves the player's name via {@link com.velocitypowered.api.proxy.ProxyServer#getPlayer(UUID)}, a caching mechanism or related things. * * @param uuid the uuid of the player * @return the name, or {@link Optional#empty()} */ Optional<String> getPlayerName(@NotNull UUID uuid); /** * Queries the player's name, for example through the Mojang API * * @param uuid the uuid of the player * @param executor an executor to compute async operations * @return a {@link CompletableFuture} being completed with the player's name or null, if not found. */ CompletableFuture<String> queryPlayerName(@NotNull UUID uuid, @NotNull Executor executor); /** * At first, {@link #getPlayerName(UUID)} is invoked. If the result is empty, the result of {@link #queryPlayerName(UUID, Executor)} will be returned. * * @param uuid the uuid of the player * @param executor an executor to compute async operations * @return a {@link CompletableFuture} being completed with the player's name or null, if not found. */ CompletableFuture<String> getOrQueryPlayerName(@NotNull UUID uuid, @NotNull Executor executor); /** * Retrieves the player's uuid via {@link com.velocitypowered.api.proxy.ProxyServer#getPlayer(String)}, a caching mechanism or related things. * * @param name the name of the player * @return the name, or {@link Optional#empty()} */ Optional<UUID> getPlayerUuid(@NotNull String name); /** * Queries the player's uuid, for example through the Mojang API * * @param name the name of the player * @param executor an executor to compute async operations * @return a {@link CompletableFuture} being completed with the player's uuid or null, if not found. */ CompletableFuture<UUID> queryPlayerUuid(@NotNull String name, @NotNull Executor executor); /** * At first, {@link #getPlayerUuid(String)} is invoked. If the result is empty, the result of {@link #queryPlayerUuid(String, Executor)} will be returned. * * @param name the uuid of the player * @param executor an executor to compute async operations * @return a {@link CompletableFuture} being completed with the player's name or null, if not found. */ CompletableFuture<UUID> getOrQueryPlayerUuid(@NotNull String name, @NotNull Executor executor); }
48.572917
169
0.722282
07f2f33110d6b53773d36450904be66d6862bfd4
3,276
/* * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.io.File; import java.io.FileOutputStream; import jdk.internal.org.objectweb.asm.ClassWriter; import jdk.internal.org.objectweb.asm.MethodVisitor; import static jdk.internal.org.objectweb.asm.Opcodes.*; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.process.OutputAnalyzer; /* * @test TestMultiANewArray * @bug 8038076 * @library /test/lib * @modules java.base/jdk.internal.org.objectweb.asm * java.base/jdk.internal.misc * java.management * @compile -XDignore.symbol.file TestMultiANewArray.java * @run driver TestMultiANewArray 49 * @run driver TestMultiANewArray 50 * @run driver TestMultiANewArray 51 * @run driver TestMultiANewArray 52 */ public class TestMultiANewArray { public static void main(String... args) throws Exception { int cfv = Integer.parseInt(args[0]); writeClassFile(cfv); System.err.println("Running with cfv: " + cfv); ProcessBuilder pb = ProcessTools.createTestJvm("-cp", ".", "ClassFile"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("VerifyError"); output.shouldHaveExitValue(1); } public static void writeClassFile(int cfv) throws Exception { ClassWriter cw = new ClassWriter(0); MethodVisitor mv; cw.visit(cfv, ACC_PUBLIC + ACC_SUPER, "ClassFile", null, "java/lang/Object", null); mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); mv.visitCode(); mv.visitInsn(ICONST_1); mv.visitInsn(ICONST_2); mv.visitMultiANewArrayInsn("[I", 2); mv.visitVarInsn(ASTORE, 1); mv.visitInsn(RETURN); mv.visitMaxs(2, 2); mv.visitEnd(); cw.visitEnd(); try (FileOutputStream fos = new FileOutputStream(new File("ClassFile.class"))) { fos.write(cw.toByteArray()); } } }
37.655172
99
0.683455
418849c8e73c5a14922cb8f9cb7c37f7d87b89a0
5,234
/* * Copyright (C) 2006-2013 Bitronix Software (http://www.bitronix.be) * * 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 bitronix.tm; import bitronix.tm.utils.Uid; import javax.transaction.xa.Xid; /** * Implementation of {@link javax.transaction.xa.Xid}. * <p>A XID is divided in two parts: globalTransactionId (GTRID) and branchQualifier (BQUAL). The first one uniquely * identifies the global transaction while the latter uniquely identifies the transaction branch, or the local part of * the global transaction inside a resource.</p> * <p>Technically in the Bitronix implementation, GTRID and BQUAL have the same format as described by Mike Spille. * Each {@link bitronix.tm.BitronixTransaction} get assigned a GTRID at creation time and full XIDs are created and * assigned to every {@link bitronix.tm.internal.XAResourceHolderState} when enlisted in the transaction's * {@link bitronix.tm.internal.XAResourceManager}. Both GTRID and XIDs are generated * by the {@link bitronix.tm.utils.UidGenerator}.</p> * * @author Ludovic Orban * @see bitronix.tm.utils.UidGenerator * @see bitronix.tm.BitronixTransaction * @see bitronix.tm.internal.XAResourceManager * @see <a href="http://jroller.com/page/pyrasun?entry=xa_exposed_part_iii_the">XA Exposed, Part III: The Implementor's Notebook</a> */ public class BitronixXid implements Xid { /** * int-encoded "Btnx" string. This is used as the globally unique ID to discriminate BTM XIDs. */ public static final int FORMAT_ID = 0x42746e78; private final Uid globalTransactionId; private final Uid branchQualifier; private final int hashCodeValue; private final String toStringValue; /** * Create a new XID using the specified GTRID and BQUAL. * @param globalTransactionId the GTRID. * @param branchQualifier the BQUAL. */ public BitronixXid(Uid globalTransactionId, Uid branchQualifier) { this.globalTransactionId = globalTransactionId; this.branchQualifier = branchQualifier; this.toStringValue = precalculateToString(); this.hashCodeValue = precalculateHashCode(); } public BitronixXid(Xid xid) { this.globalTransactionId = new Uid(xid.getGlobalTransactionId()); this.branchQualifier = new Uid(xid.getBranchQualifier()); this.toStringValue = precalculateToString(); this.hashCodeValue = precalculateHashCode(); } /** * Get Bitronix XID format ID. Defined by {@link BitronixXid#FORMAT_ID}. * @return the Bitronix XID format ID. */ public int getFormatId() { return FORMAT_ID; } /** * Get the BQUAL of the XID. * @return the XID branch qualifier. */ public byte[] getBranchQualifier() { return branchQualifier.getArray(); } public Uid getBranchQualifierUid() { return branchQualifier; } /** * Get the GTRID of the XID. * @return the XID global transaction ID. */ public byte[] getGlobalTransactionId() { return globalTransactionId.getArray(); } public Uid getGlobalTransactionIdUid() { return globalTransactionId; } /** * Get a human-readable string representation of the XID. * @return a human-readable string representation. */ public String toString() { return toStringValue; } private String precalculateToString() { StringBuilder sb = new StringBuilder(288); sb.append("a Bitronix XID ["); sb.append(globalTransactionId.toString()); sb.append(" : "); sb.append(branchQualifier.toString()); sb.append("]"); return sb.toString(); } /** * Compare two XIDs for equality. * @param obj the XID to compare to. * @return true if both XIDs have the same format ID and contain exactly the same GTRID and BQUAL. */ public boolean equals(Object obj) { if (!(obj instanceof BitronixXid)) return false; BitronixXid otherXid = (BitronixXid) obj; return FORMAT_ID == otherXid.getFormatId() && globalTransactionId.equals(otherXid.getGlobalTransactionIdUid()) && branchQualifier.equals(otherXid.getBranchQualifierUid()); } /** * Get an integer hash for the XID. * @return a constant hash value. */ public int hashCode() { return hashCodeValue; } private int precalculateHashCode() { int hashCode = FORMAT_ID; if (globalTransactionId != null) hashCode += globalTransactionId.hashCode(); if (branchQualifier != null) hashCode += branchQualifier.hashCode(); return hashCode; } }
34.20915
132
0.67864
e8f761a8430a6f9c970afed8fe1ce86a8695e45e
228
package DependenceInversionPrinciple; /** * @Author: zcc * @Created_on: 2022/3/8/15:30 * ./Book.java */ public class Book implements IRead{ @Override public String getContent() { return "书上的故事"; } }
15.2
37
0.627193
59766095ca25b5c0ff056d680d5258448a8a048d
2,534
/** * Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caintegrator/LICENSE.txt for details. */ package gov.nih.nci.caintegrator.domain.application; import gov.nih.nci.caintegrator.web.action.analysis.PrincipalComponentAnalysisForm; /** * Object representing a single gene pattern analysis job. */ public class PrincipalComponentAnalysisJob extends AbstractPersistedAnalysisJob { private static final long serialVersionUID = 1L; private final transient PrincipalComponentAnalysisForm form = new PrincipalComponentAnalysisForm(); private String preprocessDataSetUrl; private ResultsZipFile resultsZipFile; private String pcaUrl; /** * Default Constructor. */ public PrincipalComponentAnalysisJob() { this.setJobType(AnalysisJobTypeEnum.PCA); this.setMethod(AnalysisJobTypeEnum.PCA.getValue()); } /** * @return the resultsZipFile */ @Override public ResultsZipFile getResultsZipFile() { return resultsZipFile; } /** * @param resultsZipFile the resultsZipFile to set */ public void setResultsZipFile(ResultsZipFile resultsZipFile) { this.resultsZipFile = resultsZipFile; } /** * @return the form */ public PrincipalComponentAnalysisForm getForm() { return form; } /** * @return the pcaUrl */ public String getPcaUrl() { return pcaUrl; } /** * @param pcaUrl the pcaUrl to set */ public void setPcaUrl(String pcaUrl) { this.pcaUrl = pcaUrl; } /** * @return the preprocessDataSetUrl */ public String getPreprocessDataSetUrl() { return preprocessDataSetUrl; } /** * @param preprocessDataSetUrl the preprocessDataSetUrl to set */ public void setPreprocessDataSetUrl(String preprocessDataSetUrl) { this.preprocessDataSetUrl = preprocessDataSetUrl; } /** * {@inheritDoc} */ @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(retrieveHeader("Principal Component Analysis")); if (getForm().isUsePreprocessDataset()) { sb.append(getForm().getPreprocessParameters().toString()); } sb.append(getForm().getPcaParameters().toString()); return sb.toString(); } }
26.673684
104
0.6397
110177efb1da0d4d01bf8e7410daa9760777f720
3,610
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.datastax.dse.driver.api.core.graph.statement; // INFO: meta props are going away in NGDG import static com.datastax.dse.driver.api.core.graph.DseGraph.g; import static com.datastax.dse.driver.api.core.graph.FluentGraphStatement.newInstance; import static com.datastax.dse.driver.api.core.graph.SampleGraphScripts.ALLOW_SCANS; import static com.datastax.dse.driver.api.core.graph.SampleGraphScripts.MAKE_STRICT; import static com.datastax.dse.driver.api.core.graph.TinkerGraphAssertions.assertThat; import com.datastax.dse.driver.api.core.graph.GraphResultSet; import com.datastax.dse.driver.api.core.graph.ScriptGraphStatement; import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.testinfra.DseRequirement; import com.datastax.oss.driver.api.testinfra.ccm.CustomCcmRule; import com.datastax.oss.driver.api.testinfra.session.SessionRule; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; // INFO: meta props are going away in NGDG @DseRequirement(min = "5.0.3", description = "DSE 5.0.3 required for remote TinkerPop support") public class GraphTraversalMetaPropertiesIT { private static CustomCcmRule ccmRule = CustomCcmRule.builder().withDseWorkloads("graph").build(); private static SessionRule<CqlSession> sessionRule = SessionRule.builder(ccmRule).withCreateGraph().build(); @ClassRule public static TestRule chain = RuleChain.outerRule(ccmRule).around(sessionRule); /** Builds a simple schema that provides for a vertex with a property with sub properties. */ public static String metaProps = MAKE_STRICT + ALLOW_SCANS + "schema.propertyKey('sub_prop').Text().create()\n" + "schema.propertyKey('sub_prop2').Text().create()\n" + "schema.propertyKey('meta_prop').Text().properties('sub_prop', 'sub_prop2').create()\n" + "schema.vertexLabel('meta_v').properties('meta_prop').create()"; /** * Ensures that a traversal that yields a vertex with a property that has its own properties that * is appropriately parsed and made accessible via {@link VertexProperty#property(String)}. * * @test_category dse:graph */ @Test public void should_parse_meta_properties() { sessionRule.session().execute(ScriptGraphStatement.newInstance(metaProps)); GraphResultSet result = sessionRule .session() .execute( newInstance( g.addV("meta_v") .property("meta_prop", "hello", "sub_prop", "hi", "sub_prop2", "hi2"))); Vertex v = result.one().asVertex(); assertThat(v).hasProperty("meta_prop"); VertexProperty<String> metaProp = v.property("meta_prop"); assertThat(metaProp) .hasValue("hello") .hasProperty("sub_prop", "hi") .hasProperty("sub_prop2", "hi2"); } }
41.022727
99
0.729363
3747d7fd09581b1f342d2ba66db85629fb17a892
696
package org.openecomp.sdc.asdctool.impl.validator.executers; import org.junit.Test; public class TopologyTemplateValidatorExecuterTest { private TopologyTemplateValidatorExecuter createTestSubject() { return new TopologyTemplateValidatorExecuter(); } @Test public void testSetName() throws Exception { TopologyTemplateValidatorExecuter testSubject; String name = ""; // default test testSubject = createTestSubject(); testSubject.setName(name); } @Test public void testGetName() throws Exception { TopologyTemplateValidatorExecuter testSubject; String result; // default test testSubject = createTestSubject(); result = testSubject.getName(); } }
17.846154
64
0.762931
367496577ae5f1fcc82ebe3db1e0922e7a948340
1,532
package edu.teco.pavos.pke; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.joda.time.ReadableInstant;; /** * Defines a time interval to be used for filtering the data * @author Jean Baumgarten */ public class TimeIntervall { private DateTime start; private DateTime end; /** * Default constructor * @param interval of time */ public TimeIntervall(String interval) { String[] dates = interval.split(","); if (dates.length == 2) { DateTimeFormatter parser = ISODateTimeFormat.dateTimeNoMillis(); this.start = parser.parseDateTime(dates[0]); this.end = parser.parseDateTime(dates[1]); } else { this.start = new DateTime(); this.end = new DateTime(); } } /** * Checks if the given time is inside the interval * @param time to check * @return true if is inside */ public boolean isInside(DateTime time) { return (time.isAfter(this.start) && time.isBefore(this.end)); } /** * Gives the staring time of the interval * @return a joda date time */ public DateTime getStartDate() { return this.start; } /** * Gives the ending time of the interval * @return a joda date time */ public DateTime getEndDate() { return this.end; } /** * Checks if the given time is after the interval * @param time to check * @return true if is after */ public boolean isAfter(DateTime time) { return time.isAfter(this.end); } }
18.457831
67
0.666449
fa4bd332411229f5ed8addc560fd7cc3f5635829
13,964
/* * Copyright (c) 2021, the hapjs-platform Project Contributors * SPDX-License-Identifier: Apache-2.0 */ package org.hapjs.widgets; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroupOverlay; import android.widget.PopupWindow; import androidx.annotation.Size; import com.facebook.yoga.YogaNode; import com.facebook.yoga.YogaUnit; import java.util.HashMap; import java.util.Map; import org.hapjs.bridge.annotation.WidgetAnnotation; import org.hapjs.common.utils.ColorUtil; import org.hapjs.common.utils.DisplayUtil; import org.hapjs.component.Component; import org.hapjs.component.Container; import org.hapjs.component.Floating; import org.hapjs.component.FloatingHelper; import org.hapjs.component.Placement; import org.hapjs.component.bridge.RenderEventCallback; import org.hapjs.component.constants.Attributes; import org.hapjs.component.view.flexbox.PercentFlexboxLayout; import org.hapjs.runtime.HapEngine; import org.hapjs.runtime.Runtime; import org.hapjs.widgets.text.Text; @WidgetAnnotation( name = Popup.WIDGET_NAME, methods = { Component.METHOD_ANIMATE, Component.METHOD_TO_TEMP_FILE_PATH, Component.METHOD_FOCUS, Component.METHOD_GET_BOUNDING_CLIENT_RECT }) public class Popup extends Container<PercentFlexboxLayout> implements Floating { protected static final String WIDGET_NAME = "popup"; // attribute private static final String PLACEMENT = "placement"; // style private static final String MASK_COLOR = "maskColor"; // event private static final String EVENT_VISIBILITY_CHANGE = "visibilitychange"; private static int sScreenWidth = DisplayUtil.getScreenWidth(Runtime.getInstance().getContext()); private static int sScreenHeight = DisplayUtil.getScreenHeight(Runtime.getInstance().getContext()); private PopupWindow mPopup; private String mTargetId; private Placement mPlacement = Placement.BOTTOM; private int mMaskColor = 0; private boolean mVisibilityChange; private int mContentWidth; private int mContentHeight; private int mAnchorWidth; private int mAnchorHeight; private int[] mAnchorLocation = new int[2]; private boolean mHasCustomBackground; private Drawable mTransparentDrawable; private int mPaddingH; private int mPaddingV; public Popup( HapEngine hapEngine, Context context, Container parent, int ref, RenderEventCallback callback, Map savedState) { super(hapEngine, context, parent, ref, callback, savedState); mTransparentDrawable = new ColorDrawable(Color.TRANSPARENT); } @Override protected PercentFlexboxLayout createViewImpl() { PercentFlexboxLayout flexboxLayout = new PercentFlexboxLayout(mContext); flexboxLayout.setComponent(this); return flexboxLayout; } @Override public void addChild(Component child, int index) { if (child instanceof Text) { super.addChild(child, index); } } @Override protected boolean setAttribute(String key, Object attribute) { switch (key) { case Attributes.Style.TARGET: String targetId = Attributes.getString(attribute); setTargetId(targetId); return true; case PLACEMENT: String placementStr = Attributes.getString(attribute); setPlacement(placementStr); return true; case MASK_COLOR: String maskColorStr = Attributes.getString(attribute, "transparent"); setMaskColor(maskColorStr); return true; case Attributes.Style.POSITION: return true; default: break; } return super.setAttribute(key, attribute); } public void setTargetId(String targetId) { mTargetId = targetId; FloatingHelper helper = getRootComponent().getFloatingHelper(); helper.put(mTargetId, this); } public void setPlacement(String placementStr) { mPlacement = Placement.fromString(placementStr); } public void setMaskColor(String maskColorStr) { if (TextUtils.isEmpty(maskColorStr)) { return; } boolean hasAlpha = ColorUtil.hasAlpha(maskColorStr); int color = ColorUtil.getColor(maskColorStr); if (!hasAlpha) { // set alpha to 30%. color &= 0x4cffffff; } mMaskColor = color; } @Override public void setWidth(String widthStr) { super.setWidth(widthStr); if (mHost == null) { return; } YogaNode node = mHost.getYogaNode(); if (node.getWidth().unit == YogaUnit.PERCENT) { node.setWidth(sScreenWidth * node.getWidth().value / 100); } } @Override public void setHeight(String heightStr) { super.setHeight(heightStr); if (mHost == null) { return; } YogaNode node = mHost.getYogaNode(); if (node.getHeight().unit == YogaUnit.PERCENT) { node.setHeight(sScreenHeight * node.getHeight().value / 100); } } @Override protected boolean addEvent(String event) { if (TextUtils.isEmpty(event) || mHost == null) { return true; } if (EVENT_VISIBILITY_CHANGE.equals(event)) { mVisibilityChange = true; return true; } return super.addEvent(event); } @Override protected boolean removeEvent(String event) { if (TextUtils.isEmpty(event) || mHost == null) { return true; } if (EVENT_VISIBILITY_CHANGE.equals(event)) { mVisibilityChange = false; return true; } return super.removeEvent(event); } @Override public void show(View anchor) { if (anchor == null || mHost == null) { return; } if (mPopup == null) { mPopup = new PopupWindow(mContext, null, 0, R.style.Widget_AppCompat_PopupWindow); mPopup.setBackgroundDrawable( mContext.getResources().getDrawable(R.drawable.popup_background)); mPopup.setOutsideTouchable(true); mPopup.setFocusable(true); mPopup.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); mPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); Rect rect = new Rect(); mPopup.getBackground().getPadding(rect); mPaddingH = rect.left + rect.right; mPaddingV = rect.top + rect.bottom; mPopup.setOnDismissListener( new PopupWindow.OnDismissListener() { @Override public void onDismiss() { if (mVisibilityChange) { Map<String, Object> params = new HashMap(); params.put("visibility", false); mCallback.onJsEventCallback( getPageId(), mRef, EVENT_VISIBILITY_CHANGE, Popup.this, params, null); } clearDim(); } }); } if (mPopup.isShowing()) { return; } if (mVisibilityChange) { Map<String, Object> params = new HashMap(); params.put("visibility", true); mCallback.onJsEventCallback(getPageId(), mRef, EVENT_VISIBILITY_CHANGE, this, params, null); } mPopup.setContentView(mHost); mHost.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); mContentWidth = mHost.getMeasuredWidth(); mContentHeight = mHost.getMeasuredHeight(); if (mHasCustomBackground) { mPopup.setBackgroundDrawable(mTransparentDrawable); } else { mContentWidth += mPaddingH; mContentHeight += mPaddingV; } mAnchorWidth = anchor.getWidth(); mAnchorHeight = anchor.getHeight(); anchor.getLocationOnScreen(mAnchorLocation); int[] offset = new int[2]; getOffset(mPlacement, offset, false); mPopup.showAsDropDown(anchor, offset[0], offset[1]); dimBehind(); } private void getOffset(Placement placement, @Size(2) int[] offset, boolean fallback) { if (fallback && mPlacement == placement) { Placement next = placement.next(); if (next == null) { // fallback process over. offset[0] = 0; offset[1] = 0; } else { getOffset(next, offset, true); } return; } int offsetX = 0; int offsetY = 0; boolean success = false; switch (placement) { case LEFT: if (mAnchorLocation[0] >= mContentWidth) { offsetX = -mContentWidth; offsetY = -(mContentHeight + mAnchorHeight) / 2; offsetY = Math.min(offsetY, -mContentHeight); success = true; } break; case RIGHT: if (sScreenWidth - mAnchorLocation[0] - mAnchorWidth >= mContentWidth) { offsetX = mAnchorWidth; offsetY = -(mContentHeight + mAnchorHeight) / 2; offsetY = Math.min(offsetY, -mContentHeight); success = true; } break; case TOP: if (mAnchorLocation[1] >= mContentHeight) { offsetX = (mAnchorWidth - mContentWidth) / 2; ; offsetY = -(mContentHeight + mAnchorHeight); success = true; } break; case BOTTOM: if (sScreenHeight - mAnchorLocation[1] - mAnchorHeight >= mContentHeight) { offsetX = (mAnchorWidth - mContentWidth) / 2; offsetY = 0; success = true; } break; case TOP_LEFT: if (mAnchorLocation[0] > mContentWidth && mAnchorLocation[1] >= mContentHeight) { offsetX = -mContentWidth; offsetY = -(mContentHeight + mAnchorHeight); success = true; } break; case TOP_RIGHT: if (mAnchorLocation[1] >= mContentHeight && sScreenWidth - mAnchorLocation[0] - mAnchorWidth >= mContentWidth) { offsetX = mAnchorWidth; offsetY = -(mContentHeight + mAnchorHeight); success = true; } break; case BOTTOM_LEFT: if (mAnchorLocation[0] >= mContentWidth && sScreenHeight - mAnchorLocation[1] - mAnchorHeight >= mContentHeight) { offsetX = -mContentWidth; offsetY = 0; success = true; } break; case BOTTOM_RIGHT: if (sScreenWidth - mAnchorLocation[0] - mAnchorWidth >= mContentWidth && sScreenHeight - mAnchorLocation[1] - mAnchorHeight >= mContentHeight) { offsetX = mAnchorWidth; offsetY = 0; success = true; } break; default: break; } if (success) { offset[0] = offsetX; offset[1] = offsetY; } else { final Placement next; if (fallback) { next = placement.next(); } else { next = Placement.BOTTOM; } if (next != null) { getOffset(next, offset, true); } } } @Override public void dismiss() { if (mPopup != null) { mPopup.dismiss(); } } @Override public void setBackgroundColor(String colorStr) { super.setBackgroundColor(colorStr); mHasCustomBackground = true; } @Override public void setBackgroundImage(String backgroundImage) { super.setBackgroundImage(backgroundImage); mHasCustomBackground = true; } @Override public void setBackground(String background) { super.setBackground(background); mHasCustomBackground = true; } private void dimBehind() { if (mPopup == null || mMaskColor == 0 || !(mContext instanceof Activity)) { return; } Activity activity = (Activity) mContext; ViewGroup parent = (ViewGroup) activity.getWindow().getDecorView().getRootView(); Drawable dim = new ColorDrawable(mMaskColor); dim.setBounds(0, 0, parent.getWidth(), parent.getHeight()); ViewGroupOverlay overlay = parent.getOverlay(); overlay.add(dim); } private void clearDim() { if (!(mContext instanceof Activity)) { return; } Activity activity = (Activity) mContext; ViewGroup parent = (ViewGroup) activity.getWindow().getDecorView().getRootView(); ViewGroupOverlay overlay = parent.getOverlay(); overlay.clear(); } }
33.811138
98
0.56617
730f7dce67f6a9922a6ba26cf77507d51ac19164
1,539
// ============================================================================ // // Copyright (C) 2006-2017 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.components.kafka; import java.util.List; import org.apache.commons.lang3.reflect.TypeLiteral; import org.talend.daikon.properties.PropertiesImpl; import org.talend.daikon.properties.presentation.Form; import org.talend.daikon.properties.property.Property; import org.talend.daikon.properties.property.PropertyFactory; public class KafkaConfTableProperties extends PropertiesImpl { private static final TypeLiteral<List<String>> LIST_STRING_TYPE = new TypeLiteral<List<String>>() {// empty }; public Property<List<String>> keyCol = PropertyFactory.newProperty(LIST_STRING_TYPE, "keyCol"); public Property<List<String>> valueCol = PropertyFactory.newProperty(LIST_STRING_TYPE, "valueCol"); public KafkaConfTableProperties(String name) { super(name); } @Override public void setupLayout() { super.setupLayout(); Form mainForm = new Form(this, Form.MAIN); mainForm.addRow(keyCol); mainForm.addColumn(valueCol); } }
33.456522
111
0.665367
8602eb22ff8a129767f4c6d93f6202d26e0c097b
395
package codeandchords; import processing.core.PApplet; public class FullScreenDisplay extends PApplet { public FullScreenDisplay() { } public void startDisplay() { PApplet.main("core.FullScreenDisplay"); } public void settings() { this.fullScreen(); } public void setup() { } public void draw() { } public PApplet getPApplet() { return this; } }
10.128205
46
0.658228
778e7fd68196ea6c10119830fcf6810c1a91aaca
14,233
package es.uc3m.tsc.math; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.text.DecimalFormat; import java.util.Arrays; public class ArrayUtils { public static boolean equal(boolean [][]a,boolean [][]b){ if (a.length!=b.length) return false; boolean r=true; for (int i=0;i<a.length;i++){ if (!Arrays.equals(a[i],b[i])){ r=false; break; } } return r; } public static boolean equal(int [][]a,int [][]b){ if (a.length!=b.length) return false; boolean r=true; for (int i=0;i<a.length;i++){ if (!Arrays.equals(a[i],b[i])){ r=false; break; } } return r; } public static boolean equal(double [][]a,double [][]b){ if (a.length!=b.length) return false; boolean r=true; for (int i=0;i<a.length;i++){ if (!Arrays.equals(a[i],b[i])){ r=false; break; } } return r; } public static boolean almostEqual(double [][]a,double [][]b,double delta){ if (a.length!=b.length) return false; boolean r=true; loop1: for (int i=0;i<a.length;i++){ for (int j=0;j<a[i].length;j++){ double d=Math.abs((a[i][j]-b[i][j])/b[i][j]); if (d>delta){ r=false; break loop1; } } } return r; } public static boolean equalByRows(boolean[][] a, boolean[][] b){ if (a.length!=b.length) return false; boolean eqRow; boolean[] bUsed=new boolean[b.length]; Arrays.fill(bUsed, false); for (int i=0;i<a.length;i++){ eqRow=false; for (int j=0;j<b.length;j++){ if (!bUsed[j]){ if (Arrays.equals(a[i], b[j])){ eqRow=true; bUsed[j]=true; break; } } } if (!eqRow) return false; } return true; } static public int[] sumCols(boolean[][] inputMatrix){ int g=inputMatrix.length; int m=inputMatrix[0].length; int[] sumMatrix=new int[m]; int i; for (int j=0;j<m;j++){ sumMatrix[j]=0; for (i=0;i<g;i++){ if (inputMatrix[i][j]) sumMatrix[j]++; } } return sumMatrix; } static public int[] sumRows(boolean[][] inputMatrix){ int g=inputMatrix.length; int m=inputMatrix[0].length; int[] sumMatrix=new int[g]; boolean[] row; int i; for (i=0;i<g;i++){ row=inputMatrix[i]; sumMatrix[i]=0; for (int j=0;j<m;j++){ if (row[j]) sumMatrix[i]++; } } return sumMatrix; } static public boolean[][] transpose(boolean[][] inputMatrix){ int nr=inputMatrix.length; int nc=inputMatrix[0].length; boolean[][] o=new boolean[nc][nr]; for (int i=0;i<nr;i++){ for (int j=0;j<nc;j++){ o[j][i]=inputMatrix[i][j]; } } return o; } static public int sumElems(boolean[] inputRow){ int r=0; for (boolean b: inputRow){ if (b) r+=1; } return r; } static public double[] calcMaxMin(double[][] data){ double maxValue=-Double.MAX_VALUE; double minValue=Double.MAX_VALUE; for (double[] row:data){ for (double val:row){ if (maxValue<val) maxValue=val; if (minValue>val) minValue=val; } } return new double[]{maxValue,minValue}; } public static String getCanvas(double[][] data, String[] colNames, String[] toolTips){ int width=600; int height=300; return getCanvas( data, colNames, toolTips, width, height); } public static String getCanvas(double[][] data, String[] colNames, String[] toolTips, int width, int height){ if (data==null || data.length==0){ return ""; } String canvasId="datamatrix_canvas"; int lineWidth=3; int nc=data[0].length; int nr=data.length; StringBuilder s=new StringBuilder(); double max=-Double.MAX_VALUE; double min=Double.MAX_VALUE; for (int i=0;i<nr;i++){ for (int j=0;j<nc;j++){ if (data[i][j]>max) max=data[i][j]; if (data[i][j]<min) min=data[i][j]; } } String hexColor; int remainDigits; float normColor; float hue=(float)0.2; float saturation=(float)0.9; float brightness=(float)0.7; Color canvasColor; s.append("var gene_expression_canvas = document.getElementById('"+canvasId+"');\n"); s.append("var width="+width+";\n"); s.append("var height="+height+";\n"); s.append("gene_expression_canvas.width=width;\n"); s.append("gene_expression_canvas.height=height+20;\n"); s.append("var ctx = gene_expression_canvas.getContext('2d');\n"); s.append("var genExp=new Array("+nc+")\n"); s.append("var x=0;\nvar y=0;\n"); s.append("var l=(height/genExp.length)*0.9;\n"); s.append("var wcolormap=100;\n"); s.append("var i=0;\n"); s.append("var j=0;\n"); s.append("var w=0;\n"); int numLines=100; double indx=0; for (int i=0;i<nc;i++){ s.append("ctx.fillText('"+colNames[i]+"', x, y+0.9*l);\n"); s.append("var v = ctx.measureText ('"+colNames[i]+"');\n"); s.append("if (v.width>w) w=v.width;\n"); s.append("genExp["+i+"]=["); normColor=(float)((data[0][i]-min)/(max-min)); //canvasColor=Color.getHSBColor(hue,(float)Math.sqrt(1-normColor), normColor); canvasColor=Color.getHSBColor(normColor*(float)0.7,saturation, brightness); hexColor=Integer.toHexString(canvasColor.getRGB()&0xFFFFFF); remainDigits=6-hexColor.length(); for (int r=0;r<remainDigits;r++) hexColor="0"+hexColor; s.append("'#"+hexColor+"'"); for (int j=1;j<numLines;j++){ indx=(double)j/(double)numLines*nr; normColor=(float)((data[(int)indx][i]-min)/(max-min)); //canvasColor=Color.getHSBColor(hue, (float)Math.sqrt(1-normColor), normColor); canvasColor=Color.getHSBColor(normColor*(float)0.7,saturation, brightness); hexColor=Integer.toHexString(canvasColor.getRGB()&0xFFFFFF); remainDigits=6-hexColor.length(); for (int r=0;r<remainDigits;r++) hexColor="0"+hexColor; s.append(",'#"+hexColor+"'"); } s.append("]\n"); s.append(" y=y+l*1.1;\n"); } s.append("colormap=['#FFFFFF'"); for (int i=numLines-2;i>=0;i--){ normColor=(float)i/(float)numLines; //canvasColor=Color.getHSBColor(hue,(float)Math.sqrt(1-normColor), normColor); canvasColor=Color.getHSBColor(normColor*(float)0.7,saturation, brightness); hexColor=Integer.toHexString(canvasColor.getRGB()&0xFFFFFF); remainDigits=6-hexColor.length(); for (int r=0;r<remainDigits;r++) hexColor="0"+hexColor; s.append(",'#"+hexColor+"'"); } s.append("]\n"); DecimalFormat myFormatter = new DecimalFormat("###.###"); s.append("numlabels=["); s.append("'"+myFormatter.format(max)+"',"); for (double i=0.9;i>0;i-=0.1){ s.append("'"+myFormatter.format(i*(max-min)+min)+"',"); } s.append("]\n"); s.append("x=0;\n"); s.append("y=0;\n"); s.append("lineWidth=(width-w-wcolormap)/"+numLines+";\n"); s.append("ctx.lineWidth = lineWidth;\n"); s.append("for (i=0;i<genExp.length;i++){\n"); s.append(" x=w+lineWidth;\n"); s.append(" for (j=0;j<genExp[i].length;j++){\n"); s.append(" x+=lineWidth;\n"); s.append(" ctx.beginPath();\n"); s.append(" ctx.moveTo(x,y);\n"); s.append(" ctx.lineTo(x,y+l);\n"); s.append(" ctx.strokeStyle = genExp[i][j];\n"); s.append(" ctx.stroke();\n"); s.append(" };\n"); s.append(" y=y+l*1.1;\n"); s.append("}\n"); s.append("xs=width-wcolormap+20;\n"); s.append("xe=width-wcolormap+30;\n"); s.append("wl=height/("+numLines+"-1);\n"); s.append("ctx.lineWidth = wl;\n"); s.append("for (i=0;i<"+numLines+";i++){\n"); s.append(" ctx.beginPath();\n"); s.append(" ctx.moveTo(xs,i*wl);\n"); s.append(" ctx.lineTo(xe,i*wl);\n"); s.append(" ctx.strokeStyle = colormap[i];\n"); s.append(" ctx.stroke();\n"); s.append("}\n"); s.append("ctx.lineWidth = 1;\n"); s.append("ctx.strokeStyle ='#000000';\n"); s.append("for (i=0;i<numlabels.length;i++){\n"); s.append(" y=(i*height)/(numlabels.length-1);\n"); s.append(" ctx.fillText(numlabels[i], xe+10, y+8);\n"); s.append(" ctx.beginPath();\n"); s.append(" ctx.moveTo(xe,y);\n"); s.append(" ctx.lineTo(xe+8,y);\n"); s.append(" ctx.stroke();\n"); s.append("}\n"); if (toolTips!=null){ s.append("gene_expression_canvas.onmousemove = function(e){\n"); s.append(" var tooltip=document.getElementById('tooltip');\n"); s.append(" tooltip.style.visibility='visible'\n"); s.append(" var label_tooltip=new Array();\n"); for (int i=0;i<toolTips.length;i++){ s.append(" label_tooltip["+i+"]='"+toolTips[i]+"';\n"); } s.append(" label_tooltip["+toolTips.length+"]='"+toolTips[toolTips.length-1]+"';\n"); s.append(" tooltip.style.visibility='visible';\n"); s.append( " ypos = (e.offsetY || e.pageY - $(e.target).offset().top);\n"); s.append(" var indx=Math.round((ypos-l/2)/(l*1.1));\n"); s.append(" if (indx>=label_tooltip.length) indx=label_tooltip.length-1;\n"); //s.append(" var indx=Math.round((event.offsetY-l/2)/(l*1.1));\n"); s.append(" tooltip.innerHTML=label_tooltip[indx]\n"); s.append(" tooltip.style.left=((window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft))+'px';\n"); s.append(" tooltip.style.top=((window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop))+'px';\n"); //s.append(" tooltip.style.top=event.offsetY+365+'px';\n"); //s.append(" tooltip.style.left=event.offsetX+160+'px';\n"); s.append("}\n"); s.append("gene_expression_canvas.onmouseout = function(event){\n"); s.append(" var tooltip=document.getElementById('tooltip');\n"); s.append(" tooltip.style.visibility='hidden'\n"); s.append("}\n"); } return s.toString(); } public static BufferedImage generateImage(double[][] data, int pixelsWidth, int pixelsHeight ) throws Exception{ double x =0,y = 0; BufferedImage bi = new BufferedImage( pixelsWidth, pixelsHeight, BufferedImage.TYPE_3BYTE_BGR ); Graphics2D g=(Graphics2D)bi.getGraphics(); int w=data[0].length; int l=data.length; double Dy=(double)pixelsHeight/(double)l; double Dx=(double)pixelsWidth/(double)w; int height = (int)Math.ceil(Dy); int width = (int)Math.ceil(Dx); int gap=(int)Math.ceil(width/4); double max=-Double.MAX_VALUE; double min=Double.MAX_VALUE; for (int i=0;i<l;i++){ for (int j=0;j<w;j++){ if (data[i][j]>max) max=data[i][j]; if (data[i][j]<min) min=data[i][j]; } } float fcolor; g.setColor( Color.WHITE); g.fillRect( 0, 0 , pixelsWidth,pixelsHeight); for( int i =0; i < l; i++ ){ for( int j =0; j < w; j++ ){ fcolor=(float)((data[i][j]-min)/(max-min)); g.setColor(Color.getHSBColor(fcolor*(float)0.7,(float)0.9, (float)0.7)); //g.setColor(Color.getHSBColor((float)0.2, (float)Math.sqrt(1-fcolor), fcolor)); g.fillRect( (int)x, (int)y , width-gap,height); x+=Dx; } y+=Dy; x=0; } g.dispose(); return bi; } /* * Gets the index corresponding to a sorted array of A * It uses the Insertion sort algorithm which is efficient for small data sets (a.length<64) * * @param: A array to sort * @return: index of elements of A sorted */ public static int[] sortIndex(double[] A){ double[] sortedA=new double[A.length]; int[] index=new int[A.length]; double valueToInsert; int holePos; for (int i=0;i<sortedA.length;i++){ valueToInsert=A[i]; holePos=i; while (holePos>0 && valueToInsert<sortedA[holePos-1]){ sortedA[holePos]=sortedA[holePos-1]; index[holePos]=index[--holePos]; } sortedA[holePos]=valueToInsert; index[holePos]=i; } return index; /* int[] retindex=new int[A.length]; retindex[0]=index[0]; int k=1; for (int i=1;i<sortedA.length;i++){ if (sortedA[i]>sortedA[i-1]){ retindex[k++]=index[i]; } } return Arrays.copyOf(retindex, k); */ } public static PipedInputStream getPipedMatrix(final double[][] R, final String[] rowNames, final String[] colNames) throws IOException{ PipedInputStream pi=new PipedInputStream(); final PipedOutputStream po=new PipedOutputStream(pi); new Thread( new Runnable() { public void run() { try { String row=""; for (String attrName : colNames){ row+=attrName+";"; } row+="\r\n"; po.write(row.getBytes()); for(int i=0;i<R.length;i++){ double[] rowI=R[i]; row=rowNames[i]+";"; for(int j=0;j<rowI.length;j++){ row+=rowI[j]+";"; } row+="\r\n"; po.write(row.getBytes()); } po.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); return pi; } }
30.874187
196
0.546828
d3b4b0c467ef2348c829161183f1c695e9f19323
851
package io.github.linuxcounter.services.api; import io.github.linuxcounter.common.value.AnonymousReportData; /** * Service for incoming reports from clients. * * <p>This service will validate requests:</p> * <ul> * <li>Check if anonymous data is correct and complete.</li> * <li>Check if data of registered users matches their system id.</li> * </ul> */ public interface CounterService { /** * Counts an anonymous report. * * <p>This method will check if hwid is present and notify user if user is logged in and system_id was sent.</p> * * <p>The data will be saved to database (including a timestamp) if valid.</p> * * @param reportData the report data to check and (if valid) count. * @throws IllegalArgumentException any data validation error. */ void countAnonymous(AnonymousReportData reportData); }
30.392857
114
0.709753
4c891ad3193f9a6c4b7e7fd8fda9ddce968c2900
460
package covid.fukui.rss.articlefeeder.exception; /** * DateTimeの変換に失敗した場合の例外 */ public class InvalidDateTimeFormatException extends ArticleFeederException { private static final long serialVersionUID = 5337756106684712403L; /** * コンストラクタ * * @param message メッセージ * @param cause Throwable */ public InvalidDateTimeFormatException(final String message, final Throwable cause) { super(message, cause); } }
21.904762
88
0.704348
c8296018cf5f495b9c97b8523a607c1b3550bde4
2,914
package com.github.yoma.core.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.github.pagehelper.PageInfo; import com.github.yoma.common.persistence.BaseController; import com.github.yoma.common.persistence.BatchDTO; import com.github.yoma.common.result.CommonResponse; import com.github.yoma.common.result.DetailResponse; import com.github.yoma.common.result.PageResponse; import com.github.yoma.common.result.ResponseUtil; import com.github.yoma.core.domain.BaseDict; import com.github.yoma.core.dto.BaseDictQueryDTO; import com.github.yoma.core.service.BaseDictService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; /** * 数据字典RestFull服务 * * @author 马世豪 * @version 2020-12-15 */ @RestController @RequestMapping(value = "/core/baseDict") @Api(tags = "数据字典") public class BaseDictController extends BaseController { @Autowired private BaseDictService baseDictService; /** * 列表查询 */ @ApiOperation(value = " 列表查询") @GetMapping("list") public PageResponse<BaseDict> list(BaseDictQueryDTO queryDTO) { PageInfo<BaseDict> pageInfo = baseDictService.findPage(queryDTO); PageResponse<BaseDict> pageResponse = ResponseUtil.pageSuccess(pageInfo); return pageResponse; } /** * 保存或修改 */ @ApiOperation(value = " 保存或修改") @PostMapping("/save") public DetailResponse<BaseDict> save(@RequestBody BaseDict baseDict) { baseDictService.save(baseDict); DetailResponse<BaseDict> success = ResponseUtil.detailSuccess(baseDict); return success; } /** * 详情 */ @ApiOperation("详情") @GetMapping("/detail/{baseDictId}") public DetailResponse<BaseDict> detail(@PathVariable Long baseDictId) { BaseDict baseDict = new BaseDict(); baseDict.setId(baseDictId); baseDict = baseDictService.get(baseDict); DetailResponse<BaseDict> success = ResponseUtil.detailSuccess(baseDict); return success; } /** * 删除操作 */ @ApiOperation("删除") @PostMapping("/delete/{baseDictId}") public CommonResponse delete(@PathVariable Long baseDictId) { BaseDict baseDict = new BaseDict(); baseDict.setId(baseDictId); int count = baseDictService.delete(baseDict); CommonResponse success = ResponseUtil.success(); return success; } /** * 删除操作-批量 */ @ApiOperation("批量删除") @PostMapping("/batch/delete") public CommonResponse batchDelete(@RequestBody BatchDTO batchDTO) { // 获取当前操作人信息 BaseDictQueryDTO queryDTO = new BaseDictQueryDTO(); queryDTO.setBatchIdList(batchDTO.getBatchIdList()); int count = baseDictService.batchDelete(queryDTO); CommonResponse success = ResponseUtil.success(); return success; } }
29.734694
81
0.699039
df435e16e7b24fc5e87e02d3bed231a2ba48a69a
4,765
package org.asyou.sequoia.transaction.proxy; import net.sf.cglib.proxy.MethodProxy; import org.asyou.sequoia.dao.SequoiaAdapter; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * Created by steven on 17/8/9. */ public abstract class AProxy<T> implements IProxy<T> { // private static Logger logger = Logger.getGlobal(); //每个线程的计数器,KEY是线程ID private static Map<String,TransactionCounter> transactionCounterMap = new HashMap<>(); public synchronized static TransactionCounter getCounter(String key){ return transactionCounterMap.containsKey(key) ? transactionCounterMap.get(key) : createAndGetCounter(key); } public synchronized static TransactionCounter createAndGetCounter(String key){ if (!transactionCounterMap.containsKey(key)) { transactionCounterMap.put(key, new TransactionCounter()); } return transactionCounterMap.get(key); } public synchronized static void removeCounter(String key){ if (transactionCounterMap.containsKey(key)) { transactionCounterMap.remove(key); } } // static { // transactionCounterMap = new HashMap<>(); // } // protected T target; protected SequoiaAdapter adapter; protected ITransactionDelegate delegate; protected T targetObject; protected abstract T execute(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable; // public abstract T create(Class<T> targetClass, ITransactionDelegate delegate); protected T invocation(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { T result = null; TransactionCounter counter = AProxy.getCounter("proxy:thread"+Thread.currentThread().getId()+":"+ adapter.getAdapterId()); //todo before if (counter.increaseAndGetBefore() == 1) { begin(counter); } //todo method counter.increaseAndGetMethod(); //如果methodProxy为空,则采用jdk的动态代理,否则采用cglib try { result = execute0(proxy, method, args, methodProxy, counter); }catch (Throwable e){ rollback(counter); throw e; } //todo after counter.increaseAndGetAfter(); if (counter.getAfter() == counter.getBefore()) { commit(counter); // System.out.println(String.format("%s:%s",adapter.getAdapterId(),counter.toString())); // logger.info("\r\n" + gson.getAdapterId() + counter.toString()); removeCounter(); } return result; } //事务开始 protected void begin(TransactionCounter counter) throws Throwable { counter.increaseAndGetBegin(); try { if (delegate != null) { boolean beginResult = delegate.begin(); if (!beginResult) { throw new Exception("transaction begin method is failed"); } } } catch (Throwable e) { throw e; } } //事务执行过程,如果methodProxy为空则执行jdk的dynamic proxy,否则执行cglib intercept protected T execute0(Object proxy, Method method, Object[] args, MethodProxy methodProxy, TransactionCounter counter) throws Throwable { counter.increaseAndGetExecute(); T result = null; result = execute(proxy,method,args,methodProxy); // counter.increaseAndGetExecuteErrors(); return result; } //事务提交 protected void commit(TransactionCounter counter) throws Throwable { if (counter.increaseAndGetCommit() == 1) { try { if (delegate != null) { boolean commitResult = delegate.commit(); if (!commitResult) { throw new Exception("transaction commit method is failed."); } } } catch (Throwable e) { //todo counter increaseAndGetErrors() rollback(counter); throw e; } } } //事务回滚 protected void rollback(TransactionCounter counter) throws Throwable { if (counter.increaseAndGetRollback() == 1) { try { if (delegate != null) { boolean rollbackResult = delegate.rollback(); if (!rollbackResult) { throw new Exception("transaction rollback method is failed."); } } } catch (Throwable e) { throw e; } } } //删除计数器 protected void removeCounter(){ removeCounter("proxy:thread"+Thread.currentThread().getId()+":"+ adapter.getAdapterId()); } }
33.090278
140
0.60063
87c8d0d469ad22d30d8542e78dd0c1ab752f9be6
2,578
package sample; import javafx.event.EventHandler; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.Text; public class RectangleZone extends Rectangle implements Zone { private static final double MIN_SIDE = 8.0; private Text text; private boolean plant; public RectangleZone(double x, double y, double width, double height){ setX(x); setY(y); if(width < MIN_SIDE) setWidth(MIN_SIDE); else setWidth(width); if(height < MIN_SIDE) setHeight(MIN_SIDE); else setHeight(height); setFill(Color.TRANSPARENT); text = new Text(""); text.setFont(Font.font("Gabriola", 24)); addEventFilter(MouseEvent.MOUSE_ENTERED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { text.setLayoutX(getX() + width/2 - text.getLayoutBounds().getWidth() / 2); text.setLayoutY(getY() - 10); text.setFill(getStroke()); setFill(getStroke()); setOpacity(0.3); text.setVisible(true); } }); addEventFilter(MouseEvent.MOUSE_EXITED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if(plant) setFill(Color.TRANSPARENT); setOpacity(1.0); text.setVisible(false); } }); } public void move(double x, double y){ setX(getX() + x); setY(getY() + y); } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append(getClass().getName() + "," + getX() + "," + getY() + "," + getWidth() + "," + getHeight() + ","); sb.append(getStrokeWidth() + "," + getStroke() + "," + getName() + "," + plant); return sb.toString(); } public String getName(){ return text.getText(); } public void setName(String name){ text.setText(name); } public void addPane(Pane pane){ pane.getChildren().addAll(this, text); } public void setTextVisible(boolean visible){ this.text.setVisible(visible); } public void setPlant(boolean plant){ this.plant = plant; } public boolean isPlant(){ return plant; } }
28.644444
116
0.559348
7545bba15b72ed951483890355b1dfa7c1efe604
9,295
package com.cedarwood.ademo.activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.cedarwood.ademo.R; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainActivity extends BaseActivity { private String[] names = {"TabBarTestActivity","TabBarViewPagerTestActivity", "PullListViewTestActivity", "SwipeRefreshTestActivity", "DragMapTestActivity", "PickerTestActivity", "CameraTestActivity", "CheeseTestActivity", "RecyclerAnimatorsTestActivity", "TouchTestActivity", "DoubleDragTestActivity", "DoubleDragTest2Activity","JazzyViewPagerTestActivity", "OnOffTestActivity", "虫儿飞##", "路长", "虫儿飞$$", "虫儿飞","人生路", "虫儿飞~~", "虫儿飞", "人生路", "虫儿飞~~", "虫儿飞", "人生路", "虫儿飞~~", "虫儿飞", "人生路", "虫儿飞~~"}; private Class[] classNames={ TabBarTestActivity.class,TabBarViewPagerTestActivity.class,PullListViewTestActivity.class,SwipeRefreshTestActivity.class, DragMapTestActivity.class, PickerTestActivity.class,CameraTestActivity.class,CheeseTestActivity.class,RecyclerAnimatorsTestActivity.class, TouchTestActivity.class,DoubleDragTestActivity.class,DoubleDragTest2Activity.class,JazzyViewPagerTestActivity.class,OnOffTestActivity.class}; private List<String> texts = new ArrayList<String>(); private HomeAdapter adapter; private RecyclerView recycler; private Toolbar toolbar; private CollapsingToolbarLayout callapsingToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); texts = new ArrayList<String>(Arrays.asList(names)); initView(); initData(); } private void initView() { toolbar = (Toolbar) findViewById(R.id.main_toolbar); callapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.main_collapse_toolbar); callapsingToolbar.setTitle("Main"); callapsingToolbar.setTitleEnabled(false); recycler = (RecyclerView) findViewById(R.id.main_recycler); // recycler.setLayoutManager(new LinearLayoutManager(this)); recycler.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); adapter = new HomeAdapter(); recycler.setAdapter(adapter); // recycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)); // recycler.addItemDecoration(new DividerGridItemDecoration(this)); recycler.setItemAnimator(new DefaultItemAnimator()); adapter.setOnItemClickLitener(new OnItemClickLitener() { @Override public void onItemClick(View view, int position) { if(position<classNames.length){ Intent intent =new Intent(MainActivity.this,classNames[position]); startActivity(intent); } Toast.makeText(MainActivity.this, position + " click", Toast.LENGTH_SHORT).show(); } @Override public void onItemLongClick(View view, int position) { Toast.makeText(MainActivity.this, position + " long click", Toast.LENGTH_SHORT).show(); adapter.removeData(position); } }); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.main_fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } private void initData() { toolbar.setTitle("Main");//设置Toolbar标题 toolbar.setTitleTextColor(Color.parseColor("#ffffff")); //设置标题颜色 setSupportActionBar(toolbar); getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用 getSupportActionBar().setDisplayHomeAsUpEnabled(true); } public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeViewHolder> { private final ArrayList<Integer> mHeights; HomeAdapter(){ mHeights = new ArrayList<Integer>(); for (int i = 0; i < texts.size(); i++) { mHeights.add( (int) (300 + Math.random() * 200)); } } private OnItemClickLitener mOnItemClickLitener; public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) { this.mOnItemClickLitener = mOnItemClickLitener; } @Override public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.view_main_recycler_item, parent, false); HomeViewHolder holder = new HomeViewHolder(view); return holder; } @Override public void onBindViewHolder(final HomeViewHolder holder, int position) { // int height = (int)Math.random()*300+200; RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) holder.layout.getLayoutParams(); params.height = mHeights.get(position); holder.layout.setLayoutParams(params); holder.tv.setText(names[position]); if (mOnItemClickLitener != null) { holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = holder.getLayoutPosition(); mOnItemClickLitener.onItemClick(holder.itemView, pos); } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int pos = holder.getLayoutPosition(); mOnItemClickLitener.onItemLongClick(holder.itemView, pos); return false; } }); } } @Override public int getItemCount() { return texts.size(); } public void addData(int position) { texts.add(position, "Insert One"); mHeights.add( (int) (300 + Math.random() * 200)); notifyItemInserted(position); } public void removeData(int position) { texts.remove(position); notifyItemRemoved(position); } class HomeViewHolder extends RecyclerView.ViewHolder { TextView tv; LinearLayout layout; public HomeViewHolder(View view) { super(view); tv = (TextView) view.findViewById(R.id.main_recycler_item_text); layout = (LinearLayout) view.findViewById(R.id.main_recycler_item_layout); } } } public interface OnItemClickLitener{ void onItemClick(View view, int position); void onItemLongClick(View view , int position); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.id_action_add: adapter.addData(classNames.length); break; case R.id.id_action_delete: adapter.removeData(classNames.length); break; case R.id.id_action_gridview: // recycler.setLayoutManager(new GridLayoutManager(this, 4)); break; case R.id.id_action_listview: // recycler.setLayoutManager(new LinearLayoutManager(this)); break; case R.id.id_action_horizontalGridView: // recycler.setLayoutManager(new StaggeredGridLayoutManager(4, // StaggeredGridLayoutManager.HORIZONTAL)); break; case R.id.id_action_staggeredgridview: // Intent intent = new Intent(this , StaggeredGridLayoutActivity.class); // startActivity(intent); break; } return true; } }
33.555957
212
0.625605
17f5b53be3e4f1995460e8d11ce28e8ed4f0ff00
6,921
/* * Copyright 2016 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.robotframework.ide.eclipse.main.plugin.hyperlink.detectors; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.robotframework.red.junit.jupiter.ProjectExtension.createFile; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.nebula.widgets.nattable.data.IRowDataProvider; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.robotframework.ide.eclipse.main.plugin.hyperlink.FileHyperlink; import org.robotframework.ide.eclipse.main.plugin.model.RobotKeywordCall; import org.robotframework.ide.eclipse.main.plugin.model.RobotKeywordsSection; import org.robotframework.ide.eclipse.main.plugin.model.RobotModel; import org.robotframework.ide.eclipse.main.plugin.model.RobotSetting; import org.robotframework.ide.eclipse.main.plugin.model.RobotSettingsSection; import org.robotframework.ide.eclipse.main.plugin.model.RobotSuiteFile; import org.robotframework.red.junit.jupiter.Project; import org.robotframework.red.junit.jupiter.ProjectExtension; @ExtendWith(ProjectExtension.class) public class TableHyperlinksToFilesDetectorTest { @Project(dirs = { "directory" }, files = { "file.robot", "vars.py", "lib.class", "unhandled.txt", "directory/file.robot" }) static IProject project; @Test public void noHyperlinksAreProvided_whenLibraryIsImportedUsingName() throws Exception { assertThat(detect("f1.robot", "Library", "lib_name")).isEmpty(); } @Test public void noHyperlinksAreProvided_whenUsingAbsolutePathWhichIsOutsideWorkspace() throws Exception { assertThat(detect("f2.robot", "Library", "/abs_path/to_file.robot")).isEmpty(); } @Test public void noHyperlinksAreProvided_whenRelativePathPointsToDirectory() throws Exception { assertThat(detect("f3.robot", "Library", "directory/")).isEmpty(); } @Test public void noHyperlinksAreProvided_whenAbsolutePathPointsToDirectory() throws Exception { final String absPath = project.getLocation().append("directory/").toString(); assertThat(detect("f4.robot", "Library", absPath)).isEmpty(); } @Test public void noHyperlinksAreProvided_whenRelativePathPointsNonExistingFile() throws Exception { assertThat(detect("f5.robot", "Resource", "directory/non_existing.robot")).isEmpty(); } @Test public void noHyperlinksAreProvided_whenAbsolutePathPointsNonExistingFile() throws Exception { final String absPath = project.getLocation() .append("directory/non_existing.robot").toString(); assertThat(detect("f6.robot", "Resource", absPath)).isEmpty(); } @SuppressWarnings("unchecked") @Test public void noHyperlinksAreProvided_whenNonFirstColumnIsChosen() throws Exception { final IFile file = createFile(project, "f7.robot", "*** Settings ***", "Resource file.robot arg1 arg2"); final RobotSuiteFile suiteFile = new RobotModel().createSuiteFile(file); final RobotSetting setting = (RobotSetting) suiteFile .findSection(RobotSettingsSection.class).get() .getChildren().get(0); final IRowDataProvider<Object> dataProvider = mock(IRowDataProvider.class); when(dataProvider.getRowObject(0)).thenReturn(setting); final TableHyperlinksToFilesDetector detector = new TableHyperlinksToFilesDetector(dataProvider); assertThat(detector.detectHyperlinks(0, 0, "Resource", 0)).isEmpty(); assertThat(detector.detectHyperlinks(0, 2, "arg1", 0)).isEmpty(); assertThat(detector.detectHyperlinks(0, 3, "arg2", 0)).isEmpty(); } @Test public void noHyperlinksAreProvided_forNonImportSetting() throws Exception { assertThat(detect("f8.robot", "Metadata", "file.robot")).isEmpty(); } @SuppressWarnings("unchecked") @Test public void noHyperlinksAreProvided_forOtherElements() throws Exception { final IFile file = createFile(project, "f9.robot", "*** Keywords ***", "kw", " Log file.robot"); final RobotSuiteFile suiteFile = new RobotModel().createSuiteFile(file); final RobotKeywordCall logCall = suiteFile .findSection(RobotKeywordsSection.class).get() .getChildren().get(0).getChildren().get(0); final IRowDataProvider<Object> dataProvider = mock(IRowDataProvider.class); when(dataProvider.getRowObject(0)).thenReturn(logCall); final TableHyperlinksToFilesDetector detector = new TableHyperlinksToFilesDetector(dataProvider); assertThat(detector.detectHyperlinks(0, 1, "file.robot", 0)).isEmpty(); } @Test public void fileHyperlinkIsProvided_whenPathPointsToExistingFile_1() throws Exception { final List<IHyperlink> hyperlinks = detect("f10.robot", "Resource", "file.robot"); assertThat(hyperlinks).hasSize(1).allMatch(FileHyperlink.class::isInstance); } @Test public void fileHyperlinkIsProvided_whenPathPointsToExistingFile_2() throws Exception { final List<IHyperlink> hyperlinks = detect("f11.robot", "Variables", "vars.py"); assertThat(hyperlinks).hasSize(1).allMatch(FileHyperlink.class::isInstance); } @Test public void fileHyperlinkIsProvided_whenPathPointsToExistingFile_3() throws Exception { final List<IHyperlink> hyperlinks = detect("f12.robot", "Library", "lib.class"); assertThat(hyperlinks).hasSize(1).allMatch(FileHyperlink.class::isInstance); } @SuppressWarnings("unchecked") private static List<IHyperlink> detect(final String file, final String settingName, final String path) throws Exception { final IFile f = createFile(project, file, "*** Settings ***", settingName + " " + path); final RobotSuiteFile suiteFile = new RobotModel().createSuiteFile(f); final RobotSetting setting = (RobotSetting) suiteFile.findSection(RobotSettingsSection.class) .get() .getChildren() .get(0); final IRowDataProvider<Object> dataProvider = mock(IRowDataProvider.class); when(dataProvider.getRowObject(0)).thenReturn(setting); final TableHyperlinksToFilesDetector detector = new TableHyperlinksToFilesDetector(dataProvider); return detector.detectHyperlinks(0, 1, path, 0); } }
45.532895
107
0.701633
2a9b32a7f4846db924c263f3c093fd08e5bcb574
3,827
/* * Copyright 2010 Softgress - http://www.softgress.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 eu.larkc.iris.rules.compiler; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.deri.iris.api.basics.ILiteral; import org.deri.iris.api.basics.IRule; import cascading.pipe.Pipe; import eu.larkc.iris.Configuration; /** * This object gourps ll the streams for a rule, the head stream and a list of the body streams * * @author valer.roman@softgress.com * */ public class RuleStreams { private static final String HEAD_LITERAL_PREFIX = "HL"; private static final String BODY_LITERAL_PREFIX = "L"; private LiteralFields headStream = null; private List<LiteralFields> bodyStreams = new ArrayList<LiteralFields>(); /** * Identificator class used for fields of iris literal * * @author valer.roman@softgress.com * */ public class LiteralId { private int index = -1; public LiteralId() {} public LiteralId(int index) { this.index = index; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return getPrefix() + ((index == -1) ? "" : index); } private String getPrefix() { if (index == -1) { return HEAD_LITERAL_PREFIX; } else { return BODY_LITERAL_PREFIX; } } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (!(obj instanceof LiteralId)) { return false; } LiteralId literalId = (LiteralId) obj; return new EqualsBuilder().append(getPrefix(), literalId.getPrefix()) .append(index, literalId.index).isEquals(); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return new HashCodeBuilder().append(getPrefix()).append(index).hashCode(); } } public RuleStreams(Configuration configuration, Pipe mainPipe, IRule rule) { ILiteral headLiteral = rule.getHead().get(0); if (!configuration.doPredicateIndexing) { headStream = new LiteralFields(configuration, mainPipe, new LiteralId(), headLiteral); } else { headStream = new LiteralFields(configuration, new LiteralId(), headLiteral); } for (int i = 0; i < rule.getBody().size(); i++) { ILiteral literal = rule.getBody().get(i); // we shouldn't even have to check for that if we do not deal // with negation, this is basically a double check for the // parser if (!literal.isPositive()) { throw new IllegalArgumentException("Negation is not supported: " + literal); } if (!configuration.doPredicateIndexing) { bodyStreams.add(new LiteralFields(configuration, mainPipe, new LiteralId(i), literal)); } else { bodyStreams.add(new LiteralFields(configuration, new LiteralId(i), literal)); } } } public RuleStreams(Configuration configuration, IRule rule) { this(configuration, null, rule); } public LiteralFields getHeadStream() { return headStream; } public List<LiteralFields> getBodyStreams() { return bodyStreams; } public ListIterator<LiteralFields> getBodyStreamIterator() { return bodyStreams.listIterator(); } }
27.532374
95
0.703162
24bbfeed5e43338aed7c79283a097295d758c883
1,005
package com.array.controllers.requests; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; /** * @author XIII */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class RegisterRequest { @NotBlank(message = "Firstname is required") private String firstName; @NotBlank(message = "Lastname is required") private String lastName; @NotBlank(message = "Email is required") @Email(message = "An email format is required") private String email; @NotBlank(message = "Password is required") @Pattern(regexp="^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{3,}$", message="Password must contain a length of at least 3 characters included at least one digit [0-9]," + " one lowercase [a-z], one uppercase [A-Z].") private String password; }
27.162162
114
0.697512
422b720941509ee18e9f986b0f34d81c658f4696
238
package com.genius.backend.domain.model.log; public interface LogValue { String getJsonValue(HttpRequestLog httpRequestLog); String getJsonValue(HttpResponseLog httpResponseLog); String getJsonValue(SendMessageLog sendTalkLog); }
19.833333
54
0.827731
a5abb13b7eb700b95b614bf96bdc1ff2477ed67e
858
package cn.yihu.microboot.service.point; import java.util.List; import org.apache.ibatis.annotations.Select; import cn.yihu.microboot.util.Results; import cn.yihu.microboot.vo.point.ItemPoint; /** * * @author Yang * */ public interface ItemPointService { /** * 获取所有上架兑换物品 * @return */ Results<List<ItemPoint>> queryAllItemPoint(); /** * 获取上架火热物品列表 * @return */ Results<List<ItemPoint>> queryHotItemPoint(); /** * 获取上架推荐的物品兑换列表 * @return */ Results<List<ItemPoint>> queryRecommendItemPoint(); /** * 获取加入轮播的上架物品兑换列表 * @return */ Results<List<ItemPoint>> queryCarouselItemPoint(); /** * 添加 * @param itemPoint * @return */ Results<Boolean> insertItemPoint(ItemPoint itemPoint); /** * 删除 * @param itemPoint * @return */ Results<Boolean> updateItemPoint(ItemPoint itemPoint); }
13.83871
55
0.66317
68be327e917fa7ae0c56a8b3b5485260999e37b2
914
package com.jason.hibernate.model.manytomany.bidirectional; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; @Entity public class Dream implements Serializable { private static final long serialVersionUID = 5528683744502620340L; @Id @GeneratedValue private Integer id; private String name; @ManyToMany(mappedBy="dreams") private Set<User> users=new HashSet<User>(); public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
19.446809
68
0.704595
2e0ff7b2e086a2d097baaddb32ae294c0e1b1aea
1,589
package io.smallrye.stork; import java.util.List; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; public class Service { private final LoadBalancer loadBalancer; private final ServiceDiscovery serviceDiscovery; private final String serviceName; public Service(String serviceName, LoadBalancer loadBalancer, ServiceDiscovery serviceDiscovery) { this.loadBalancer = loadBalancer; this.serviceDiscovery = serviceDiscovery; this.serviceName = serviceName; } /** * Provide a single {@link ServiceInstance} * * @return a Uni with a ServiceInstance */ public Uni<ServiceInstance> selectServiceInstance() { return serviceDiscovery.getServiceInstances() .map(loadBalancer::selectServiceInstance); } /** * Provide a collection of {@link ServiceInstance}s * * @return a Multi - stream of ServiceInstances */ public Uni<List<ServiceInstance>> getServiceInstances() { return serviceDiscovery.getServiceInstances(); } /** * Get the underlying load balancer * * @return load balancer */ public LoadBalancer getLoadBalancer() { if (loadBalancer == null) { throw new IllegalArgumentException("No load balancer for service '" + serviceName + "' defined"); } return loadBalancer; } /** * Get the underlying service discovery * * @return service discovery */ public ServiceDiscovery getServiceDiscovery() { return serviceDiscovery; } }
26.483333
109
0.660793
5bcb4fc75fa062209fb41b6210138b163cabefee
4,606
package com.samsung.sds.brightics.common.workflow.context.parameter; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Immutable parameter map. * It is different with a variable. * The variables are controlled by outer class and it is mutable. * Client must resolve their variables then make own parameter map before creating this class. * * @author jb.jung */ public class Parameters { private final Map<String, JsonElement> parameterMap; public Parameters(Map<String, JsonElement> map) { parameterMap = new HashMap<>(); parameterMap.putAll(map); } public boolean contains(String key) { return parameterMap.containsKey(key); } public JsonElement getParam(String key) { return parameterMap.get(key); } public <T extends JsonElement> T getParamAs(String key, Class<T> clazz) { Object some = parameterMap.get(key); if (clazz.isInstance(some)) { return (T) some; } else { return null; } } public Number getNumber(String key) { return ((JsonPrimitive) getParamAs(key, JsonPrimitive.class)).getAsNumber(); } public Number[] getNumericArray(String key) { return convertToArray(getParamAs(key, JsonArray.class), Number.class); } private <T> T[] convertToArray(JsonArray source, Class<T> clazz) { List<T> list = new ArrayList<>(); source.forEach(elem -> { if (elem.isJsonPrimitive()) { if (clazz.equals(Number.class)) { list.add((T) elem.getAsJsonPrimitive().getAsNumber()); } else if (clazz.equals(String.class)) { list.add((T) elem.getAsJsonPrimitive().getAsString()); } } else { list.add(null); } }); T[] result = (T[]) Array.newInstance(clazz, list.size()); return list.toArray(result); } public Number[][] getNumeric2dArray(String key) { JsonArray array = getParamAs(key, JsonArray.class); List<Number[]> list = new ArrayList<>(); array.forEach(elem -> { if (elem.isJsonArray()) { list.add(convertToArray(elem.getAsJsonArray(), Number.class)); } else { list.add(null); } }); Number[][] result = new Number[list.size()][]; return list.toArray(result); } public String getString(String key) { try { return getParam(key).getAsString(); } catch (Exception e) { return null; } } public String[] getStringArray(String key) { return convertToArray(getParamAs(key, JsonArray.class), String.class); } public String[][] getString2dArray(String key) { List<String[]> list = new ArrayList<>(); getParamAs(key, JsonArray.class).forEach(elem -> { if (elem.isJsonArray()) { list.add(convertToArray(elem.getAsJsonArray(), String.class)); } else { list.add(null); } }); String[][] result = new String[list.size()][]; return list.toArray(result); } @SuppressWarnings("unchecked") public Map<String, JsonElement> getMap(String key) { Map<String, JsonElement> result = new HashMap<>(); for (Entry<String, JsonElement> entry : getParamAs(key, JsonObject.class).entrySet()) { result.put(entry.getKey(), entry.getValue()); } return result; } @Override public String toString() { return "Parameters [" + parameterMap + "]"; } public Set<String> keys() { return parameterMap.keySet(); } public Set<Entry<String, JsonElement>> entrySet() { return parameterMap.entrySet(); } public JsonObject toJsonObject() { JsonObject result = new JsonObject(); for (Entry<String, JsonElement> entry : parameterMap.entrySet()) { result.add(entry.getKey(), entry.getValue()); } return result; } public String toJsonString() { return toJsonObject().toString(); } }
31.121622
96
0.576639
a738f95c73d2dd970101bf2c0fbffe5d317cc195
1,396
package org.openstreetmap.atlas.geography.atlas.items.complex.waters.handler; import static org.openstreetmap.atlas.geography.atlas.items.ItemType.AREA; import static org.openstreetmap.atlas.geography.atlas.items.ItemType.LINE; import java.util.Arrays; import java.util.List; import org.openstreetmap.atlas.geography.atlas.items.AtlasEntity; import org.openstreetmap.atlas.geography.atlas.items.ItemType; import org.openstreetmap.atlas.geography.atlas.items.complex.waters.WaterType; import org.openstreetmap.atlas.tags.WaterwayTag; import org.openstreetmap.atlas.tags.annotations.validation.Validators; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Sid */ public class CreekHandler extends AbstractWaterHandler { private static final Logger logger = LoggerFactory.getLogger(CreekHandler.class); public static boolean isCreek(final AtlasEntity atlasEntity) { return Validators.isOfType(atlasEntity, WaterwayTag.class, WaterwayTag.STREAM); } @Override public boolean canHandle(final AtlasEntity entity) { return isCreek(entity); } @Override public List<ItemType> getAllowedTypes() { return Arrays.asList(AREA, LINE); } @Override public Logger getLogger() { return logger; } @Override public WaterType getType() { return WaterType.CREEK; } }
26.339623
87
0.745702
73ae63413f488acb2376b79641bae95cb886fa2c
708
package com.example.demo.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.example.demo.entity.User; public interface IUserRepository extends JpaRepository<User, Integer>{ @Query("SELECT u FROM User u WHERE u.username = ?1 AND u.password = ?2") User findByUsernameAndPassword(String username, String password); // List<User> findByUsernameAndPasswor(String emailAddress, String password); @Query("SELECT u FROM User u WHERE u.username = ?1 ") User findByUsername(String username); @Query("SELECT u FROM User u WHERE u.key = ?1 ") User findByKey(String key); }
30.782609
79
0.724576
0aa6266db00b79ed79f5c3b093410fa094caa2e4
6,301
/* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * 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.hpcloud.mon.infrastructure.persistence.influxdb; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import javax.inject.Named; import org.influxdb.InfluxDB; import org.influxdb.dto.Serie; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Query; import org.skife.jdbi.v2.util.StringMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.hpcloud.mon.MonApiConfiguration; import com.hpcloud.mon.common.model.alarm.AlarmState; import com.hpcloud.mon.domain.model.alarmstatehistory.AlarmStateHistory; import com.hpcloud.mon.domain.model.alarmstatehistory.AlarmStateHistoryRepository; import com.hpcloud.mon.infrastructure.persistence.DimensionQueries; import com.hpcloud.mon.infrastructure.persistence.SubAlarmQueries; public class AlarmStateHistoryInfluxDbRepositoryImpl implements AlarmStateHistoryRepository { private static final Logger logger = LoggerFactory .getLogger(AlarmStateHistoryInfluxDbRepositoryImpl.class); private final MonApiConfiguration config; private final InfluxDB influxDB; private final DBI mysql; private static final String FIND_ALARMS_SQL = "select distinct a.id from alarm as a " + "join" + " sub_alarm sa on a.id = sa.alarm_id " + "left outer join sub_alarm_dimension dim on " + "sa.id = dim.sub_alarm_id%s " + "where a.tenant_id = :tenantId and a.deleted_at is " + "NULL"; @Inject public AlarmStateHistoryInfluxDbRepositoryImpl(@Named("mysql") DBI mysql, MonApiConfiguration config, InfluxDB influxDB) { this.mysql = mysql; this.config = config; this.influxDB = influxDB; } @Override public List<AlarmStateHistory> findById(String tenantId, String alarmId) throws Exception { // InfluxDB orders queries by time stamp desc by default. String query = buildQueryForFindById(tenantId, alarmId); return queryInfluxDBForAlarmStateHistory(query); } String buildQueryForFindById(String tenantId, String alarmId) throws Exception { return String.format("select alarm_id, old_state, new_state, reason, reason_data " + "from alarm_state_history " + "where tenant_id = '%1$s' and alarm_id = '%2$s'", Utils.SQLSanitizer.sanitize(tenantId), Utils.SQLSanitizer.sanitize(alarmId)); } @Override public Collection<AlarmStateHistory> find(String tenantId, Map<String, String> dimensions, DateTime startTime, @Nullable DateTime endTime) throws Exception { List<String> alarmIds = null; // Find alarm Ids for dimensions try (Handle h = mysql.open()) { String sql = String.format(FIND_ALARMS_SQL, SubAlarmQueries.buildJoinClauseFor(dimensions)); Query<Map<String, Object>> query = h.createQuery(sql).bind("tenantId", tenantId); DimensionQueries.bindDimensionsToQuery(query, dimensions); alarmIds = query.map(StringMapper.FIRST).list(); } if (alarmIds == null || alarmIds.isEmpty()) { return Collections.emptyList(); } String timePart = buildTimePart(startTime, endTime); String alarmsPart = buildAlarmsPart(alarmIds); String query = buildQueryForFind(tenantId, timePart, alarmsPart); return queryInfluxDBForAlarmStateHistory(query); } String buildTimePart(DateTime startTime, DateTime endTime) { return Utils.WhereClauseBuilder.buildTimePart(startTime, endTime); } String buildQueryForFind(String tenantId, String timePart, String alarmsPart) throws Exception { return String.format("select alarm_id, old_state, new_state, reason, reason_data " + "from alarm_state_history " + "where tenant_id = '%1$s' %2$s %3$s", Utils.SQLSanitizer.sanitize(tenantId), timePart, alarmsPart); } String buildAlarmsPart(List<String> alarmIds) { StringBuilder sb = new StringBuilder(); for (String alarmId : alarmIds) { if (sb.length() > 0) { sb.append(" or "); } sb.append(String.format(" alarm_id = '%1$s' ", alarmId)); } if (sb.length() > 0) { sb.insert(0, " and ("); sb.insert(sb.length(), ")"); } return sb.toString(); } private List<AlarmStateHistory> queryInfluxDBForAlarmStateHistory(String query) { logger.debug("Query string: {}", query); List<Serie> result = this.influxDB.Query(this.config.influxDB.getName(), query, TimeUnit.MILLISECONDS); List<AlarmStateHistory> alarmStateHistoryList = new LinkedList<>(); // Should only be one serie -- alarm_state_history. for (Serie serie : result) { Object[][] valObjArryArry = serie.getPoints(); for (int i = 0; i < valObjArryArry.length; i++) { AlarmStateHistory alarmStateHistory = new AlarmStateHistory(); // Time is always in position 0. Double timeDouble = (Double) valObjArryArry[i][0]; alarmStateHistory.setTimestamp(new DateTime(timeDouble.longValue(), DateTimeZone.UTC)); // Sequence_number is always in position 1. alarmStateHistory.setAlarmId((String) valObjArryArry[i][2]); alarmStateHistory.setNewState(AlarmState.valueOf((String) valObjArryArry[i][3])); alarmStateHistory.setOldState(AlarmState.valueOf((String) valObjArryArry[i][4])); alarmStateHistory.setReason((String) valObjArryArry[i][5]); alarmStateHistory.setReasonData((String) valObjArryArry[i][6]); alarmStateHistoryList.add(alarmStateHistory); } } return alarmStateHistoryList; } }
37.730539
100
0.729249
de89422480bf6522af6751ab910a6047948d38e3
1,845
/* * Copyright (C) 2012 Brendan Robert (BLuRry) brendan.robert@gmail.com. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package jace.apple2e.softswitch; import jace.core.Keyboard; import jace.core.RAMEvent; import jace.core.SoftSwitch; /** * Keyboard keypress strobe -- on = key pressed * @author Brendan Robert (BLuRry) brendan.robert@gmail.com */ public class KeyboardSoftSwitch extends SoftSwitch { public KeyboardSoftSwitch(String name, int offAddress, int onAddress, int queryAddress, RAMEvent.TYPE changeType, Boolean initalState) { super(name,offAddress,onAddress,queryAddress,changeType,initalState); } public KeyboardSoftSwitch(String name, int[] offAddrs, int[] onAddrs, int[] queryAddrs, RAMEvent.TYPE changeType, Boolean initalState) { super(name,offAddrs,onAddrs,queryAddrs,changeType,initalState); } @Override public void stateChanged() { Keyboard.clearStrobe(); } /** * return current keypress (if high bit set, strobe is not cleared) * @return */ @Override public byte readSwitch() { return Keyboard.readState(); } }
36.176471
140
0.722493
b8cf8ba0dc1b01953abc46daff76b5f9725c1293
916
public class Solution { static Character vowels[] = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' }; static Set<Character> vowelsSet = new HashSet<>(Arrays.asList(vowels)); public int solve(String A) { // What about spaces? // length - vowelIndex -> number of substrings starting with this vowel // Solution 1 // straight-forward // result // loop // if character is vowel // result += (length - vowelIndex) // O(N) // Solution 2 // regexp // smth like int length = A.length(); if (length == 0) { return 0; } int result = 0; for (int i = 0; i < length; ++i) { if (vowelsSet.contains(A.charAt(i))) { result += (length - i); } } return result % 10003; } }
25.444444
85
0.447598
10246ae6607a836cf3cd44214fc1c3dd1511fc89
1,164
package flask.test; import flak.Response; import flak.annotations.Post; import flak.annotations.Route; import flak.login.FlakUser; import flak.login.LoginNotRequired; import org.junit.Assert; import org.junit.Test; /** * Reproduce invalid cookie path generated when app path is null|""|/ */ public class AuthCookiePathTest extends AbstractAppTest { @Override protected void preScan() { installFlakLogin(); sessionManager.setLoginPage("/"); sessionManager.setRequireLoggedInByDefault(true); } @Route("/data") public String getData() { return "OK"; } @Route("/") public String loginPage() { return "Please login"; } @LoginNotRequired @Route("/api/login") @Post public void login(Response r) { FlakUser user = sessionManager.createUser("test"); sessionManager.openSession(app, user, r); } @Test public void testLoginLogout() throws Exception { Assert.assertEquals("Please login", client.get("/data")); client.post("/api/login", ""); Assert.assertEquals("OK", client.get("/data")); Assert.assertEquals("/", client.getCookie(sessionManager.getAuthTokenCookieName()).getPath()); } }
23.755102
98
0.70189
bc5d241d12ac7bb8d7f1f1a946eabad2ff8bbabd
175
package ghissues; import org.osgl.mvc.annotation.GetAction; public class Gh1257 extends BaseController { @GetAction("1257") public void test(int[] data) { } }
14.583333
44
0.697143
3a660ee41111eb7fe66e886b6572fa2d298a5dd0
1,472
package com.smilehacker.lego.util; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * Created by zhouquan on 17/2/28. */ public class ReflectionUtil { private static final String TYPE_NAME_PREFIX = "class "; public static String getClassName(Type type) { if (type==null) { return ""; } String className = type.toString(); if (className.startsWith(TYPE_NAME_PREFIX)) { className = className.substring(TYPE_NAME_PREFIX.length()); } return className; } public static Class<?> getClass(Type type) throws ClassNotFoundException { String className = getClassName(type); if (className==null || className.isEmpty()) { return null; } return Class.forName(className); } public static Object newInstance(Type type) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class<?> clazz = getClass(type); if (clazz==null) { return null; } return clazz.newInstance(); } public static Type[] getParameterizedTypes(Object object) { Type superclassType = object.getClass().getGenericSuperclass(); if (!ParameterizedType.class.isAssignableFrom(superclassType.getClass())) { return null; } return ((ParameterizedType)superclassType).getActualTypeArguments(); } }
29.44
91
0.634511
eca2563259863e4354220b8abf4e5596fea1e629
1,543
package com.dumblthon.messenger.auth.repository; import org.jooq.Param; import org.jooq.Query; import org.jooq.conf.ParamType; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; public interface NamedParamJdbcOps<T> { NamedParameterJdbcOperations getNamedParamJdbcOperations(); RowMapper<T> getMapper(); default T queryForObject(Query query) { return queryForObject(query, getMapper()); } default <R> R queryForObject(Query query, RowMapper<R> mapper) { return getNamedParamJdbcOperations() .queryForObject( query.getSQL(ParamType.NAMED), toParamSource(query), mapper); } default Optional<T> queryForOptionalObject(Query query) { return queryForOptionalObject(query, getMapper()); } default <R> Optional<R> queryForOptionalObject(Query query, RowMapper<R> mapper) { try { R result = queryForObject(query, mapper); return Optional.ofNullable(result); } catch (EmptyResultDataAccessException e) { return Optional.empty(); } } default Map<String, Object> toParamSource(Query query) { return query.getParams().values().stream() .collect(Collectors.toMap(Param::getName, Param::getValue)); } }
30.86
86
0.685677
16b45f19531c10bfd5ddc5fc8d122d4a623f5217
3,228
package com.microsoft.azure.functions.worker.binding; import java.util.HashMap; import java.util.Map; import com.microsoft.azure.functions.HttpResponseMessage; import com.microsoft.azure.functions.HttpStatus; import com.microsoft.azure.functions.HttpStatusType; import com.microsoft.azure.functions.rpc.messages.RpcHttp; import com.microsoft.azure.functions.rpc.messages.TypedData; final class RpcHttpDataTarget extends DataTarget implements HttpResponseMessage, HttpResponseMessage.Builder { RpcHttpDataTarget() { super(HTTP_TARGET_OPERATIONS); this.headers = new HashMap<>(); this.httpStatus = HttpStatus.OK; this.httpStatusCode = HttpStatus.OK.value(); super.setValue(this); } @Override public HttpStatusType getStatus() { return httpStatus; } @Override public int getStatusCode() { return httpStatusCode; } @Override public String getHeader(String key) { return this.headers.get(key); } @Override public Object getBody() { return this.body; } private int httpStatusCode; private HttpStatusType httpStatus; private Object body; private Map<String, String> headers; public static TypedData.Builder toRpcHttpData(RpcHttpDataTarget response) throws Exception { TypedData.Builder dataBuilder = TypedData.newBuilder(); if (response != null) { RpcHttp.Builder httpBuilder = RpcHttp.newBuilder().setStatusCode(Integer.toString(response.getStatusCode())); response.headers.forEach(httpBuilder::putHeaders); RpcUnspecifiedDataTarget bodyTarget = new RpcUnspecifiedDataTarget(); bodyTarget.setValue(response.getBody()); bodyTarget.computeFromValue().ifPresent(httpBuilder::setBody); dataBuilder.setHttp(httpBuilder); } return dataBuilder; } private static final DataOperations<Object, TypedData.Builder> HTTP_TARGET_OPERATIONS = new DataOperations<>(); static { HTTP_TARGET_OPERATIONS.addTargetOperation(HttpResponseMessage.class, v -> toRpcHttpData((RpcHttpDataTarget) v)); HTTP_TARGET_OPERATIONS.addTargetOperation(RpcHttpDataTarget.class, v -> toRpcHttpData((RpcHttpDataTarget) v)); } public Builder status(HttpStatus status) { this.httpStatusCode = status.value(); this.httpStatus = status; return this; } @Override public Builder status(HttpStatusType httpStatusType) { this.httpStatusCode = httpStatusType.value(); this.httpStatus = httpStatusType; return this; } public Builder status(int httpStatusCode) { if (httpStatusCode < 100 || httpStatusCode > 599) { throw new IllegalArgumentException("Invalid HTTP Status code class. Valid classes are in the range of 1xx, 2xx, 3xx, 4xx and 5xx."); } this.httpStatusCode = httpStatusCode; this.httpStatus = HttpStatusType.custom(httpStatusCode); return this; } @Override public Builder header(String key, String value) { this.headers.put(key, value); return this; } @Override public Builder body(Object body) { this.body = body; return this; } @Override public HttpResponseMessage build() { return this; } }
33.625
144
0.713445
83bbb3894362624ac81598f58b5e04ec26137843
1,034
package og; import java.util.Random; import java.util.function.Consumer; public class ElementProperties { public static Property color = new ColorProperty() { @Override public String getName() { return "color"; } @Override public String getDefaultValue() { return "black"; } }; public static Property labelColor = new ColorProperty() { @Override public String getName() { return "labelColor"; } @Override public String getDefaultValue() { return "black"; } }; public static Property width = new IntProperty(10) { @Override public String getName() { return "width"; } @Override public String getDefaultValue() { return "1"; } }; public static Property label = new LabelProperty() { @Override public String getName() { return "label"; } @Override public String getDefaultValue() { return ""; } }; public static void forEach(Consumer<Property> p) { p.accept(color); p.accept(width); p.accept(label); p.accept(labelColor); } }
14.985507
58
0.658607
de53878c593fd00ea8dab2ae0c81e539ed56d445
9,478
/* * Copyright 2015 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.server; import static com.linecorp.armeria.server.VirtualHost.ensureHostnamePatternMatchesDefaultHostname; import static com.linecorp.armeria.server.VirtualHost.normalizeDefaultHostname; import static com.linecorp.armeria.server.VirtualHost.normalizeHostnamePattern; import static java.util.Objects.requireNonNull; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import javax.net.ssl.SSLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linecorp.armeria.common.ServiceInvocationContext; import com.linecorp.armeria.common.SessionProtocol; import com.linecorp.armeria.common.util.NativeLibraries; import io.netty.handler.codec.http2.Http2SecurityUtil; import io.netty.handler.ssl.ApplicationProtocolConfig; import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol; import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior; import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior; import io.netty.handler.ssl.ApplicationProtocolNames; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import io.netty.handler.ssl.SupportedCipherSuiteFilter; /** * Builds a new {@link VirtualHost}. * <h2>Example</h2> * <pre>{@code * VirtualHostBuilder vhb = new VirtualHostBuilder("*.example.com"); * vhb.serviceAt("/foo", new FooService()) * .serviceUnder("/bar/", new BarService()) * .service(PathMapping.ofRegex("^/baz/.*", new BazService()); * * VirtualHost vh = vhb.build(); * }</pre> * * @see PathMapping */ public final class VirtualHostBuilder { private static final Logger logger = LoggerFactory.getLogger(VirtualHostBuilder.class); private static final ApplicationProtocolConfig HTTPS_ALPN_CFG = new ApplicationProtocolConfig( Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1); private static final String LOCAL_HOSTNAME; static { // Try the '/usr/bin/hostname' command first, which is more reliable. Process process = null; String hostname = null; try { process = Runtime.getRuntime().exec("hostname"); final String line = new BufferedReader(new InputStreamReader(process.getInputStream())).readLine(); if (line == null) { logger.warn("The 'hostname' command returned nothing; " + "using InetAddress.getLocalHost() instead", line); } else { hostname = normalizeDefaultHostname(line.trim()); logger.info("Hostname: {} (via 'hostname' command)", hostname); } } catch (Exception e) { logger.warn("Failed to get the hostname using the 'hostname' command; " + "using InetAddress.getLocalHost() instead", e); } finally { if (process != null) { process.destroy(); } } if (hostname == null) { try { hostname = normalizeDefaultHostname(InetAddress.getLocalHost().getHostName()); logger.info("Hostname: {} (via InetAddress.getLocalHost())", hostname); } catch (Exception e) { hostname = "localhost"; logger.warn("Failed to get the hostname using InetAddress.getLocalHost(); " + "using 'localhost' instead", e); } } LOCAL_HOSTNAME = hostname; } private final String defaultHostname; private final String hostnamePattern; private final List<ServiceConfig> services = new ArrayList<>(); private SslContext sslContext; /** * Creates a new {@link VirtualHostBuilder} whose hostname pattern is {@code "*"} (match-all). */ public VirtualHostBuilder() { this(LOCAL_HOSTNAME, "*"); } /** * Creates a new {@link VirtualHostBuilder} with the specified hostname pattern. */ public VirtualHostBuilder(String hostnamePattern) { hostnamePattern = normalizeHostnamePattern(hostnamePattern); if ("*".equals(hostnamePattern)) { defaultHostname = LOCAL_HOSTNAME; } else if (hostnamePattern.startsWith("*.")) { defaultHostname = hostnamePattern.substring(2); } else { defaultHostname = hostnamePattern; } this.hostnamePattern = hostnamePattern; } /** * Creates a new {@link VirtualHostBuilder} with the specified hostname pattern. */ public VirtualHostBuilder(String defaultHostname, String hostnamePattern) { requireNonNull(defaultHostname, "defaultHostname"); defaultHostname = normalizeDefaultHostname(defaultHostname); hostnamePattern = normalizeHostnamePattern(hostnamePattern); ensureHostnamePatternMatchesDefaultHostname(hostnamePattern, defaultHostname); this.defaultHostname = defaultHostname; this.hostnamePattern = hostnamePattern; } /** * Sets the {@link SslContext} of this {@link VirtualHost}. */ public VirtualHostBuilder sslContext(SslContext sslContext) { this.sslContext = VirtualHost.validateSslContext(requireNonNull(sslContext, "sslContext")); return this; } /** * Sets the {@link SslContext} of this {@link VirtualHost} from the specified {@link SessionProtocol}, * {@code keyCertChainFile} and cleartext {@code keyFile}. */ public VirtualHostBuilder sslContext( SessionProtocol protocol, File keyCertChainFile, File keyFile) throws SSLException { return sslContext(protocol, keyCertChainFile, keyFile, null); } /** * Sets the {@link SslContext} of this {@link VirtualHost} from the specified {@link SessionProtocol}, * {@code keyCertChainFile}, {@code keyFile} and {@code keyPassword}. */ public VirtualHostBuilder sslContext( SessionProtocol protocol, File keyCertChainFile, File keyFile, String keyPassword) throws SSLException { if (requireNonNull(protocol, "protocol") != SessionProtocol.HTTPS) { throw new IllegalArgumentException("unsupported protocol: " + protocol); } final SslContextBuilder builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword); builder.sslProvider(NativeLibraries.isOpenSslAvailable() ? SslProvider.OPENSSL : SslProvider.JDK); builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE); builder.applicationProtocolConfig(HTTPS_ALPN_CFG); sslContext(builder.build()); return this; } /** * Binds the specified {@link Service} at the specified exact path. */ public VirtualHostBuilder serviceAt(String exactPath, Service service) { return service(PathMapping.ofExact(exactPath), service); } /** * Binds the specified {@link Service} under the specified directory.. */ public VirtualHostBuilder serviceUnder(String pathPrefix, Service service) { return service(PathMapping.ofPrefix(pathPrefix), service); } /** * Binds the specified {@link Service} at the specified {@link PathMapping}. */ public VirtualHostBuilder service(PathMapping pathMapping, Service service) { services.add(new ServiceConfig(pathMapping, service, null)); return this; } /** * Binds the specified {@link Service} at the specified {@link PathMapping}. * * @param loggerName the name of the {@linkplain ServiceInvocationContext#logger() service logger}; * must be a string of valid Java identifier names concatenated by period ({@code '.'}), * such as a package name or a fully-qualified class name */ public VirtualHostBuilder service(PathMapping pathMapping, Service service, String loggerName) { services.add(new ServiceConfig(pathMapping, service, loggerName)); return this; } /** * Creates a new {@link VirtualHost}. */ public VirtualHost build() { return new VirtualHost(defaultHostname, hostnamePattern, sslContext, services); } @Override public String toString() { return VirtualHost.toString(getClass(), defaultHostname, hostnamePattern, sslContext, services); } }
38.528455
111
0.684322
291a8355fd05e456f86f6d5648c234a2388cba9d
1,829
package com.reecycle.reecycleapp.form.SlidePages.Reepontos; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.reecycle.reecycleapp.R; import java.util.List; public class PremiosAdapter extends RecyclerView.Adapter<PremiosAdapter.PremiosViewHolder> { private List<PremiosModel> premiosModels; public PremiosAdapter(List<PremiosModel> premiosModels) { this.premiosModels = premiosModels; } static class PremiosViewHolder extends RecyclerView.ViewHolder{ ImageView image; TextView titulo; TextView reepoints; public PremiosViewHolder(@NonNull View itemView) { super(itemView); image = itemView.findViewById(R.id.imgPremio); titulo = itemView.findViewById(R.id.titulo); reepoints = itemView.findViewById(R.id.reepoints); } } private PremiosViewHolder aViewHolder; @NonNull @Override public PremiosViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.premios_list, parent, false); aViewHolder = new PremiosViewHolder(view); return aViewHolder; } @Override public void onBindViewHolder(@NonNull PremiosViewHolder holder, int position) { holder.image.setImageResource(premiosModels.get(position).getItem()); holder.titulo.setText(premiosModels.get(position).getTitulo()); holder.reepoints.setText(premiosModels.get(position).getPontos()); } @Override public int getItemCount() { return premiosModels.size(); } }
31.534483
107
0.722253
5340cfe27207406f5cbc7f365564d11416bc2463
1,144
package com.sypht; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.junit.Rule; import org.junit.contrib.java.lang.system.EnvironmentVariables; import java.io.IOException; /** * Unit test for simple App. */ public class OAuthClientTest extends TestCase { @Rule public final EnvironmentVariables environmentVariables = new EnvironmentVariables(); public OAuthClientTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(OAuthClientTest.class); } @Override protected void setUp() throws Exception { environmentVariables.set("OAUTH_AUDIENCE", "https://api.sypht.com"); } /** * Test the OAuth Login */ public void testLogin() throws IOException { OAuthClient client = new OAuthClient(); String token = client.login(); assertTrue("no response from login service", token != null); assertTrue("doesn't look like a JWT Token", token.startsWith("eyJ")); } }
24.869565
77
0.66958
269199fd4a68958a118015de2ef4a040dbfa7b30
3,358
/* * Copyright 2019 Insurance Australia Group Limited * * 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.mark59.core.utils; import java.security.MessageDigest; import java.util.Arrays; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; /** * A simple encryption program to allow for non clear-case entry of passwords in scripts. <br> * It is <b>NOT</b> meant to be used when a high level of security is required.<br> * Reference: https://howtodoinjava.com/security/java-aes-encryption-example * * @author Philip Webb * Written: Australian Winter 2019 */ public class SimpleAES { private static SecretKeySpec secretKey; private static byte[] key; /** * sets the class key * @param myKey passed key */ public static void setKey(String myKey) { MessageDigest sha = null; try { key = myKey.getBytes("UTF-8"); sha = MessageDigest.getInstance("SHA-1"); } catch (Exception e) { e.printStackTrace(); } key = sha.digest(key); key = Arrays.copyOf(key, 16); secretKey = new SecretKeySpec(key, "AES"); } /** * @param strToEncrypt string to encrypt * @param secret secret * @return encrypted string */ public static String encrypt(String strToEncrypt, String secret) { try { setKey(secret); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))); } catch (Exception e) { System.out.println("Error while encrypting: " + e.toString()); } return null; } /** * @param strToDecrypt string to decrypt * @return decrypted string */ public static String decrypt(String strToDecrypt) { return decrypt(strToDecrypt, Mark59Constants.REFERENCE); } /** * @param strToDecrypt string to decrypt * @param secret secret * @return decrypted string */ public static String decrypt(String strToDecrypt, String secret) { try { setKey(secret); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); } catch (Exception e) { System.out.println("Error while decrypting: " + e.toString()); } return null; } /** * uncomment and run this main to see how encrypt/decrypt works on a given string. * @param args no args required */ public static void main(String[] args) { // String originalString = "My test string!"; // String encryptedString = SimpleAES.encrypt(originalString, Mark59Constants.REFERENCE ); // String decryptedString = SimpleAES.decrypt(encryptedString, Mark59Constants.REFERENCE); // // System.out.println(originalString); // System.out.println(encryptedString); // System.out.println(decryptedString); } }
29.716814
94
0.712031
debe99785c33c02f2e4d02af03ca81e85b880c29
491
package org.maltparser.parser.history; import org.maltparser.core.exception.MaltChainedException; import org.maltparser.parser.history.action.GuideUserAction; /** * * @author Johan Hall */ public interface HistoryNode { public HistoryNode getPreviousNode(); public GuideUserAction getAction(); public void setAction(GuideUserAction action); public void setPreviousNode(HistoryNode node); public int getPosition(); public void clear() throws MaltChainedException; }
28.882353
61
0.778004
577627fdc98f661cc783c1ce1e61f94cf94003ce
303
package org.jeecg.modules.device.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.jeecg.modules.device.entity.Device; /** * @Description: 设备信息 * @Author: jeecg-boot * @Date: 2022-01-19 * @Version: V1.0 */ public interface DeviceMapper extends BaseMapper<Device> { }
18.9375
58
0.735974
508531f2a53177336fd919509be221d327564274
3,682
package com.test.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import com.test.bean.Person; /** * 演示反射的使用: * 通过反射找到方法名,参数名等 * */ public class TestReflectUtil { /** * 根据指定的类,将List集合转换成json格式进行输出。 * 注:只能处理基本类型,以及ByteEnum的实现类,java.util.Date * * @param className 全路径类名 * @param col list集合 * @param prefix 产生的json传的前缀,默认为 "list" * @return json格式的字符串 * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException * @throws InvocationTargetException * @throws IllegalArgumentException */ @SuppressWarnings("unchecked") public static <T> String listToJson(String className,List<T>col,String prefix) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ if(col==null || col.size()==0 || className==null || className.equals("") ) return ""; if(prefix==null || prefix.equals("")) prefix = "\"list\""; StringBuilder sb = new StringBuilder("{"+prefix+":["); Class clazz = Class.forName(className); //使用LinkedHashMap保证输出的顺序一致 LinkedHashMap<String,Method> methodMap = new LinkedHashMap<String, Method>(); //性能优化:第一次获取所有的method以后,缓存到Map,提高效率。 for(int k=0;k<col.size();k++){ Object obj = col.get(k); if(k==0){ Method[] methods = clazz.getMethods(); for(int i=0;i<methods.length;i++){ if(i==0) sb.append("{"); Method method = methods[i]; String methodName = method.getName(); if(methodName.equals("getClass")) continue; if(methodName.startsWith("get")){ String proName = methodName.substring(3,4).toLowerCase()+methodName.substring(4); String proValue = getObjValue(obj, method); sb.append("\""+proName+"\":\""+proValue+"\","); methodMap.put(proName, method); } } }else{ for (String proName : methodMap.keySet()) { String proValue = getObjValue(obj, methodMap.get(proName)); sb.append("\"" + proName + "\":\"" + proValue + "\","); } } String tempStr = sb.substring(0, sb.length()-1); sb = new StringBuilder(tempStr); sb.append("},{"); } String tempStr = sb.substring(0, sb.length()-2); sb = new StringBuilder(tempStr).append("]}"); return sb.toString(); } /** * 获得obj对象,调用method后,获得的方法值。 obj.method() * @param obj * @param method * @return * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static String getObjValue(Object obj,Method method) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{ String proValue = null; Object tempValue = method.invoke(obj,new Object[]{}); if(tempValue instanceof Date){ SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); proValue = formate.format((Date)tempValue); }else{ proValue = tempValue.toString(); } return proValue; } /** * @param args */ public static void main(String[] args) throws Exception{ List<Person>list = new ArrayList<Person>(); Person p1 = new Person("张三", 20); Person p2 = new Person("李四", 22); Person p3 = new Person("王五", 24); for(int i=0;i<1;i++){ list.add(p1); list.add(p2); list.add(p3); } long t1 = System.currentTimeMillis(); System.out.println(listToJson("com.test.bean.Person", list, "list")); long t2 = System.currentTimeMillis(); System.out.println("共耗时:"+(t2-t1)+"毫秒"); } }
27.684211
212
0.667572
0be2eae61d9a0bcd1ec6fa451c2b53883b2413cf
1,414
package fwlib32; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; /** * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class EMBLSI extends Structure { public short Collision; public short CarrierSenseLost; public short DelayOver; public short Underrun; public short SendParityError; public short AlignmentError; public short CrcError; public short Overrun; public short FrameLengthViolation; public short RecvParityError; public EMBLSI() { super(); } protected List<String> getFieldOrder() { return Arrays.asList("Collision", "CarrierSenseLost", "DelayOver", "Underrun", "SendParityError", "AlignmentError", "CrcError", "Overrun", "FrameLengthViolation", "RecvParityError"); } public EMBLSI(Pointer peer) { super(peer); } public static class ByReference extends EMBLSI implements Structure.ByReference { }; public static class ByValue extends EMBLSI implements Structure.ByValue { }; }
37.210526
195
0.743281
d22c35d36ff1dcebcde365199e1441ac943a8395
635
package com.bird.gateway.web.pipe.before.authorize; import com.bird.core.session.BirdSession; import org.springframework.web.server.ServerWebExchange; /** * @author liuxx * @date 2018/12/3 */ public interface IAuthorizeManager { /** * 解析session信息 * @param exchange exchange * @return session */ BirdSession parseSession(ServerWebExchange exchange); /** * 校验权限信息 * @param session session * @param permissions permissions * @param checkAll checkAll * @return true or false */ Boolean checkPermissions(BirdSession session,String[] permissions, boolean checkAll); }
22.678571
89
0.689764
453cb3aa01534e02b698075d6f517c024e2f9663
381
package roth.lib.java.code.java; public enum JavaModifier { STATIC, FINAL, ABSTRACT, SYNCHRONIZED, TRANSIENT, VOLATILE, NATIVE, STRICTFP, DEFAULT; @Override public String toString() { return name().toLowerCase(); } public static JavaModifier parse(String value) { try { return valueOf(value); } catch(Exception e) { } return null; } }
10.885714
47
0.661417
de5271bb147b5b57de1214e9b142e423e8c951d9
11,847
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.xray.strategy; import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorderBuilder; import com.amazonaws.xray.emitters.Emitter; import com.amazonaws.xray.entities.FacadeSegment; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.SegmentImpl; import com.amazonaws.xray.entities.Subsegment; import com.amazonaws.xray.entities.SubsegmentImpl; import com.amazonaws.xray.entities.TraceHeader; import com.amazonaws.xray.entities.TraceID; import com.amazonaws.xray.strategy.sampling.LocalizedSamplingStrategy; import org.junit.Assert; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.mockito.Mockito; @FixMethodOrder(MethodSorters.JVM) public class DefaultStreamingStrategyTest { @Before public void setupAWSXRay() { Emitter blankEmitter = Mockito.mock(Emitter.class); LocalizedSamplingStrategy defaultSamplingStrategy = new LocalizedSamplingStrategy(); Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.anyObject()); Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.anyObject()); AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard() .withEmitter(blankEmitter) .withSamplingStrategy(defaultSamplingStrategy) .build()); AWSXRay.clearTraceEntity(); } @Test public void testDefaultStreamingStrategyRequiresStreaming() { DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1); Segment smallSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "small"); Assert.assertFalse(defaultStreamingStrategy.requiresStreaming(smallSegment)); Segment bigSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "big"); bigSegment.addSubsegment(new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "big_child", bigSegment)); bigSegment.addSubsegment(new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "big_child", bigSegment)); Assert.assertTrue(defaultStreamingStrategy.requiresStreaming(bigSegment)); } @Test public void testDefaultStreamingStrategyDoesNotRequireStreaming() { DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1); Segment smallSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "small"); Assert.assertFalse(defaultStreamingStrategy.requiresStreaming(smallSegment)); } @Test public void testingBasicStreamingFunctionality() { DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1); TraceID traceId = new TraceID(); Segment segment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", traceId); Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test", segment); Subsegment subsegment1 = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "test", segment); segment.addSubsegment(subsegment); segment.addSubsegment(subsegment1); segment.setStartTime(1.0); subsegment.setStartTime(1.0); subsegment1.setStartTime(1.0); subsegment.end(); defaultStreamingStrategy.streamSome(segment, AWSXRay.getGlobalRecorder().getEmitter()); Assert.assertTrue(segment.getTotalSize().intValue() == 1); } //test to see if the correct actions are being taken in streamSome (children get removed from parent) @Test public void testStreamSomeChildrenRemovedFromParent() { TraceID traceId = new TraceID(); DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1); Segment bigSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "big", traceId); bigSegment.setStartTime(1.0); for (int i = 0; i < 5; i++) { Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "child" + i, bigSegment); subsegment.setStartTime(1.0); bigSegment.addSubsegment(subsegment); subsegment.end(); } Assert.assertTrue(defaultStreamingStrategy.requiresStreaming(bigSegment)); defaultStreamingStrategy.streamSome(bigSegment, AWSXRay.getGlobalRecorder().getEmitter()); Assert.assertTrue(bigSegment.getTotalSize().intValue() == 0); } //test to see if the correct actions are being taken in streamSome (children do NOT get removed from parent due to subsegments //being in progress.) @Test public void testStreamSomeChildrenNotRemovedFromParent() { TraceID traceId = new TraceID(); DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1); Segment bigSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "big", traceId); bigSegment.setStartTime(1.0); for (int i = 0; i < 5; i++) { Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "child" + i, bigSegment); subsegment.setStartTime(1.0); bigSegment.addSubsegment(subsegment); } Assert.assertTrue(defaultStreamingStrategy.requiresStreaming(bigSegment)); defaultStreamingStrategy.streamSome(bigSegment, AWSXRay.getGlobalRecorder().getEmitter()); Assert.assertTrue(bigSegment.getTotalSize().intValue() == 5); } @Test public void testMultithreadedStreamSome() { DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1); Segment segment = AWSXRay.beginSegment("big"); Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "subsegment1", segment); subsegment.setStartTime(1.0); segment.addSubsegment(subsegment); subsegment.end(); Thread thread1 = new Thread(() -> { AWSXRay.setTraceEntity(segment); AWSXRay.beginSubsegment("thread1"); AWSXRay.endSubsegment(); }); Thread thread2 = new Thread(() -> { AWSXRay.setTraceEntity(segment); AWSXRay.beginSubsegment("thread2"); AWSXRay.endSubsegment(); }); thread1.start(); thread2.start(); for (Thread thread : new Thread[]{thread1, thread2}) { try { thread.join(); } catch (InterruptedException e) { return; } } Assert.assertTrue(AWSXRay.getTraceEntity().getName().equals("big")); //asserts that all subsegments are added correctly. Assert.assertTrue(AWSXRay.getTraceEntity().getTotalSize().intValue() == 3); defaultStreamingStrategy.streamSome(segment, AWSXRay.getGlobalRecorder().getEmitter()); Assert.assertTrue(segment.getTotalSize().intValue() == 0); } @Test public void testBushyandSpindlySegmentTreeStreaming() { TraceID traceId = new TraceID(); Segment bigSegment = new SegmentImpl(AWSXRay.getGlobalRecorder(), "big", traceId); bigSegment.setStartTime(1.0); for (int i = 0; i < 5; i++) { Subsegment subsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "child" + i, bigSegment); subsegment.setStartTime(1.0); bigSegment.addSubsegment(subsegment); subsegment.end(); } SubsegmentImpl holder = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "big_child0", bigSegment); holder.setStartTime(1.0); bigSegment.addSubsegment(holder); holder.end(); SubsegmentImpl holder1 = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "big_child1", bigSegment); holder1.setStartTime(1.0); bigSegment.addSubsegment(holder1); holder1.end(); SubsegmentImpl holder2 = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "big_child2", bigSegment); holder2.setStartTime(1.0); bigSegment.addSubsegment(holder2); holder2.end(); DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1); Assert.assertTrue(defaultStreamingStrategy.requiresStreaming(bigSegment)); defaultStreamingStrategy.streamSome(bigSegment, AWSXRay.getGlobalRecorder().getEmitter()); Assert.assertTrue(bigSegment.getReferenceCount() == 0); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void testDefaultStreamingStrategyMaxSegmentSizeParameterValidation() { DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(-1); } //test to see if FacadeSegment can be streamed out correctly @Test public void testDefaultStreamingStrategyForLambdaTraceContext() { DefaultStreamingStrategy defaultStreamingStrategy = new DefaultStreamingStrategy(1); //if FacadeSegment size is larger than maxSegmentSize and only the first subsegment is completed, first subsegment will be //streamed out FacadeSegment facadeSegmentOne = new FacadeSegment(AWSXRay.getGlobalRecorder(), new TraceID(), "", TraceHeader.SampleDecision.SAMPLED); Subsegment firstSubsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "FirstSubsegment", facadeSegmentOne); Subsegment secondSubsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "SecondSubsegment", facadeSegmentOne); facadeSegmentOne.addSubsegment(firstSubsegment); facadeSegmentOne.addSubsegment(secondSubsegment); firstSubsegment.end(); Assert.assertTrue(facadeSegmentOne.getTotalSize().intValue() == 2); defaultStreamingStrategy.streamSome(facadeSegmentOne, AWSXRay.getGlobalRecorder().getEmitter()); Assert.assertTrue(facadeSegmentOne.getTotalSize().intValue() == 1); Subsegment tempOne = facadeSegmentOne.getSubsegments().get(0); Assert.assertEquals("SecondSubsegment", tempOne.getName()); //if FarcadeSegment size is larger than maxSegmentSize and only the second subsegment is completed, second subsegment will //be streamed out FacadeSegment facadeSegmentTwo = new FacadeSegment(AWSXRay.getGlobalRecorder(), new TraceID(), "", TraceHeader.SampleDecision.SAMPLED); Subsegment thirdSubsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "ThirdSubsegment", facadeSegmentTwo); Subsegment fourthSubsegment = new SubsegmentImpl(AWSXRay.getGlobalRecorder(), "FourthSubsegment", facadeSegmentTwo); facadeSegmentTwo.addSubsegment(thirdSubsegment); facadeSegmentTwo.addSubsegment(fourthSubsegment); fourthSubsegment.end(); Assert.assertTrue(facadeSegmentTwo.getTotalSize().intValue() == 2); defaultStreamingStrategy.streamSome(facadeSegmentTwo, AWSXRay.getGlobalRecorder().getEmitter()); Assert.assertTrue(facadeSegmentTwo.getTotalSize().intValue() == 1); Subsegment tempTwo = facadeSegmentTwo.getSubsegments().get(0); Assert.assertEquals("ThirdSubsegment", tempTwo.getName()); } }
45.918605
130
0.699418
56291c48a7b0882afd6665035dbe6f8b770cb4a7
1,310
package com.github.rstockbridge.showstats; import com.github.rstockbridge.showstats.api.models.City; import com.github.rstockbridge.showstats.api.models.Coordinates; import com.github.rstockbridge.showstats.api.models.Setlist; import com.github.rstockbridge.showstats.api.models.SetlistArtist; import com.github.rstockbridge.showstats.api.models.SetlistVenue; import com.github.rstockbridge.showstats.appmodels.UserStatistics; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public final class UserStatisticsUnitTests { private String userId = "rebecca"; private UserStatistics userStatistics; @Before public void initialize() { final List<Setlist> setlists = new ArrayList<>(); final Setlist setlist1 = new Setlist( "123abc", "01-01-2018", new SetlistArtist("artistA", "Artist A"), new SetlistVenue("Venue A", new City("City A", new Coordinates(42.3314, -83.0458))), "http://www.artistA.com"); setlists.add(setlist1); userStatistics = new UserStatistics(userId, setlists); } @Test public void testUserId() { assertEquals(userStatistics.getUserId(), userId); } }
30.465116
100
0.69771
236fc83e51799cb3fae209906fd24168edee4cfd
5,140
package net.sitemorph.protostore.sql; import net.sitemorph.protostore.CrudException; import net.sitemorph.protostore.CrudIterator; import net.sitemorph.protostore.MessageNotFoundException; import com.google.protobuf.ByteString; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Message; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Iterator that uses builder fields to index a prepared statement. * * Assumes that the prepared statement uses the field list from the builder * * @author dak * * TODO implement type converter interface for type mappers and allow * registration to allow arbitrary type mapping. */ public class DbFieldIterator<T extends Message> implements CrudIterator<T> { private final ResultSet resultSet; private Message.Builder prototype; private boolean readAhead = false; private boolean hasNext = false; public DbFieldIterator(T.Builder builder, ResultSet resultSet) { // nasty setup required prototype = builder; this.resultSet = resultSet; } public static String getCrudFieldList(Descriptor descriptor, String alias, FieldDescriptor... skip) { StringBuilder result = new StringBuilder(); List<FieldDescriptor> fields = descriptor.getFields(); Set<FieldDescriptor> skipSet = new HashSet<>(); for (int i = 0; null != skip && i < skip.length; i++) { skipSet.add(skip[i]); } for (FieldDescriptor field : fields) { if (skipSet.contains(field)) { continue; } if (null != alias) { result.append(alias) .append("."); } result.append(field.getName()) .append(", "); } result.delete(result.length() - 2, result.length()); return result.toString(); } public static String getCrudFieldList(Descriptor descriptor, FieldDescriptor... skip) { return getCrudFieldList(descriptor, null, skip); } @SuppressWarnings("unchecked") @Override public T next() throws CrudException { Message.Builder next = prototype.clone(); try { if (!readAhead) { hasNext = resultSet.next(); } else { readAhead = false; } if (!hasNext) { throw new MessageNotFoundException("Called next when no more records"); } Descriptor descriptor = prototype.getDescriptorForType(); int offset = 1; for (FieldDescriptor field : descriptor.getFields()) { Object value; switch (field.getType()) { case DOUBLE : value = resultSet.getDouble(offset++); break; case FLOAT : value = resultSet.getFloat(offset++); break; case INT64: case SINT64: case SFIXED64: case UINT64: case FIXED64 : value = resultSet.getLong(offset++); break; case SINT32: case UINT32: case SFIXED32: case FIXED32: case INT32: value = resultSet.getInt(offset++); break; case BOOL: value = resultSet.getBoolean(offset++); break; case STRING: value = resultSet.getString(offset++); break; case ENUM : String key = resultSet.getString(offset++); EnumValueDescriptor enumDescriptor = field.getEnumType().findValueByName(key); if (null != key && null == enumDescriptor) { throw new CrudException("Error finding enum " + field.getEnumType().getName() + " value " + key); } value = enumDescriptor; break; case BYTES : byte[] data = resultSet.getBytes(offset++); if (null != data && 0 < data.length) { value = ByteString.copyFrom(data); } else { value = null; } break; //case GROUP: //case MESSAGE: default: throw new CrudException("Unsupported proto field type: " + field.getType().name()); } if (resultSet.wasNull() || null == value) { next.clearField(field); } else { next.setField(field, value); } } readAhead = false; return (T) next.build(); } catch (SQLException e) { throw new CrudException("Error reading proto field", e); } } @Override public boolean hasNext() throws CrudException { try { if (!readAhead) { hasNext = resultSet.next(); readAhead = true; } return hasNext; } catch (SQLException e) { throw new CrudException("Error checking for next crud object", e); } } @Override public void close() throws CrudException { try { resultSet.close(); } catch (SQLException e) { throw new CrudException("Error closing crud iterator", e); } } }
29.54023
79
0.601167
d262f6f4fb1ffdaed3f6fd4d21a23d3c764ab43a
991
public void notifyStartup(StartupEvent event) { logger.info("Running revision info..."); Process pr = null; try { pr = Runtime.getRuntime().exec("svn info"); } catch (IOException e) { e.printStackTrace(); } logger.info("Running revision info...done."); logger.info("Saving revision info output..."); try { BufferedReader procout = new BufferedReader(new InputStreamReader(pr.getInputStream())); BufferedWriter fileout = new BufferedWriter(new FileWriter(Controler.getOutputFilename(this.filename))); String line; while ((line = procout.readLine()) != null) { fileout.write(line); fileout.write(System.getProperty("line.separator")); } fileout.close(); } catch (IOException e) { e.printStackTrace(); } logger.info("Saving revision info output...done."); }
39.64
116
0.565086
490d283b202faaed78aa9b9bca0303aff806d0f7
1,174
/* * 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.aliyuncs.arms.transform.v20190808; import com.aliyuncs.arms.model.v20190808.UpdateAlertContactResponse; import com.aliyuncs.transform.UnmarshallerContext; public class UpdateAlertContactResponseUnmarshaller { public static UpdateAlertContactResponse unmarshall(UpdateAlertContactResponse updateAlertContactResponse, UnmarshallerContext _ctx) { updateAlertContactResponse.setRequestId(_ctx.stringValue("UpdateAlertContactResponse.RequestId")); updateAlertContactResponse.setIsSuccess(_ctx.booleanValue("UpdateAlertContactResponse.IsSuccess")); return updateAlertContactResponse; } }
39.133333
135
0.803237
3822ce6525395f3a4c261cf0f307ed37884d1a51
91
package com.mobile.communication.domain.enums; public enum StatusCode { OK, KO }
11.375
46
0.703297
7f658ca86ea4c62e1c19ddee0103bc26e1b2a199
1,275
/* By: facug91 From: http://coj.uci.cu/24h/problem.xhtml?abb=2549 Name: SETNJA Number: 2549 Date: 22/10/2013 */ import java.text.DecimalFormat; import java.util.Scanner; public class SETNJA { static int square (int n) { return (n * n); } public static void main (String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int[] x = new int[n]; int[] y = new int[n]; int pointx = 0; int pointy = 0; for (int i=0; i<n; i++) { x[i] = stdin.nextInt(); y[i] = stdin.nextInt(); pointx += x[i]; pointy += y[i]; } System.out.println(pointx+" "+pointy); Double min = Math.sqrt(square(pointx) + square(pointy)); //distancia original Double aux; int j = 0; while ((min > 0) && (j < n)) { pointx -= x[j]; pointy -= y[j]; aux = Math.sqrt(square(pointx) + square(pointy)); if (aux < min) { min = aux; } pointx += x[j]; pointy += y[j]; j++; } DecimalFormat df = new DecimalFormat("0.00"); String result = df.format(min); result = result.substring(0,result.length()-3)+"."+result.substring(result.length()-2,result.length()); System.out.println(result); stdin.close(); } }
19.615385
106
0.549804
2eecc1198c77435b8b7ec3acd3c4dc1d059e53a6
1,539
/** * boilerpipe * * Copyright (c) 2009, 2014 Christian Kohlschütter * * The author licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kohlschutter.boilerpipe.sax; import java.io.ByteArrayInputStream; import java.nio.charset.Charset; import org.xml.sax.InputSource; /** * An {@link InputSourceable} for {@link HTMLFetcher}. */ public class HTMLDocument implements InputSourceable { private final Charset charset; private final byte[] data; public HTMLDocument(final byte[] data, final Charset charset) { this.data = data; this.charset = charset; } public HTMLDocument(final String data) { Charset cs = Charset.forName("utf-8"); this.data = data.getBytes(cs); this.charset = cs; } public Charset getCharset() { return charset; } public byte[] getData() { return data; } public InputSource toInputSource() { final InputSource is = new InputSource(new ByteArrayInputStream(data)); is.setEncoding(charset.name()); return is; } }
27
77
0.7141
0fdadb22354b393d0bc687ef86093cc1c7b8ae84
24,232
package com.dianwoda.test.bassy.db.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class DingdingNotifyExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public DingdingNotifyExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andChatidIsNull() { addCriterion("chatid is null"); return (Criteria) this; } public Criteria andChatidIsNotNull() { addCriterion("chatid is not null"); return (Criteria) this; } public Criteria andChatidEqualTo(String value) { addCriterion("chatid =", value, "chatid"); return (Criteria) this; } public Criteria andChatidNotEqualTo(String value) { addCriterion("chatid <>", value, "chatid"); return (Criteria) this; } public Criteria andChatidGreaterThan(String value) { addCriterion("chatid >", value, "chatid"); return (Criteria) this; } public Criteria andChatidGreaterThanOrEqualTo(String value) { addCriterion("chatid >=", value, "chatid"); return (Criteria) this; } public Criteria andChatidLessThan(String value) { addCriterion("chatid <", value, "chatid"); return (Criteria) this; } public Criteria andChatidLessThanOrEqualTo(String value) { addCriterion("chatid <=", value, "chatid"); return (Criteria) this; } public Criteria andChatidLike(String value) { addCriterion("chatid like", value, "chatid"); return (Criteria) this; } public Criteria andChatidNotLike(String value) { addCriterion("chatid not like", value, "chatid"); return (Criteria) this; } public Criteria andChatidIn(List<String> values) { addCriterion("chatid in", values, "chatid"); return (Criteria) this; } public Criteria andChatidNotIn(List<String> values) { addCriterion("chatid not in", values, "chatid"); return (Criteria) this; } public Criteria andChatidBetween(String value1, String value2) { addCriterion("chatid between", value1, value2, "chatid"); return (Criteria) this; } public Criteria andChatidNotBetween(String value1, String value2) { addCriterion("chatid not between", value1, value2, "chatid"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("`type` is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("`type` is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(Byte value) { addCriterion("`type` =", value, "type"); return (Criteria) this; } public Criteria andTypeNotEqualTo(Byte value) { addCriterion("`type` <>", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThan(Byte value) { addCriterion("`type` >", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(Byte value) { addCriterion("`type` >=", value, "type"); return (Criteria) this; } public Criteria andTypeLessThan(Byte value) { addCriterion("`type` <", value, "type"); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(Byte value) { addCriterion("`type` <=", value, "type"); return (Criteria) this; } public Criteria andTypeIn(List<Byte> values) { addCriterion("`type` in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<Byte> values) { addCriterion("`type` not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(Byte value1, Byte value2) { addCriterion("`type` between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(Byte value1, Byte value2) { addCriterion("`type` not between", value1, value2, "type"); return (Criteria) this; } public Criteria andContentIsNull() { addCriterion("content is null"); return (Criteria) this; } public Criteria andContentIsNotNull() { addCriterion("content is not null"); return (Criteria) this; } public Criteria andContentEqualTo(String value) { addCriterion("content =", value, "content"); return (Criteria) this; } public Criteria andContentNotEqualTo(String value) { addCriterion("content <>", value, "content"); return (Criteria) this; } public Criteria andContentGreaterThan(String value) { addCriterion("content >", value, "content"); return (Criteria) this; } public Criteria andContentGreaterThanOrEqualTo(String value) { addCriterion("content >=", value, "content"); return (Criteria) this; } public Criteria andContentLessThan(String value) { addCriterion("content <", value, "content"); return (Criteria) this; } public Criteria andContentLessThanOrEqualTo(String value) { addCriterion("content <=", value, "content"); return (Criteria) this; } public Criteria andContentLike(String value) { addCriterion("content like", value, "content"); return (Criteria) this; } public Criteria andContentNotLike(String value) { addCriterion("content not like", value, "content"); return (Criteria) this; } public Criteria andContentIn(List<String> values) { addCriterion("content in", values, "content"); return (Criteria) this; } public Criteria andContentNotIn(List<String> values) { addCriterion("content not in", values, "content"); return (Criteria) this; } public Criteria andContentBetween(String value1, String value2) { addCriterion("content between", value1, value2, "content"); return (Criteria) this; } public Criteria andContentNotBetween(String value1, String value2) { addCriterion("content not between", value1, value2, "content"); return (Criteria) this; } public Criteria andInsTmIsNull() { addCriterion("ins_tm is null"); return (Criteria) this; } public Criteria andInsTmIsNotNull() { addCriterion("ins_tm is not null"); return (Criteria) this; } public Criteria andInsTmEqualTo(Date value) { addCriterion("ins_tm =", value, "insTm"); return (Criteria) this; } public Criteria andInsTmNotEqualTo(Date value) { addCriterion("ins_tm <>", value, "insTm"); return (Criteria) this; } public Criteria andInsTmGreaterThan(Date value) { addCriterion("ins_tm >", value, "insTm"); return (Criteria) this; } public Criteria andInsTmGreaterThanOrEqualTo(Date value) { addCriterion("ins_tm >=", value, "insTm"); return (Criteria) this; } public Criteria andInsTmLessThan(Date value) { addCriterion("ins_tm <", value, "insTm"); return (Criteria) this; } public Criteria andInsTmLessThanOrEqualTo(Date value) { addCriterion("ins_tm <=", value, "insTm"); return (Criteria) this; } public Criteria andInsTmIn(List<Date> values) { addCriterion("ins_tm in", values, "insTm"); return (Criteria) this; } public Criteria andInsTmNotIn(List<Date> values) { addCriterion("ins_tm not in", values, "insTm"); return (Criteria) this; } public Criteria andInsTmBetween(Date value1, Date value2) { addCriterion("ins_tm between", value1, value2, "insTm"); return (Criteria) this; } public Criteria andInsTmNotBetween(Date value1, Date value2) { addCriterion("ins_tm not between", value1, value2, "insTm"); return (Criteria) this; } public Criteria andMsgIdIsNull() { addCriterion("msg_id is null"); return (Criteria) this; } public Criteria andMsgIdIsNotNull() { addCriterion("msg_id is not null"); return (Criteria) this; } public Criteria andMsgIdEqualTo(String value) { addCriterion("msg_id =", value, "msgId"); return (Criteria) this; } public Criteria andMsgIdNotEqualTo(String value) { addCriterion("msg_id <>", value, "msgId"); return (Criteria) this; } public Criteria andMsgIdGreaterThan(String value) { addCriterion("msg_id >", value, "msgId"); return (Criteria) this; } public Criteria andMsgIdGreaterThanOrEqualTo(String value) { addCriterion("msg_id >=", value, "msgId"); return (Criteria) this; } public Criteria andMsgIdLessThan(String value) { addCriterion("msg_id <", value, "msgId"); return (Criteria) this; } public Criteria andMsgIdLessThanOrEqualTo(String value) { addCriterion("msg_id <=", value, "msgId"); return (Criteria) this; } public Criteria andMsgIdLike(String value) { addCriterion("msg_id like", value, "msgId"); return (Criteria) this; } public Criteria andMsgIdNotLike(String value) { addCriterion("msg_id not like", value, "msgId"); return (Criteria) this; } public Criteria andMsgIdIn(List<String> values) { addCriterion("msg_id in", values, "msgId"); return (Criteria) this; } public Criteria andMsgIdNotIn(List<String> values) { addCriterion("msg_id not in", values, "msgId"); return (Criteria) this; } public Criteria andMsgIdBetween(String value1, String value2) { addCriterion("msg_id between", value1, value2, "msgId"); return (Criteria) this; } public Criteria andMsgIdNotBetween(String value1, String value2) { addCriterion("msg_id not between", value1, value2, "msgId"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("`status` is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("`status` is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("`status` =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("`status` <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("`status` >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("`status` >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("`status` <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("`status` <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("`status` in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("`status` not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("`status` between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("`status` not between", value1, value2, "status"); return (Criteria) this; } public Criteria andModifyTmIsNull() { addCriterion("modify_tm is null"); return (Criteria) this; } public Criteria andModifyTmIsNotNull() { addCriterion("modify_tm is not null"); return (Criteria) this; } public Criteria andModifyTmEqualTo(Date value) { addCriterion("modify_tm =", value, "modifyTm"); return (Criteria) this; } public Criteria andModifyTmNotEqualTo(Date value) { addCriterion("modify_tm <>", value, "modifyTm"); return (Criteria) this; } public Criteria andModifyTmGreaterThan(Date value) { addCriterion("modify_tm >", value, "modifyTm"); return (Criteria) this; } public Criteria andModifyTmGreaterThanOrEqualTo(Date value) { addCriterion("modify_tm >=", value, "modifyTm"); return (Criteria) this; } public Criteria andModifyTmLessThan(Date value) { addCriterion("modify_tm <", value, "modifyTm"); return (Criteria) this; } public Criteria andModifyTmLessThanOrEqualTo(Date value) { addCriterion("modify_tm <=", value, "modifyTm"); return (Criteria) this; } public Criteria andModifyTmIn(List<Date> values) { addCriterion("modify_tm in", values, "modifyTm"); return (Criteria) this; } public Criteria andModifyTmNotIn(List<Date> values) { addCriterion("modify_tm not in", values, "modifyTm"); return (Criteria) this; } public Criteria andModifyTmBetween(Date value1, Date value2) { addCriterion("modify_tm between", value1, value2, "modifyTm"); return (Criteria) this; } public Criteria andModifyTmNotBetween(Date value1, Date value2) { addCriterion("modify_tm not between", value1, value2, "modifyTm"); return (Criteria) this; } public Criteria andNotifyToIsNull() { addCriterion("notify_to is null"); return (Criteria) this; } public Criteria andNotifyToIsNotNull() { addCriterion("notify_to is not null"); return (Criteria) this; } public Criteria andNotifyToEqualTo(String value) { addCriterion("notify_to =", value, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToNotEqualTo(String value) { addCriterion("notify_to <>", value, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToGreaterThan(String value) { addCriterion("notify_to >", value, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToGreaterThanOrEqualTo(String value) { addCriterion("notify_to >=", value, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToLessThan(String value) { addCriterion("notify_to <", value, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToLessThanOrEqualTo(String value) { addCriterion("notify_to <=", value, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToLike(String value) { addCriterion("notify_to like", value, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToNotLike(String value) { addCriterion("notify_to not like", value, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToIn(List<String> values) { addCriterion("notify_to in", values, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToNotIn(List<String> values) { addCriterion("notify_to not in", values, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToBetween(String value1, String value2) { addCriterion("notify_to between", value1, value2, "notifyTo"); return (Criteria) this; } public Criteria andNotifyToNotBetween(String value1, String value2) { addCriterion("notify_to not between", value1, value2, "notifyTo"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
31.026889
102
0.56706
41ae8e1917152f37a1444e61b8b4305920bac511
8,338
/* * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.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. * * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) * SPDX-License-Identifier: Apache-2.0 */ package com.arcadedb.graphql; import com.arcadedb.database.RID; import com.arcadedb.exception.QueryParsingException; import com.arcadedb.query.sql.executor.Result; import com.arcadedb.query.sql.executor.ResultSet; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.*; public class GraphQLBasicTest extends AbstractGraphQLTest { @Test public void ridMapping() { executeTest((database) -> { final String types = "type Query {\n" +// " bookById(id: String): Book\n" +// "}\n\n" +// "type Book {\n" +// " id: String\n" +// " name: String\n" +// " pageCount: Int\n" +// " authors: [Author] @relationship(type: \"IS_AUTHOR_OF\", direction: IN)\n" +// "}\n\n" +// "type Author {\n" +// " id: String\n" +// " firstName: String\n" +// " lastName: String\n" +// "}"; database.command("graphql", types); RID rid = null; try (ResultSet resultSet = database.query("graphql", "{ bookById(id: \"book-1\"){" +// " rid @rid" +// " id" +// " name" +// " pageCount" +// " authors {" +// " firstName" +// " lastName" +// " }" +// "}" +// "}")) { Assertions.assertTrue(resultSet.hasNext()); final Result record = resultSet.next(); System.out.println(record.toJSON()); rid = record.getIdentity().get(); Assertions.assertNotNull(rid); Assertions.assertEquals(5, record.getPropertyNames().size()); Assertions.assertEquals(1, ((Collection) record.getProperty("authors")).size()); Assertions.assertFalse(resultSet.hasNext()); } return null; }); } @Test public void bookByName() { executeTest((database) -> { defineTypes(database); try (ResultSet resultSet = database.query("graphql", "{ bookByName(name: \"Harry Potter and the Philosopher's Stone\")}")) { Assertions.assertTrue(resultSet.hasNext()); final Result record = resultSet.next(); Assertions.assertEquals(4, record.getPropertyNames().size()); Assertions.assertEquals(1, ((Collection) record.getProperty("authors")).size()); Assertions.assertEquals("Harry Potter and the Philosopher's Stone", record.getProperty("name")); Assertions.assertFalse(resultSet.hasNext()); } try (ResultSet resultSet = database.query("graphql", "{ bookByName(name: \"Mr. brain\") }")) { Assertions.assertTrue(resultSet.hasNext()); final Result record = resultSet.next(); Assertions.assertEquals(4, record.getPropertyNames().size()); Assertions.assertEquals(1, ((Collection) record.getProperty("authors")).size()); Assertions.assertEquals("Mr. brain", record.getProperty("name")); Assertions.assertFalse(resultSet.hasNext()); } return null; }); } @Test public void bookByNameWrongParams() { executeTest((database) -> { defineTypes(database); try { database.query("graphql", "{ bookByName(wrong: \"Mr. brain\") }"); Assertions.fail(); } catch (QueryParsingException e) { // EXPECTED Assertions.assertEquals(QueryParsingException.class, e.getCause().getClass()); } return null; }); } @Test public void allBooks() { executeTest((database) -> { final String types = "type Query {\n" +// " bookById(id: String): Book\n" +// " books(where: String!): [Book!]!\n" +// "}\n\n" +// "type Book {\n" +// " id: String\n" +// " name: String\n" +// " pageCount: Int\n" +// " authors: [Author] @relationship(type: \"IS_AUTHOR_OF\", direction: IN)\n" +// "}\n\n" +// "type Author {\n" +// " id: String\n" +// " firstName: String\n" +// " lastName: String\n" +// "}"; database.command("graphql", types); try (ResultSet resultSet = database.query("graphql", "{ books }")) { Assertions.assertTrue(resultSet.hasNext()); Result record = resultSet.next(); Assertions.assertEquals(4, record.getPropertyNames().size()); Assertions.assertEquals(1, ((Collection) record.getProperty("authors")).size()); Assertions.assertTrue(resultSet.hasNext()); record = resultSet.next(); Assertions.assertEquals(4, record.getPropertyNames().size()); Assertions.assertEquals(1, ((Collection) record.getProperty("authors")).size()); Assertions.assertFalse(resultSet.hasNext()); } return null; }); } @Test public void allBooksWrongRelationshipDirective() { executeTest((database) -> { final String types = "type Query {\n" +// " bookById(id: String): Book\n" +// " books(where: String!): [Book!]!\n" +// "}\n\n" +// "type Book {\n" +// " id: String\n" +// " name: String\n" +// " pageCount: Int\n" +// " authors: [Author] @relationship(type: \"IS_AUTHOR_OF\", direction: IN)\n" +// "}\n\n" +// "type Author {\n" +// " id: String\n" +// " firstName: String\n" +// " lastName: String\n" +// "}"; database.command("graphql", types); try (ResultSet resultSet = database.query("graphql", "{ books { id\n name\n pageCount\n authors @relationship(type: \"WRONG\", direction: IN)} }")) { Assertions.assertTrue(resultSet.hasNext()); Result record = resultSet.next(); Assertions.assertEquals(4, record.getPropertyNames().size()); Assertions.assertEquals(0, countIterable(record.getProperty("authors"))); Assertions.assertTrue(resultSet.hasNext()); record = resultSet.next(); Assertions.assertEquals(4, record.getPropertyNames().size()); Assertions.assertEquals(0, countIterable(record.getProperty("authors"))); Assertions.assertFalse(resultSet.hasNext()); } return null; }); } @Test public void queryWhereCondition() { executeTest((database) -> { final String types = "type Query {\n" +// " bookById(id: String): Book\n" +// " books(where: WHERE): [Book!]!\n" +// "}\n\n" +// "type Book {\n" +// " id: String\n" +// " name: String\n" +// " pageCount: Int\n" +// " authors: [Author] @relationship(type: \"IS_AUTHOR_OF\", direction: IN)\n" +// "}\n\n" +// "type Author {\n" +// " id: String\n" +// " firstName: String\n" +// " lastName: String\n" +// "}"; database.command("graphql", types); try (ResultSet resultSet = database.query("graphql", "{ books( where: \"name = 'Mr. brain'\" ) }")) { Assertions.assertTrue(resultSet.hasNext()); Result record = resultSet.next(); Assertions.assertEquals(4, record.getPropertyNames().size()); Assertions.assertEquals("book-2", record.getProperty("id")); Assertions.assertEquals("Mr. brain", record.getProperty("name")); Assertions.assertEquals(422, (Integer) record.getProperty("pageCount")); Assertions.assertEquals(1, ((Collection) record.getProperty("authors")).size()); Assertions.assertFalse(resultSet.hasNext()); } return null; }); } }
34.312757
155
0.576157
df4f89b9b7ba78586571294552eadffed7135ea0
2,227
package com.example.pragyaagrawal.levelmoneytask.adapters; import android.content.Context; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.pragyaagrawal.levelmoneytask.R; import com.example.pragyaagrawal.levelmoneytask.models.Transactions; import com.example.pragyaagrawal.levelmoneytask.utils.Utils; import java.util.List; public class TransactionsAdapter extends RecyclerView.Adapter<TransactionsViewHolder> { private List<Transactions> transactionsList; private Context context; public TransactionsAdapter(List<Transactions> transactionsList, Context context) { this.transactionsList = transactionsList; this.context = context; } @Override public TransactionsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View transactionView = inflater.inflate(R.layout.transaction_item, parent, false); //Return the a new Holder instance TransactionsViewHolder viewHolder = new TransactionsViewHolder(transactionView); return viewHolder; } @Override public void onBindViewHolder(TransactionsViewHolder holder, int position) { holder.tvMerchant.setText(transactionsList.get(position).getMerchant()); //Negative amount = debit, positive amount = credit. Centocents. 20000 centocents = $2. Double amount = Double.valueOf(transactionsList.get(position).getAmount())/20000; holder.tvAmount.setText(Utils.getFormattedCurrency(amount)); if (transactionsList.get(position).getAmount().contains("-")) { holder.tvAmount.setTextColor(Color.RED); }else { holder.tvAmount.setTextColor(Color.GREEN); } } @Override public int getItemCount() { if (transactionsList != null) { return transactionsList.size(); } return 0; } public void setTransactionsList(List<Transactions> transactionsList) { this.transactionsList = transactionsList; } }
34.796875
95
0.727436
d5c2646fc0ee1c2eebb9d50abe388c17c0753e68
329
package org.jeecg.modules.business.service; import org.jeecg.modules.business.entity.SysWarnUser; import com.baomidou.mybatisplus.extension.service.IService; /** * @Description: 报警短信接收人 * @Author: jeecg-boot * @Date: 2020-07-09 * @Version: V1.0 */ public interface ISysWarnUserService extends IService<SysWarnUser> { }
21.933333
68
0.759878
fe9728649d5a8f776976e44daaa5909c8bab1004
430
package s02.Cycle; /** * Description: NestedLoopTest * Author: silence * Update: silence(2017-04-20 16:47) */ public class NestedLoopTest { public static void main(String[] args) { //外层循环 for (int i = 0 ; i < 5 ; i++ ) { //内层循环 for (int j = 0; j < 3 ; j++ ) { System.out.println("i的值为:" + i + " j的值为:" + j); } } } }
19.545455
64
0.439535
ce4f2303c3f461703049fc06fdc456f71976bb00
396
// Math.pow requires doubles, returns a double public class Solution { public int titleToNumber(String s) { int ALPHABET=26; int n=s.length(); char[] letters = s.toCharArray(); int num=0; int base=1; for(int i=n-1; i>=0; i--, base*=ALPHABET){ int d=letters[i]-'A'+1; num+=d*base; } return num; } }
22
50
0.507576
4f9a234be134106126ccd98fdec8f47f5f41f0cf
3,630
package com.Nasa.ProjetoNasa.model; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.util.Date; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.SwingConstants; public class Utils { public static void ajustesBotao(JButton b, int x, int y, String s, String toolTip) { b.setBounds(x, y, b.getIcon().getIconWidth(), b.getIcon().getIconHeight()); b.setRolloverIcon(new ImageIcon(Utils.class.getResource(s))); b.setToolTipText(toolTip); b.setBackground(new Color(0, 0, 0, 0)); b.setForeground(Color.white); b.setFont(new Font("Consolas", Font.BOLD, 23)); b.setFocusPainted(false); b.setContentAreaFilled(false); b.setBorderPainted(false); b.setCursor(new Cursor(12)); b.setHorizontalTextPosition(SwingConstants.CENTER); b.setVerticalAlignment(SwingConstants.CENTER); b.setFont(new Font("Nasalization Rg", Font.BOLD, 15)); } public static void ajustesBotao(JButton b, String text, int x, int y, String toolTip) { b.setText("<html>"+text+"</html>".toUpperCase()); b.setBounds(x, y, 121, 62); b.setFocusPainted(false); b.setBorderPainted(false); b.setToolTipText(toolTip); b.setForeground(Color.white); b.setCursor(new Cursor(12)); b.setContentAreaFilled(false); b.setBackground(new Color(0, 0, 0, 0)); b.setVerticalAlignment(SwingConstants.CENTER); b.setHorizontalTextPosition(SwingConstants.CENTER); b.setFont(new Font("Nasalization Rg", Font.BOLD, 15)); b.setRolloverIcon(new ImageIcon(Utils.class.getResource("/02_botao_rolover.png"))); } public static void ajustesComboBox(JComboBox<String> c, int x, int y) { c.setBounds(x, y, 100, 30); c.setFont(new Font("Montserrat", Font.PLAIN, 14)); } @SuppressWarnings("deprecation") public static boolean validarData(String dia, String mes, String ano) { Date hoje = new Date(); Date min = new Date(1995 - 1900, 6-1, 1); Date d = new Date(); d.setDate(Integer.parseInt(dia)); d.setMonth(Integer.parseInt(mes)-1); d.setYear(Integer.parseInt(ano)-1900); if(Integer.parseInt(dia)<1 || Integer.parseInt(dia)>31) { return false; }else if(Integer.parseInt(mes)<1 || Integer.parseInt(mes)>12) { return false; } if(d.before(min)) { return false; }else if(d.after(hoje)) { return false; }else if(d.equals(hoje)) { return true; }else if(d.after(min)) { return true; } return true; } public static String organizarData(String dia, String mes, String ano) { String data = ""; data += ano + "-" + mes + "-" + dia; return data; } public static String dataPadraoBr(String data) { String dia = data.substring(8, 10); String mes = data.substring(5, 7); String ano = data.substring(0, 4); String hora = data.substring(11, 18); switch(mes) { case "01": mes = "Jan"; break; case "02": mes = "Fev"; break; case "03": mes = "Mar"; break; case "04": mes = "Abr"; break; case "05": mes = "Mai"; break; case "06": mes = "Jun"; break; case "07": mes = "Jul"; break; case "08": mes = "Ago"; break; case "09": mes = "Set"; break; case "10": mes = "Out"; break; case "11": mes = "Nov"; break; case "12": mes = "Dec"; break; } return dia + " " + mes + " " + ano + " - " + hora; } public static boolean isInteger(String str) { return str != null && str.matches("[0-9]*"); } public static void botaoVoltar(JButton b) { ImageIcon voltarImageIcon = new ImageIcon(Utils.class.getResource("/09_botao_voltar.png")); b.setIcon(voltarImageIcon); Utils.ajustesBotao(b, 0, 10, "/10_botao_voltar_rolover.png", null); } }
29.754098
93
0.67135
ff17f45a7563dc932df41e438adfaf56683467a1
697
package com.cognizant.cognizantits.qcconnection.qcupdation; import com4j.Com4jObject; import com4j.DISPID; import com4j.IID; import com4j.NativeType; import com4j.ReturnValue; import com4j.VTID; @IID("{49B715FA-458E-46EA-A171-0E0BFB38B3AF}") public abstract interface ILinkFactory extends IBaseFactory { @DISPID(8) @VTID(16) @ReturnValue(type=NativeType.Dispatch) public abstract Com4jObject owner(); @DISPID(9) @VTID(17) public abstract boolean fullLinkage(); @DISPID(9) @VTID(18) public abstract void fullLinkage(boolean paramBoolean); } /* Location: D:\Prabu\jars\QC.jar * Qualified Name: qcupdation.ILinkFactory * JD-Core Version: 0.7.0.1 */
21.78125
59
0.731707
4845b597c3c2ee55b0bee96ccd625f65c3cff595
6,258
package com.jbirdvegas.mgerrit.database; /* * Copyright (C) 2014 Android Open Kang Project (AOKP) * Author: Evan Conway (P4R4N01D), 2014 * * 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. */ import android.content.Context; import android.content.UriMatcher; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Handler; import android.support.v4.content.CursorLoader; public class FileChanges extends DatabaseTable { // Table name public static final String TABLE = "FileChanges"; // --- Columns (FileInfo table)--- // The Change-Id of the change. public static final String C_CHANGE_ID = FileInfoTable.C_CHANGE_ID; // The patch set number. public static final String C_PATCH_SET_NUMBER = FileInfoTable.C_PATCH_SET_NUMBER; public static final String C_FILE_NAME = FileInfoTable.C_FILE_NAME; /* The status of the file ("A"=Added, "D"=Deleted, "R"=Renamed, "C"=Copied, "W"=Rewritten). * Not set if the file was Modified ("M"). optional. */ public static final String C_STATUS = FileInfoTable.C_STATUS; // Whether the file is binary. public static final String C_ISBINARY = FileInfoTable.C_ISBINARY; // The old file path. Only set if the file was renamed or copied. public static final String C_OLDPATH = FileInfoTable.C_OLDPATH; // Number of inserted lines. Not set for binary files or if no lines were inserted. public static final String C_LINES_INSERTED = FileInfoTable.C_LINES_INSERTED; // Number of deleted lines. Not set for binary files or if no lines were deleted. public static final String C_LINES_DELETED = FileInfoTable.C_LINES_DELETED; // Whether the file is an image. public static final String C_ISIMAGE = FileInfoTable.C_ISIMAGE; // --- Columns (Changes table) --- // The legacy numeric ID of the change (used in the web address) public static final String C_COMMIT_NUMBER = Changes.C_COMMIT_NUMBER; public static final int ITEM_LIST = UriType.FileChangesList.ordinal(); public static final int ITEM_ID = UriType.FileChangesID.ordinal(); public static final Uri CONTENT_URI = Uri.parse(DatabaseFactory.BASE_URI + TABLE); public static final String CONTENT_TYPE = DatabaseFactory.BASE_MIME_LIST + TABLE; public static final String CONTENT_ITEM_TYPE = DatabaseFactory.BASE_MIME_ITEM + TABLE; // Sort by condition for querying results. public static final String SORT_BY = FileInfoTable.SORT_BY; public static final String[] PROJECTION = new String[] { FileInfoTable.TABLE + ".rowid AS _id", Changes.TABLE + "." + Changes.C_CHANGE_ID, Changes.TABLE + "." + Changes.C_COMMIT_NUMBER, C_PATCH_SET_NUMBER, C_FILE_NAME, FileInfoTable.TABLE + "." + FileInfoTable.C_STATUS, C_ISBINARY, C_OLDPATH, C_ISIMAGE, C_LINES_INSERTED, C_LINES_DELETED }; private static FileChanges mInstance = null; private MyObserver mObserver; public static FileChanges getInstance() { if (mInstance == null) mInstance = new FileChanges(); return mInstance; } @Override public void create(String TAG, SQLiteDatabase db) { // This is not a real table (do nothing) } public static void addURIMatches(UriMatcher _urim) { _urim.addURI(DatabaseFactory.AUTHORITY, TABLE, ITEM_LIST); _urim.addURI(DatabaseFactory.AUTHORITY, TABLE + "/#", ITEM_ID); } /** * Get details on what files changed in a change * @param context Context for database access * @param changeid The Change-Id of the change to get the file changes for * @return A CursorLoader */ public static CursorLoader getFileChanges(Context context, String changeid) { return new CursorLoader(context, CONTENT_URI, PROJECTION, FileInfoTable.TABLE + "." + C_CHANGE_ID + " = ? AND " + FileInfoTable.TABLE + "." + C_CHANGE_ID + " = " + Changes.TABLE + "." + Changes.C_CHANGE_ID, new String[] { changeid }, SORT_BY); } /** * Get details for the files which we can show diff details for in the DiffViewer * @param context Context for database access * @param changeNumber The number of the change to get the file changes for * @return A CursorLoader */ public static CursorLoader getDiffableFiles(Context context, Integer changeNumber) { String[] PROJECTION = new String[] { FileInfoTable.TABLE + ".rowid AS _id", C_FILE_NAME, C_ISBINARY, C_COMMIT_NUMBER, C_PATCH_SET_NUMBER, FileInfoTable.TABLE + "." + C_STATUS, C_LINES_INSERTED, C_LINES_DELETED}; return new CursorLoader(context, CONTENT_URI, PROJECTION, Changes.TABLE + "." + C_COMMIT_NUMBER + " = ? AND " + FileInfoTable.TABLE + "." + C_CHANGE_ID + " = " + Changes.TABLE + "." + Changes.C_CHANGE_ID + " AND (" + C_ISBINARY + " = 0 OR " + C_ISIMAGE + " = 1)", new String[] { String.valueOf(changeNumber) }, SORT_BY); } @Override protected void registerContentObserver(Context context) { mObserver = new MyObserver(new Handler(), context, CONTENT_URI); context.getContentResolver().registerContentObserver(FileInfoTable.CONTENT_URI, true, mObserver); context.getContentResolver().registerContentObserver(Changes.CONTENT_URI, true, mObserver); } @Override protected void unRegisterContentObserver(Context context) { context.getContentResolver().unregisterContentObserver(mObserver); } }
41.443709
96
0.678651
e3227a612cee38263e578c6355435502a6e2360b
2,255
package file; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.nio.file.NoSuchFileException; import java.util.HashMap; import java.util.Map; import path.MaldoPath; import path.PathRegistry; /** * Registry of all directories in the FS. This class also serves as the Factory for creating * {@link Directory}. */ public class DirectoryRegistry { private static final Map<MaldoPath,Directory> registry = new HashMap<>(); private DirectoryRegistry(){} public static Directory getDirectoryCreateIfNew(MaldoPath path){ checkNotNull(path); if(registry.containsKey(path)){ return registry.get(path); } createParentDirectoriesIfNotExist(path); createDirectoryIfNotExist(path); return registry.get(path); } public static boolean directoryExists(MaldoPath path){ return registry.containsKey(path); } public static Directory getDirectory(MaldoPath path) throws IOException { checkContains(path); return registry.get(path); } public static Directory getFileDirectory(MaldoPath path) throws IOException { checkArgument(!path.isDirectory(), "Path must be a File"); MaldoPath dirPath = PathRegistry.convert(path.getParent()); return getDirectory(dirPath); } public static void remove(MaldoPath path) throws IOException { checkContains(path); registry.remove(path); } private static void checkContains(MaldoPath path) throws NoSuchFileException { if(!registry.containsKey(path)){ throw new NoSuchFileException(path.getCanonical()); } } private static void createParentDirectoriesIfNotExist(MaldoPath maldoPath) { for(MaldoPath childPath: maldoPath.getPathChain()){ if(!registry.containsKey(childPath)){ createDirectoryIfNotExist(maldoPath); } } } private static void createDirectoryIfNotExist(MaldoPath path) { if(path.isRoot()){ registry.put(path, new Directory(path)); }else{ Directory newDir = new Directory(path); Directory parentDir = getDirectoryCreateIfNew(path.getParent()); parentDir.addFileIfNotExist(newDir); registry.put(path, newDir); } } }
29.285714
92
0.736142
cbfe4e4625ae0304cbd4fa14c9965831cc4ab281
3,413
/* * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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.tencent.cloud.polaris.ratelimit.filter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.tencent.cloud.metadata.constant.MetadataConstant.SystemMetadataKey; import com.tencent.cloud.metadata.context.MetadataContextHolder; import com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant; import com.tencent.cloud.polaris.ratelimit.utils.QuotaCheckUtils; import com.tencent.polaris.ratelimit.api.core.LimitAPI; import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse; import com.tencent.polaris.ratelimit.api.rpc.QuotaResultCode; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.web.filter.OncePerRequestFilter; import static org.springframework.http.HttpStatus.TOO_MANY_REQUESTS; /** * Servlet filter to check quota. * * @author Haotian Zhang */ @Order(RateLimitConstant.FILTER_ORDER) public class QuotaCheckServletFilter extends OncePerRequestFilter { private static final Logger LOG = LoggerFactory .getLogger(QuotaCheckServletFilter.class); private final LimitAPI limitAPI; public QuotaCheckServletFilter(LimitAPI limitAPI) { this.limitAPI = limitAPI; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String localNamespace = MetadataContextHolder.get() .getSystemMetadata(SystemMetadataKey.LOCAL_NAMESPACE); String localService = MetadataContextHolder.get() .getSystemMetadata(SystemMetadataKey.LOCAL_SERVICE); String method = MetadataContextHolder.get() .getSystemMetadata(SystemMetadataKey.LOCAL_PATH); Map<String, String> labels = null; if (StringUtils.isNotBlank(method)) { labels = new HashMap<>(); labels.put("method", method); } try { QuotaResponse quotaResponse = QuotaCheckUtils.getQuota(limitAPI, localNamespace, localService, 1, labels, null); if (quotaResponse.getCode() == QuotaResultCode.QuotaResultLimited) { response.setStatus(TOO_MANY_REQUESTS.value()); response.getWriter().write( RateLimitConstant.QUOTA_LIMITED_INFO + quotaResponse.getInfo()); } else { filterChain.doFilter(request, response); } } catch (Throwable t) { // 限流API调用出现异常,不应该影响业务流程的调用 LOG.error("fail to invoke getQuota, service is " + localService, t); filterChain.doFilter(request, response); } } }
34.826531
100
0.783768
f1ecb2407d802503c21dd97624a95cc4c2de55ce
1,112
package ata.util; import com.alibaba.fastjson.JSONObject; public class JSONResult { public static String success() { JSONObject json = new JSONObject(); json.put("result", true); return json.toJSONString(); } public static String success(Object data) { JSONObject json = new JSONObject(); json.put("result", true); json.put("data", data); return json.toJSONString(); } public static String success(String name, Object value) { JSONObject json = new JSONObject(); json.put("result", true); json.put(name, value); return json.toJSONString(); } public static String error(String error) { JSONObject json = new JSONObject(); json.put("result", false); json.put("error", error); return json.toJSONString(); } public static String error(String code, String error) { JSONObject json = new JSONObject(); json.put("result", false); json.put("code", code); json.put("error", error); return json.toJSONString(); } }
26.47619
61
0.598022
d02ac4e69fd6de002c81a9bbefb893a43c746eac
9,365
package io.github.bigbio.pgatk.io.mzxml.mzxml.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="msManufacturer"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;extension base="{http://sashimi.sourceforge.net/schema_revision/mzXML_3.2}ontologyEntryType"&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;element name="msModel" type="{http://sashimi.sourceforge.net/schema_revision/mzXML_3.2}ontologyEntryType"/&gt; * &lt;element name="msIonisation" type="{http://sashimi.sourceforge.net/schema_revision/mzXML_3.2}ontologyEntryType"/&gt; * &lt;element name="msMassAnalyzer"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;extension base="{http://sashimi.sourceforge.net/schema_revision/mzXML_3.2}ontologyEntryType"&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;element name="msDetector" type="{http://sashimi.sourceforge.net/schema_revision/mzXML_3.2}ontologyEntryType"/&gt; * &lt;element ref="{http://sashimi.sourceforge.net/schema_revision/mzXML_3.2}software"/&gt; * &lt;element name="msResolution" type="{http://sashimi.sourceforge.net/schema_revision/mzXML_3.2}ontologyEntryType" minOccurs="0"/&gt; * &lt;element ref="{http://sashimi.sourceforge.net/schema_revision/mzXML_3.2}operator" minOccurs="0"/&gt; * &lt;sequence maxOccurs="unbounded" minOccurs="0"&gt; * &lt;element name="nameValue" type="{http://sashimi.sourceforge.net/schema_revision/mzXML_3.2}namevalueType"/&gt; * &lt;element name="comment" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/sequence&gt; * &lt;attribute name="msInstrumentID" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "msManufacturer", "msModel", "msIonisation", "msMassAnalyzer", "msDetector", "software", "msResolution", "operator", "nameValueAndComment" }) public class MsInstrument implements Serializable, MzXMLObject { private final static long serialVersionUID = 320L; @XmlElement(required = true) protected MsManufacturer msManufacturer; @XmlElement(required = true) protected OntologyEntry msModel; @XmlElement(required = true) protected OntologyEntry msIonisation; @XmlElement(required = true) protected MsMassAnalyzer msMassAnalyzer; @XmlElement(required = true) protected OntologyEntry msDetector; @XmlElement(required = true) protected Software software; protected OntologyEntry msResolution; protected Operator operator; @XmlElements({ @XmlElement(name = "nameValue", type = NameValue.class), @XmlElement(name = "comment", type = String.class) }) protected List<Serializable> nameValueAndComment; @XmlAttribute protected Integer msInstrumentID; /** * Gets the value of the msManufacturer property. * * @return * possible object is * {@link MsManufacturer } * */ public MsManufacturer getMsManufacturer() { return msManufacturer; } /** * Sets the value of the msManufacturer property. * * @param value * allowed object is * {@link MsManufacturer } * */ public void setMsManufacturer(MsManufacturer value) { this.msManufacturer = value; } /** * Gets the value of the msModel property. * * @return * possible object is * {@link OntologyEntry } * */ public OntologyEntry getMsModel() { return msModel; } /** * Sets the value of the msModel property. * * @param value * allowed object is * {@link OntologyEntry } * */ public void setMsModel(OntologyEntry value) { this.msModel = value; } /** * Gets the value of the msIonisation property. * * @return * possible object is * {@link OntologyEntry } * */ public OntologyEntry getMsIonisation() { return msIonisation; } /** * Sets the value of the msIonisation property. * * @param value * allowed object is * {@link OntologyEntry } * */ public void setMsIonisation(OntologyEntry value) { this.msIonisation = value; } /** * Gets the value of the msMassAnalyzer property. * * @return * possible object is * {@link MsMassAnalyzer } * */ public MsMassAnalyzer getMsMassAnalyzer() { return msMassAnalyzer; } /** * Sets the value of the msMassAnalyzer property. * * @param value * allowed object is * {@link MsMassAnalyzer } * */ public void setMsMassAnalyzer(MsMassAnalyzer value) { this.msMassAnalyzer = value; } /** * Gets the value of the msDetector property. * * @return * possible object is * {@link OntologyEntry } * */ public OntologyEntry getMsDetector() { return msDetector; } /** * Sets the value of the msDetector property. * * @param value * allowed object is * {@link OntologyEntry } * */ public void setMsDetector(OntologyEntry value) { this.msDetector = value; } /** * Gets the value of the software property. * * @return * possible object is * {@link Software } * */ public Software getSoftware() { return software; } /** * Sets the value of the software property. * * @param value * allowed object is * {@link Software } * */ public void setSoftware(Software value) { this.software = value; } /** * Gets the value of the msResolution property. * * @return * possible object is * {@link OntologyEntry } * */ public OntologyEntry getMsResolution() { return msResolution; } /** * Sets the value of the msResolution property. * * @param value * allowed object is * {@link OntologyEntry } * */ public void setMsResolution(OntologyEntry value) { this.msResolution = value; } /** * Gets the value of the operator property. * * @return * possible object is * {@link Operator } * */ public Operator getOperator() { return operator; } /** * Sets the value of the operator property. * * @param value * allowed object is * {@link Operator } * */ public void setOperator(Operator value) { this.operator = value; } /** * Gets the value of the nameValueAndComment property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nameValueAndComment property. * * <p> * For example, to put a new item, do as follows: * <pre> * getNameValueAndComment().put(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link NameValue } * {@link String } * * */ public List<Serializable> getNameValueAndComment() { if (nameValueAndComment == null) { nameValueAndComment = new ArrayList<>(); } return this.nameValueAndComment; } /** * Gets the value of the msInstrumentID property. * * @return * possible object is * {@link Integer } * */ public Integer getMsInstrumentID() { return msInstrumentID; } /** * Sets the value of the msInstrumentID property. * * @param value * allowed object is * {@link Integer } * */ public void setMsInstrumentID(Integer value) { this.msInstrumentID = value; } }
27.066474
144
0.586866
eae2809e6de82335771bdcb38353346ba08f0a76
167
package com.vanessagl2.dojo; public class Main { public static void main(String[] args) { System.out.println("Welcome to the Vending Machine!"); } }
18.555556
62
0.664671
1e0c0dd3855a28810b75fd100fb4556ea55722db
1,537
/** * */ package at.free23.shop.model; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; /** * @author michael.vlasaty * */ @Entity public class Vendor { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idgen") @SequenceGenerator(name = "idgen", sequenceName = "vendor_id_sequence", allocationSize = 1, initialValue = 1) private Long id; private String name; private String country; @OneToMany(mappedBy = "vendor") private List<Product> products; /** * @return the name */ public String getName() { return this.name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the country */ public String getCountry() { return this.country; } /** * @param country * the country to set */ public void setCountry(String country) { this.country = country; } /** * @return the id */ public Long getId() { return this.id; } /** * @param id * the id to set */ public void setId(Long id) { this.id = id; } /** * @return the products */ public List<Product> getProducts() { return this.products; } /** * @param products * the products to set */ public void setProducts(List<Product> products) { this.products = products; } }
16.351064
110
0.648666
42f5b3cd7bab5e7fc79f16b2708b6a6235965fc8
1,198
package com.djs.learn.spring_sample.jpa; import java.util.List; import org.apache.log4j.Logger; import org.springframework.orm.jpa.JpaTemplate; import com.djs.learn.spring_sample.db.Item; import com.djs.learn.spring_sample.db.ItemDao; public class ItemDaoJpaImplA implements ItemDao { private final Logger log = Logger.getLogger( ItemDaoJpaImplA.class ); private JpaTemplate jpaTemplate; public void setJpaTemplate( JpaTemplate jpaTemplate ) { if (log.isTraceEnabled()) { log.trace( "Set " + jpaTemplate.getClass().getName() ); } this.jpaTemplate = jpaTemplate; } @Override public void save( Item item ) { if (log.isInfoEnabled()) { log.info( "Save/Update: " + item ); } jpaTemplate.persist( item ); } @Override public List<Item> query( String itemName ) { // Here must include Item's full package name. final String sql = "SELECT a FROM " + Item.class.getName() + " a WHERE a.ITEM_NAME = ?1"; if (log.isInfoEnabled()) { log.info( "Query: " + itemName ); } List items = jpaTemplate.find( sql, itemName ); if (log.isInfoEnabled()) { log.info( "Result: " + items ); } return items.size() > 0 ? (List<Item>)items : null; } }
19.966667
91
0.68197
de917a80917f48627f52b92715004b86296d717a
2,872
package com.ba.captwo.eda.demo.routes; import com.ba.captwo.eda.demo.model.Booking; import com.ba.captwo.eda.demo.model.Person; import com.ba.captwo.eda.demo.model.Reservation; import org.apache.cxf.helpers.IOUtils; import org.apache.cxf.jaxrs.client.WebClient; import org.codehaus.jackson.map.ObjectMapper; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.ws.rs.core.Response; import java.io.InputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Created by u760245 on 06/07/2014. */ public class ReservationRouteIT { private static String endpointUrl; private final static Logger log = LoggerFactory.getLogger(ReservationRouteIT.class); @BeforeClass public static void beforeClass() { log.info("***** System.getProperty : " + System.getProperty("service.url")); endpointUrl = System.getProperty("service.url"); if(endpointUrl == null) { endpointUrl = "http://localhost:8080/routes"; } log.info("***** endpointUrl : " + endpointUrl); } @Test public void testCreateReservation() throws Exception { log.info("***** Test CreateReservation"); Booking b = new Booking(); b.setPersonID(1); b.setFlightNum("BA009"); b.setTickets(2); b.setCabin("J"); Person p = new Person(); p.setLastName("Windsor"); p.setFirstName("William"); p.setAddress("Kensington Palace"); p.setCity("London"); String uri = "/reservation/create;fname=" + p.getFirstName() + ";lname=" + p.getLastName() + ";address=" + p.getAddress() + ";city=" + p.getCity() + ";fnum=" + b.getFlightNum() + ";ticks=" + b.getTickets() + ";cab=" + b.getCabin(); log.info("***** Calling : "+uri); WebClient client = WebClient.create(endpointUrl + uri); Response r = client.accept("application/json").get(); assertEquals(Response.Status.OK.getStatusCode(), r.getStatus()); String value = IOUtils.toString((InputStream) r.getEntity()); log.info("***** Test CreateReservation : " + value); ObjectMapper mapper = new ObjectMapper(); Reservation res = mapper.readValue(value, Reservation.class); log.info("Reservation : "+p.getPersonID()); assertNotNull(res.getPerson()); assertNotNull(res.getBooking()); } }
35.02439
88
0.610724
5c59e264d20155ff28664830e7574e5e47315981
1,400
package org.minimallycorrect.tickthreading.mixin.extended.forge; import java.util.List; import lombok.val; import org.minimallycorrect.mixin.Mixin; import org.minimallycorrect.mixin.Overwrite; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.oredict.OreDictionary; @Mixin public abstract class MixinOreDictionary extends OreDictionary { @Overwrite public static int[] getOreIDs(ItemStack stack) { if (stack == null) throw new IllegalArgumentException(); val item = stack.getItem(); if (item == null) throw new IllegalArgumentException(); val delegate = item.delegate; val registryName = delegate.name(); if (registryName == null) { FMLLog.log.debug("Attempted to find the oreIDs for an unregistered object (%s). This won't work very well.", stack); return new int[0]; } // TODO: cache this? val set = new IntOpenHashSet(); int id = Item.REGISTRY.getIDForObject(delegate.get()); List<Integer> ids = stackToId.get(id); if (ids != null) { set.addAll(ids); } ids = stackToId.get(id | stack.getItemDamage() + 1 << 16); if (ids != null) { set.addAll(ids); } val ret = new int[set.size()]; val ie = set.iterator(); int i = 0; while (ie.hasNext()) ret[i++] = ie.nextInt(); return ret; } }
24.561404
119
0.705
5f8f0c2b20e85e433c73d2517c81c4d146282df9
5,067
package at.ac.tuwien.oz.datatypes.postconditions.combinable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import at.ac.tuwien.oz.datatypes.postconditions.ChangeOperationCall; import at.ac.tuwien.oz.datatypes.postconditions.ComplexChangePostconditionMapping; import at.ac.tuwien.oz.datatypes.postconditions.ComplexOutputPromotionMapping; import at.ac.tuwien.oz.datatypes.postconditions.interfaces.ICombinablePostconditions; public class CompositePostconditionFactory { private CompositePostconditionDataCollector collector; private Map<String, List<ChangeOperationCall>> postconditionPerCallerMap; public CompositePostconditionFactory(CompositePostconditionDataCollector collector){ this.collector = collector; } public ICombinablePostconditions createPostcondition(){ if (hasCommonCallers()){ return createThenPostcondition(); } else if (hasCalls() && (hasCommunicationVars() || hasSharedVars() || hasPromotions())){ return createCommunicationChangePostcondition(); } else if (hasCalls()){ return createChangeOperationCalls(); } else if (hasPromotions() && hasPromotionsWithCommunication()){ return createOutputPromotionsWithCommunication(); } else if (hasPromotions()){ return createOutputPromotions(); } else { return EmptyPostconditions.empty(); } } private boolean hasCommonCallers() { createPostconditionsPerCallerMap(); for (List<ChangeOperationCall> postcondition : postconditionPerCallerMap.values()) { if (postcondition.size() > 1) { return true; } } return false; } private void createPostconditionsPerCallerMap() { Map<String, List<ChangeOperationCall>> postconditionPerCallerMap = new HashMap<String, List<ChangeOperationCall>>(); for (ChangeOperationCall postcondition : collector.getAllCalls().asList()) { String caller = "self"; if (postcondition.getCaller() != null){ caller = postcondition.getCaller().render(); } List<ChangeOperationCall> postconditionsOfCaller = postconditionPerCallerMap.get(caller); if (postconditionsOfCaller != null) { postconditionsOfCaller.add(postcondition); } else { postconditionsOfCaller = new ArrayList<ChangeOperationCall>(); postconditionsOfCaller.add(postcondition); postconditionPerCallerMap.put(caller, postconditionsOfCaller); } } this.postconditionPerCallerMap = postconditionPerCallerMap; } private ICombinablePostconditions createOutputPromotions() { return new OutputPromotions(collector.getSimplePromotions()); } private ICombinablePostconditions createOutputPromotionsWithCommunication() { ComplexOutputPromotionMapping mapping = new ComplexOutputPromotionMapping(collector.getCommunicatingPromotions(), collector.getCommunicationVariables(), collector.getVisibleCommunicationVariables()); return new ComplexOutputPromotions(collector.getSimplePromotions(), mapping); } private ICombinablePostconditions createChangeOperationCalls(){ return new ChangeOperationCalls(collector.getSimpleCalls()); } private ICombinablePostconditions createCommunicationChangePostcondition() { ComplexChangePostconditionMapping mapping = new ComplexChangePostconditionMapping(collector.getCommunicatingPromotions(), collector.getCommunicatingCalls(), collector.getCommunicationVariables(), collector.getVisibleCommunicationVariables(), collector.getSharedOutputVariables()); return new ComplexChangePostcondition(collector.getSimplePromotions(), collector.getSimpleCalls(), mapping); } private ICombinablePostconditions createThenPostcondition() { ThenPostcondition result = new ThenPostcondition.Builder(this.postconditionPerCallerMap) .withSimpleOutputPromotions(collector.getSimplePromotions()) .withCommunicatingOutputPromotions(collector.getCommunicatingPromotions()) .withCommunicatingVariables(collector.getCommunicationVariables()) .withVisibleCommunicatingVariables(collector.getVisibleCommunicationVariables()) .withSharedOutputVariables(collector.getSharedOutputVariables()) .build(); result.checkCommunicationOrder(); return result; } private boolean hasPromotionsWithCommunication() { if (hasVisibleCommunicationVars()){ return true; } else if (!collector.getCommunicatingPromotions().getWithInputParameters(collector.getCommunicationVariables().getInputCopies()).isEmpty()) { return true; } return false; } private boolean hasCalls() { return !this.collector.getAllCalls().isEmpty(); } private boolean hasPromotions() { if (this.collector.getSimplePromotions().isEmpty() && this.collector.getCommunicatingPromotions().isEmpty()){ return false; } return true; } private boolean hasSharedVars() { return !this.collector.getSharedOutputVariables().isEmpty(); } private boolean hasCommunicationVars() { return !this.collector.getCommunicationVariables().isEmpty(); } private boolean hasVisibleCommunicationVars() { return !this.collector.getVisibleCommunicationVariables().isEmpty(); } }
35.683099
144
0.790606
95b04306edb91314e4f224fec405945e60667b1d
534
public class Alumno{ String nombre; char sexo; int edad; double calif[]; public Alumno(String n, char s, int e double c){ nombre = n; sexo = s; edad = e; c=calif; } public String getNombre(){ return nombre; } public char getSexo(){ return sexo; } public int getedad(){ return edad; } public double getcalif(){ return calif; } public String toString(){ return nombre+" "+sexo+" "+edad+" "+calif; } }
14.833333
56
0.514981
3e1dd97a99d4bbcfc66408f2bd6a05490fab007a
23,740
package com.prtech.svarog; import java.lang.management.ManagementFactory; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import org.apache.logging.log4j.Logger; import org.joda.time.DateTime; import com.google.common.cache.LoadingCache; import com.google.gson.JsonObject; import com.prtech.svarog_common.DbDataArray; import com.prtech.svarog_common.DbDataObject; /** * Class for managing the svarog cluster infrastructure. Provides basic * synchronization methods between multiple svarog nodes. * * @author ristepejov * */ public class SvCluster extends SvCore { static final byte MSG_UNKNOWN = -2; static final byte MSG_FAIL = -1; static final byte MSG_SUCCESS = 0; static final byte MSG_HEARTBEAT = 1; static final byte MSG_AUTH_TOKEN_PUT = 3; static final byte MSG_AUTH_TOKEN_GET = 4; static final byte MSG_AUTH_TOKEN_SET = 6; static final byte MSG_JOIN = 10; static final byte MSG_PART = 11; static final byte MSG_LOCK = 20; static final byte MSG_LOCK_RELEASE = 21; static final byte NOTE_LOCK_ACQUIRED = 22; static final byte NOTE_LOCK_RELEASED = 23; static final byte NOTE_DIRTY_OBJECT = 30; static final byte NOTE_LOGOFF = 31; static final byte NOTE_DIRTY_TILE = 32; static final byte NOTE_ACK = 33; static final String JOIN_TIME = "join_time"; static final String PART_TIME = "part_time"; static final String LAST_MAINTENANCE = "last_maintenance"; static final String NEXT_MAINTENANCE = "next_maintenance"; static final String NODE_INFO = "node_info"; /** * Class to wrap the standard locks in order to support the distributed * locking of the svarog cluster. The key of the lock as well as the node * which holds the lock are the needed information * * @author ristepejov * */ static class DistributedLock { public String key; public Long nodeId; public ReentrantLock lock; public int lockHash; DistributedLock(String key, Long nodeId, ReentrantLock lock, int lockHash) { this.nodeId = nodeId; this.lock = lock; this.key = key; this.lockHash = lockHash; } } /** * Timeout interval on the socket receive */ static final int SOCKET_RECV_TIMEOUT = SvConf.getHeartBeatInterval() / 2; /** * Flag to know if the current node is coordinator or worker. */ private static boolean isCoordinator = false; /** * Flag if the cluster is running */ private static final AtomicBoolean isRunning = new AtomicBoolean(false); /** * Flag if the client is running */ private static AtomicBoolean isActive = new AtomicBoolean(false); /** * Log4j instance used for logging */ static final Logger log4j = SvConf.getLogger(SvCluster.class); /** * Reference to the coordinator node */ private static DbDataObject coordinatorNode = null; /** * Reference to the current node descriptor. If the current node is * coordinator, the references should be equal. */ // static DbDataObject currentNode = null; static final String IP_ADDR_DELIMITER = ";"; /** * Member fields holding reference to the heart beat thread */ static private Thread heartBeatThread = null; static private Thread notifierThread = null; /** * Reference to the coordinator node */ static boolean autoStartClient = true; /** * Default Constructor. This constructor can be used only within the svarog * package since it will run with system privileges. * * @throws SvException */ SvCluster() throws SvException { super(svCONST.systemUser, null); } /** * Method to generate a DBO describing the current node * * @return A DbDataObject descriptor of the current node */ static DbDataObject getCurrentNodeInfo() { DbDataObject cNode = new DbDataObject(svCONST.OBJECT_TYPE_CLUSTER); cNode.setVal(JOIN_TIME, new DateTime()); cNode.setVal(PART_TIME, SvConf.MAX_DATE); cNode.setVal(LAST_MAINTENANCE, new DateTime()); cNode.setVal(NEXT_MAINTENANCE, new DateTime().plusSeconds(SvConf.getClusterMaintenanceInterval())); String localIp = "0.0.0.0:" + SvConf.getHeartBeatPort(); try { localIp = SvUtil.getIpAdresses(true, IP_ADDR_DELIMITER); } catch (UnknownHostException e) { log4j.error("Can't get node IP Address!", e); } cNode.setVal("local_ip", localIp); JsonObject json = new JsonObject(); json.addProperty("pid", ManagementFactory.getRuntimeMXBean().getName()); json.addProperty("version", SvConf.appVersion); json.addProperty("build", SvConf.appBuild); json.addProperty("ip", localIp); cNode.setVal(NODE_INFO, json.toString()); return cNode; } /** * Method to perform coordinator promotion of the current node * * @param svc * A reference to an SvCore (the read/write of the nodes has to * be in the same transaction) * @return True if the current node was promoted to coordinator * @throws SvException * any underlying exception (except object not updateable, which * would mean someone else got promoted in meantime) */ static boolean becomeCoordinator(SvCore svc) throws SvException { SvWriter svw = null; boolean success = true; try { svw = new SvWriter(svc); if (coordinatorNode == null) { coordinatorNode = new DbDataObject(svCONST.OBJECT_TYPE_CLUSTER); coordinatorNode.setObjectId(svCONST.CLUSTER_COORDINATOR_ID); } coordinatorNode.setValuesMap(getCurrentNodeInfo().getValuesMap()); svw.isInternal = true; svw.saveObject(coordinatorNode, true); } catch (SvException e) { // if the object is not update-able, another node became // coordinator and we should register a worker node if (!e.getLabelCode().equals("system.error.obj_not_updateable")) throw (e); else success = false; } finally { if (svw != null) svw.release(); } // If we failed to promote lets try to refresh the coordinator node info if (!success) { DbCache.removeObject(coordinatorNode.getObjectId(), coordinatorNode.getObjectType()); coordinatorNode = null; log4j.warn("Coordinator record is invalid. Next maintenance in the past: " + coordinatorNode.getVal(NEXT_MAINTENANCE)); } else log4j.info("The node promoted to coordinator: " + coordinatorNode.getVal(NODE_INFO)); return success; } /** * Method to perform resigning of coordinator * * @param svc * A reference to an SvCore (the read/write of the nodes has to * be in the same transaction) * @return True if the current has resigned from the coordinator role * @throws SvException * any underlying exception (except object not updateable, which * would mean someone else got promoted in meantime) */ static boolean resignCoordinator() throws SvException { SvWriter svw = null; SvReader svr = null; boolean success = false; try { if (isCoordinator) { svr = new SvReader(); svr.isInternal = true; svw = new SvWriter(svr); DbCache.removeObject(svCONST.CLUSTER_COORDINATOR_ID, svCONST.OBJECT_TYPE_CLUSTER); coordinatorNode = svr.getObjectById(svCONST.CLUSTER_COORDINATOR_ID, svCONST.OBJECT_TYPE_CLUSTER, null); coordinatorNode.setVal(LAST_MAINTENANCE, DateTime.now()); coordinatorNode.setVal(NEXT_MAINTENANCE, DateTime.now()); coordinatorNode.setVal(PART_TIME, DateTime.now()); svw.isInternal = true; svw.saveObject(coordinatorNode, true); success = true; } else success = false; } catch (SvException e) { // if the object is not update-able, another node became // coordinator and we should register a worker node if (!e.getLabelCode().equals("system.error.obj_not_updateable")) throw (e); else success = false; } finally { if (svw != null) svw.release(); if (svr != null) svr.release(); } return success; } /** * Method to ensure the cluster clients have started and connected to the * hear beat address/port of the coordinator * * @param hbAddress * String list of available heartbeat end points * @return True if the client threads have started and connected with * success */ private static boolean startClients(String hbAddress) { boolean initHb = false; boolean initNotif = false; boolean threadStarted = false; initHb = SvClusterClient.initClient(hbAddress); initNotif = initHb ? SvClusterNotifierClient.initClient(hbAddress) : false; if (initHb && initNotif) { heartBeatThread = new Thread(new SvClusterClient()); heartBeatThread.setName("SvClusterClientThread"); heartBeatThread.start(); notifierThread = new Thread(new SvClusterNotifierClient()); notifierThread.setName("SvClusterNotifierClientThread"); notifierThread.start(); threadStarted = true; } else { log4j.info("Svarog Cluster Clients initialisation failed. Initiating Cluster shutdown."); shutdown(); } return initHb && initNotif && threadStarted; } /** * Method to start the server threads of the cluster * * @return True if the server threads have been started successfully. * @throws SvException */ private static boolean startServers() throws SvException { boolean initHb = false; boolean initNotif = false; initHb = SvClusterServer.initServer(); initNotif = SvClusterNotifierProxy.initServer(); if (initHb && initNotif) { // promote the local locks from the old node id heartBeatThread = new Thread(new SvClusterServer()); heartBeatThread.setName("SvClusterServerThread"); heartBeatThread.start(); notifierThread = new Thread(new SvClusterNotifierProxy()); notifierThread.setName("SvClusterNotifierProxyThread"); notifierThread.start(); // finally we are the coordinator isCoordinator = true; } else { log4j.info("Svarog Cluster Servers initialisation failed. Initiating Cluster shutdown."); shutdown(); } return initHb && initNotif && isCoordinator; } /** * Method to initialise the Svarog Cluster. This method shall try to locate * a valid coordinator node, or become one if there isn't any. If it becomes * a coordinator then it will start the heart beat listener and the notifier * proxy servers. If the current node doesn't manage to become a coordinator * then it will start a Heart Beat client and notifier client and try to * connect to the coordinator * * @return True if the cluster was properly initialised. */ static boolean initCluster() { if (!isRunning.compareAndSet(false, true)) { log4j.error("Cluster is already initialised and active. Shutdown first"); return false; } else log4j.info("SvCluster is starting"); SvReader svr = null; isCoordinator = false; try { svr = new SvReader(); svr.isInternal = true; // do try to get a valid coordinator // force purge of the cache to get the coordinator DbCache.removeObject(svCONST.CLUSTER_COORDINATOR_ID, svCONST.OBJECT_TYPE_CLUSTER); coordinatorNode = svr.getObjectById(svCONST.CLUSTER_COORDINATOR_ID, svCONST.OBJECT_TYPE_CLUSTER, null); // currentNode = getCurrentNodeInfo(); DateTime nextMaintenance = coordinatorNode != null ? (DateTime) coordinatorNode.getVal(NEXT_MAINTENANCE) : null; // the next maintenance is in the past means there's no active // coordinator, we will try to become a coordinator if (nextMaintenance == null || nextMaintenance.isBeforeNow()) isCoordinator = becomeCoordinator(svr); else log4j.info("Valid coordinator record found: " + coordinatorNode.getVal(NODE_INFO)); // if the local IP including the hb port is the same ... means that // the coordinator record is related to this node, but maybe a core // dump caused the server to fail. So lets try to become coordinator String hbAddress = (String) coordinatorNode.getVal("local_ip"); if (isCoordinator || (!isCoordinator && SvUtil.getIpAdresses(true, IP_ADDR_DELIMITER).equals(hbAddress))) isActive.set(startServers()); // if the servers failed to start, then try to start as a client if (!isActive.get() && autoStartClient) isActive.set(startClients(hbAddress)); } catch (Exception e) { log4j.error("Svarog cluster could not be initialised. Cluster not running!", e); shutdown(); } finally { if (svr != null) svr.release(); } return isActive.get(); } /** * Method to check if the cluster services are running correctly */ public static void checkCluster() { // TODO add sanity check of the threads } /** * Method to update a distributed lock. This is invoked when the Notifier * client is processing lock acknowledgments and needs to update the list of * distributed locks by the SvLock on the coordinator node. * * @param lockHash * The hash of the lock * @param lockKey * The key of the lock * * @return True if the lock was updated */ static boolean updateDistributedLock(String lockKey, Integer lockHash, ConcurrentHashMap<String, SvCluster.DistributedLock> distLocks) { DistributedLock dlock = distLocks.get(lockKey); if (dlock != null) dlock.lockHash = lockHash; return dlock != null; } /** * Method to shutdown the Svarog cluster. The cluster shutdown will in turn: * 1. Check the current node is a cluster coordinator. 2. If we are a * cluster coordinator then we shall shutdown the SvClusterServer and * SvClusterNotifierProxy 3. If we are not a coordinator then we shall * shutdown the SvClusterClient and SvClusterNotifierClient */ static void shutdown() { shutdown(true); } /** * Method to shutdown the clients if running */ static void stopClients() { if (autoStartClient) { if (SvClusterClient.isRunning.get()) SvClusterClient.shutdown(); if (SvClusterNotifierClient.isRunning.get()) SvClusterNotifierClient.shutdown(); } } /** * Method to stop the servers if running */ static void stopServers() { if (SvClusterServer.isRunning.get()) SvClusterServer.shutdown(); if (SvClusterNotifierProxy.isRunning.get()) SvClusterNotifierProxy.shutdown(); } /** * Join the heart beat and notifier threads so we are sure that the clients * or servers have stopped */ static void joinDaemonThreads() { // just check if the join isn't invoked from the heartbeat or notifier. Thread joinHb = (!Thread.currentThread().equals(heartBeatThread) ? heartBeatThread : null); Thread joinNf = (!Thread.currentThread().equals(notifierThread) ? notifierThread : null); while ((joinHb != null && joinHb.isAlive()) || (joinNf != null && joinNf.isAlive())) { try { if (joinHb != null && joinHb.isAlive()) joinHb.join(1); if (joinNf != null && joinNf.isAlive()) joinNf.join(1); synchronized (SvMaintenance.maintenanceThread) { SvMaintenance.maintenanceThread.wait(100); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); log4j.info("Waiting on the maintenance thread got interrupted. Retry to join daemon threads", e); } } } /** * Method to shutdown the Svarog cluster. The cluster shutdown will in turn: * 1. Check the current node is a cluster coordinator. 2. If we are a * cluster coordinator then we shall shutdown the SvClusterServer and * SvClusterNotifierProxy 3. If we are not a coordinator then we shall * shutdown the SvClusterClient and SvClusterNotifierClient */ static void shutdown(boolean doMaintenance) { if (!isRunning.compareAndSet(true, false)) { log4j.debug("Svarog Cluster not running. Can't shutdown"); return; } else log4j.info("SvCluster is stopping"); if (doMaintenance) SvMaintenance.performMaintenance(); // shut down all daemon threads if (isCoordinator) stopServers(); else stopClients(); // join the threads joinDaemonThreads(); // reset the global variables heartBeatThread = null; notifierThread = null; coordinatorNode = null; isCoordinator = false; // notify interested parties that we shut down synchronized (SvCluster.isRunning) { isRunning.notifyAll(); } } /** * Method to release a distributed lock. This is invoked when the * clusterServer processes releaseLock message. This method is also invoked * by the SvLock on the coordinator node. * * @param lockHash * The hash of the lock * @param nodeId * The node id which acquires the lock * @param nodeLocks * The map of nodes which contains locks held by node * @param distributedLocks * The map of distributed nodes in the cluster to be used for * releasing the lock * @return Null if the lock was NOT released, otherwise the lock key. */ static String releaseDistributedLock(Integer lockHash, long nodeId, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> nodeLocks, ConcurrentHashMap<String, SvCluster.DistributedLock> distributedLocks, LoadingCache<String, ReentrantLock> sysLocks) { boolean lockReleased = false; CopyOnWriteArrayList<SvCluster.DistributedLock> nodeLock = nodeLocks.get(nodeId); SvCluster.DistributedLock currentLock = null; if (nodeLock != null) { for (SvCluster.DistributedLock dLock : nodeLock) if (lockHash.equals(dLock.lockHash)) { currentLock = dLock; break; } } if (currentLock != null) { lockReleased = SvLock.releaseLock(currentLock.key, currentLock.lock, false, sysLocks); if (currentLock.lock.getHoldCount() == 0) { synchronized (distributedLocks) { distributedLocks.remove(currentLock.key, currentLock); } nodeLock.remove(currentLock); } } else log4j.error("Lock with hash " + lockHash.toString() + ", does not exist in the list of distributed locks"); return lockReleased ? currentLock.key : null; } /** * Method to acquire a distributed lock from the svarog cluster (this is * server agnostic). It is called also by SvLock in order to synchronize * properly the distributed locks * * @param lockKey * The lock key which should be locked. * @param nodeId * The id of the node which shall acquire the lock * @param extendedInfo * The id of the node which already holds the lock (available * only if the lock fails) * @param nodeLocks * The map of nodes which contains locks held by node * @param distributedLocks * The map of distributed nodes in the cluster to be used for * releasing the lock * @return Instance of re-entrant lock if the lock was acquired. Otherwise * null. If null the extendedInfo is populated with the node holding * the lock */ static ReentrantLock acquireDistributedLock(String lockKey, Long nodeId, Long[] extendedInfo, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> nodeLocks, ConcurrentHashMap<String, SvCluster.DistributedLock> distributedLocks, LoadingCache<String, ReentrantLock> sysLocks) { ReentrantLock lock = null; SvCluster.DistributedLock dlock = null; synchronized (distributedLocks) { dlock = distributedLocks.get(lockKey); if (dlock != null && dlock.nodeId.equals(nodeId)) { // same node is locking the re-entrant lock again lock = SvLock.getLock(lockKey, false, 0L, sysLocks); } else { if (dlock == null) // brand new lock { lock = SvLock.getLock(lockKey, false, 0L, sysLocks); if (lock != null) { dlock = new SvCluster.DistributedLock(lockKey, nodeId, lock, lock.hashCode()); distributedLocks.put(lockKey, dlock); } } else extendedInfo[0] = dlock.nodeId; } } updateNodeLocks(lock, dlock, nodeLocks, nodeId); return lock; } /** * Update the map with locks per node if the lock was acquired * * @param lock * @param dlock * @param nodeLocks * @param nodeId */ static void updateNodeLocks(ReentrantLock lock, SvCluster.DistributedLock dlock, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> nodeLocks, long nodeId) { if (lock != null) { CopyOnWriteArrayList<SvCluster.DistributedLock> currentNode = new CopyOnWriteArrayList<SvCluster.DistributedLock>(); CopyOnWriteArrayList<SvCluster.DistributedLock> oldNode = nodeLocks.putIfAbsent(nodeId, currentNode); if (oldNode != null) currentNode = oldNode; currentNode.addIfAbsent(dlock); } } /** * Method to clean up the distributed locks acquired by a node * * @param nodeId * The node for which the distributed locks shall be cleaned */ static void clusterCleanUp(Long nodeId, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> nodeLocks, ConcurrentHashMap<String, SvCluster.DistributedLock> distributedLocks) { { CopyOnWriteArrayList<SvCluster.DistributedLock> nodeLock = nodeLocks.get(nodeId); if (nodeLock != null) { for (SvCluster.DistributedLock dstLock : nodeLock) { SvLock.releaseLock(dstLock.key, dstLock.lock); synchronized (distributedLocks) { distributedLocks.remove(dstLock.key, dstLock); } } nodeLocks.remove(nodeId); } } } /** * Method to migrate locks from one node to another. This is useful if the * node has lost a heart beat, then re-joined with a new node ID. In this * case we'll just migrate the locks from the old node id to the new one * * @param nodeId * The node under which the locks shall be moved * @param oldNodeId * The node from which the locks will be moved * @param nodeLocks * The map fo locks which shall be used (Server or Client side) */ static void migrateLocks(Long nodeId, Long oldNodeId, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> nodeLocks) { { CopyOnWriteArrayList<SvCluster.DistributedLock> nodeLock = nodeLocks.remove(oldNodeId); if (nodeLock != null) { for (SvCluster.DistributedLock dstLock : nodeLock) { dstLock.nodeId = nodeId; } nodeLocks.put(nodeId, nodeLock); } } } /** * Method to migrate locks from one node to another. This is useful if the * node has lost a heart beat, then re-joined with a new node ID. In this * case we'll just migrate the locks from the old node id to the new one * * @param nodeId * The node under which the locks shall be moved * @param oldNodeId * The node from which the locks will be moved * @param nodeLocks * The map fo locks which shall be used (Server or Client side) */ static void copyLocalLocks(Long nodeId, Long oldNodeId, ConcurrentHashMap<Long, CopyOnWriteArrayList<SvCluster.DistributedLock>> localNodeLocks) { { CopyOnWriteArrayList<SvCluster.DistributedLock> nodeLock = localNodeLocks.remove(oldNodeId); if (nodeLock != null) { for (SvCluster.DistributedLock dstLock : nodeLock) { SvLock.getDistributedLockImpl(dstLock.key, SvCluster.isCoordinator, nodeId); } } } } public static boolean isCoordinator() { return isCoordinator; } public static void setCoordinator(boolean isCoordinator) { SvCluster.isCoordinator = isCoordinator; } public static AtomicBoolean isRunning() { return isRunning; } public static AtomicBoolean getIsActive() { if (isCoordinator) return isActive; else return SvClusterClient.isActive; } public static void setIsActive(AtomicBoolean isActive) { SvCluster.isActive = isActive; } public static DbDataObject getCoordinatorNode() { return coordinatorNode; } public static void setCoordinatorNode(DbDataObject coordinatorNode) { SvCluster.coordinatorNode = coordinatorNode; } }
32.972222
119
0.714069
4a19e746d09a8d0d26630f783c0f736f6f6a001a
805
package ducky.core.levels; import ducky.Game; import ducky.core.entities.CV; import ducky.graphics.DRenderer; import ducky.graphics.Res; public class PlayLevel2 extends PlayLevel { public PlayLevel2() { super(Res.LEVEL2_BACKGROUND, 82, Res.LEVEL2_INFO, Res.LEVEL2_EOTLR, Res.LEVEL2_EOTLL, 4, 0, 0, 60); int limit = random.nextInt(30) + 50; for (int i = 0; i < limit; i++) { int skin = random.nextInt(2); add(new CV(this, genRandomPos(), Game.HEIGHT - height - 28, skin)); } } public void update() { super.update(); if (player.playerXP >= player.playerXPLimit) { player.endScene(); curTime--; if(player.endScene) Game.mainGame.startGame(new SelectionLevel()); } } public void render(DRenderer r) { super.render(r); r.render(Res.HELP_FILL, 5, 45); } }
22.361111
70
0.677019
8cbc0b335bb12971215f7932cba46a54522c5802
44,564
/** * Autogenerated by Frugal Compiler (2.9.1) * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * * @generated */ package variety.java; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Generated(value = "Autogenerated by Frugal Compiler (2.9.1)", date = "2015-11-24") public class EventWrapper implements org.apache.thrift.TBase<EventWrapper, EventWrapper._Fields>, java.io.Serializable, Cloneable, Comparable<EventWrapper> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("EventWrapper"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("ID", org.apache.thrift.protocol.TType.I64, (short)1); private static final org.apache.thrift.protocol.TField EV_FIELD_DESC = new org.apache.thrift.protocol.TField("Ev", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final org.apache.thrift.protocol.TField EVENTS_FIELD_DESC = new org.apache.thrift.protocol.TField("Events", org.apache.thrift.protocol.TType.LIST, (short)3); private static final org.apache.thrift.protocol.TField EVENTS2_FIELD_DESC = new org.apache.thrift.protocol.TField("Events2", org.apache.thrift.protocol.TType.SET, (short)4); private static final org.apache.thrift.protocol.TField EVENT_MAP_FIELD_DESC = new org.apache.thrift.protocol.TField("EventMap", org.apache.thrift.protocol.TType.MAP, (short)5); private static final org.apache.thrift.protocol.TField NUMS_FIELD_DESC = new org.apache.thrift.protocol.TField("Nums", org.apache.thrift.protocol.TType.LIST, (short)6); private static final org.apache.thrift.protocol.TField ENUMS_FIELD_DESC = new org.apache.thrift.protocol.TField("Enums", org.apache.thrift.protocol.TType.LIST, (short)7); private static final org.apache.thrift.protocol.TField A_BOOL_FIELD_FIELD_DESC = new org.apache.thrift.protocol.TField("aBoolField", org.apache.thrift.protocol.TType.BOOL, (short)8); private static final org.apache.thrift.protocol.TField A_UNION_FIELD_DESC = new org.apache.thrift.protocol.TField("a_union", org.apache.thrift.protocol.TType.STRUCT, (short)9); private static final org.apache.thrift.protocol.TField TYPEDEF_OF_TYPEDEF_FIELD_DESC = new org.apache.thrift.protocol.TField("typedefOfTypedef", org.apache.thrift.protocol.TType.STRING, (short)10); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new EventWrapperStandardSchemeFactory()); schemes.put(TupleScheme.class, new EventWrapperTupleSchemeFactory()); } public long ID; // optional public Event Ev; // required public java.util.List<Event> Events; // required public java.util.Set<Event> Events2; // required public java.util.Map<Long, Event> EventMap; // required public java.util.List<java.util.List<Integer>> Nums; // required public java.util.List<ItsAnEnum> Enums; // required public boolean aBoolField; // required public TestingUnions a_union; // required public String typedefOfTypedef; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "ID"), EV((short)2, "Ev"), EVENTS((short)3, "Events"), EVENTS2((short)4, "Events2"), EVENT_MAP((short)5, "EventMap"), NUMS((short)6, "Nums"), ENUMS((short)7, "Enums"), A_BOOL_FIELD((short)8, "aBoolField"), A_UNION((short)9, "a_union"), TYPEDEF_OF_TYPEDEF((short)10, "typedefOfTypedef") ; private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; case 2: // EV return EV; case 3: // EVENTS return EVENTS; case 4: // EVENTS2 return EVENTS2; case 5: // EVENT_MAP return EVENT_MAP; case 6: // NUMS return NUMS; case 7: // ENUMS return ENUMS; case 8: // A_BOOL_FIELD return A_BOOL_FIELD; case 9: // A_UNION return A_UNION; case 10: // TYPEDEF_OF_TYPEDEF return TYPEDEF_OF_TYPEDEF; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __ID_ISSET_ID = 0; private static final int __ABOOLFIELD_ISSET_ID = 1; private byte __isset_bitfield = 0; public EventWrapper() { } public EventWrapper( Event Ev, java.util.List<Event> Events, java.util.Set<Event> Events2, java.util.Map<Long, Event> EventMap, java.util.List<java.util.List<Integer>> Nums, java.util.List<ItsAnEnum> Enums, boolean aBoolField, TestingUnions a_union, String typedefOfTypedef) { this(); this.Ev = Ev; this.Events = Events; this.Events2 = Events2; this.EventMap = EventMap; this.Nums = Nums; this.Enums = Enums; this.aBoolField = aBoolField; setABoolFieldIsSet(true); this.a_union = a_union; this.typedefOfTypedef = typedefOfTypedef; } /** * Performs a deep copy on <i>other</i>. */ public EventWrapper(EventWrapper other) { __isset_bitfield = other.__isset_bitfield; this.ID = other.ID; if (other.isSetEv()) { this.Ev = new Event(other.Ev); } if (other.isSetEvents()) { this.Events = new ArrayList<Event>(other.Events.size()); for (Event elem93 : other.Events) { Event elem94 = new Event(elem93); this.Events.add(elem94); } } if (other.isSetEvents2()) { this.Events2 = new HashSet<Event>(other.Events2.size()); for (Event elem95 : other.Events2) { Event elem96 = new Event(elem95); this.Events2.add(elem96); } } if (other.isSetEventMap()) { this.EventMap = new HashMap<Long,Event>(other.EventMap.size()); for (Map.Entry<Long, Event> elem97 : other.EventMap.entrySet()) { long elem99 = elem97.getKey(); Event elem98 = new Event(elem97.getValue()); this.EventMap.put(elem99, elem98); } } if (other.isSetNums()) { this.Nums = new ArrayList<java.util.List<Integer>>(other.Nums.size()); for (java.util.List<Integer> elem100 : other.Nums) { java.util.List<Integer> elem101 = new ArrayList<Integer>(elem100.size()); for (int elem102 : elem100) { int elem103 = elem102; elem101.add(elem103); } this.Nums.add(elem101); } } if (other.isSetEnums()) { this.Enums = new ArrayList<ItsAnEnum>(other.Enums.size()); for (ItsAnEnum elem104 : other.Enums) { ItsAnEnum elem105 = elem104; this.Enums.add(elem105); } } this.aBoolField = other.aBoolField; if (other.isSetA_union()) { this.a_union = new TestingUnions(other.a_union); } if (other.isSetTypedefOfTypedef()) { this.typedefOfTypedef = other.typedefOfTypedef; } } public EventWrapper deepCopy() { return new EventWrapper(this); } @Override public void clear() { setIDIsSet(false); this.ID = 0L; this.Ev = null; this.Events = null; this.Events2 = null; this.EventMap = null; this.Nums = null; this.Enums = null; setABoolFieldIsSet(false); this.aBoolField = false; this.a_union = null; this.typedefOfTypedef = null; } public long getID() { return this.ID; } public EventWrapper setID(long ID) { this.ID = ID; setIDIsSet(true); return this; } public void unsetID() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID); } /** Returns true if field ID is set (has been assigned a value) and false otherwise */ public boolean isSetID() { return EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID); } public void setIDIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value); } public Event getEv() { return this.Ev; } public EventWrapper setEv(Event Ev) { this.Ev = Ev; return this; } public void unsetEv() { this.Ev = null; } /** Returns true if field Ev is set (has been assigned a value) and false otherwise */ public boolean isSetEv() { return this.Ev != null; } public void setEvIsSet(boolean value) { if (!value) { this.Ev = null; } } public int getEventsSize() { return (this.Events == null) ? 0 : this.Events.size(); } public java.util.Iterator<Event> getEventsIterator() { return (this.Events == null) ? null : this.Events.iterator(); } public void addToEvents(Event elem) { if (this.Events == null) { this.Events = new ArrayList<Event>(); } this.Events.add(elem); } public java.util.List<Event> getEvents() { return this.Events; } public EventWrapper setEvents(java.util.List<Event> Events) { this.Events = Events; return this; } public void unsetEvents() { this.Events = null; } /** Returns true if field Events is set (has been assigned a value) and false otherwise */ public boolean isSetEvents() { return this.Events != null; } public void setEventsIsSet(boolean value) { if (!value) { this.Events = null; } } public int getEvents2Size() { return (this.Events2 == null) ? 0 : this.Events2.size(); } public java.util.Iterator<Event> getEvents2Iterator() { return (this.Events2 == null) ? null : this.Events2.iterator(); } public void addToEvents2(Event elem) { if (this.Events2 == null) { this.Events2 = new HashSet<Event>(); } this.Events2.add(elem); } public java.util.Set<Event> getEvents2() { return this.Events2; } public EventWrapper setEvents2(java.util.Set<Event> Events2) { this.Events2 = Events2; return this; } public void unsetEvents2() { this.Events2 = null; } /** Returns true if field Events2 is set (has been assigned a value) and false otherwise */ public boolean isSetEvents2() { return this.Events2 != null; } public void setEvents2IsSet(boolean value) { if (!value) { this.Events2 = null; } } public int getEventMapSize() { return (this.EventMap == null) ? 0 : this.EventMap.size(); } public void putToEventMap(long key, Event val) { if (this.EventMap == null) { this.EventMap = new HashMap<Long,Event>(); } this.EventMap.put(key, val); } public java.util.Map<Long, Event> getEventMap() { return this.EventMap; } public EventWrapper setEventMap(java.util.Map<Long, Event> EventMap) { this.EventMap = EventMap; return this; } public void unsetEventMap() { this.EventMap = null; } /** Returns true if field EventMap is set (has been assigned a value) and false otherwise */ public boolean isSetEventMap() { return this.EventMap != null; } public void setEventMapIsSet(boolean value) { if (!value) { this.EventMap = null; } } public int getNumsSize() { return (this.Nums == null) ? 0 : this.Nums.size(); } public java.util.Iterator<java.util.List<Integer>> getNumsIterator() { return (this.Nums == null) ? null : this.Nums.iterator(); } public void addToNums(java.util.List<Integer> elem) { if (this.Nums == null) { this.Nums = new ArrayList<java.util.List<Integer>>(); } this.Nums.add(elem); } public java.util.List<java.util.List<Integer>> getNums() { return this.Nums; } public EventWrapper setNums(java.util.List<java.util.List<Integer>> Nums) { this.Nums = Nums; return this; } public void unsetNums() { this.Nums = null; } /** Returns true if field Nums is set (has been assigned a value) and false otherwise */ public boolean isSetNums() { return this.Nums != null; } public void setNumsIsSet(boolean value) { if (!value) { this.Nums = null; } } public int getEnumsSize() { return (this.Enums == null) ? 0 : this.Enums.size(); } public java.util.Iterator<ItsAnEnum> getEnumsIterator() { return (this.Enums == null) ? null : this.Enums.iterator(); } public void addToEnums(ItsAnEnum elem) { if (this.Enums == null) { this.Enums = new ArrayList<ItsAnEnum>(); } this.Enums.add(elem); } public java.util.List<ItsAnEnum> getEnums() { return this.Enums; } public EventWrapper setEnums(java.util.List<ItsAnEnum> Enums) { this.Enums = Enums; return this; } public void unsetEnums() { this.Enums = null; } /** Returns true if field Enums is set (has been assigned a value) and false otherwise */ public boolean isSetEnums() { return this.Enums != null; } public void setEnumsIsSet(boolean value) { if (!value) { this.Enums = null; } } public boolean isABoolField() { return this.aBoolField; } public EventWrapper setABoolField(boolean aBoolField) { this.aBoolField = aBoolField; setABoolFieldIsSet(true); return this; } public void unsetABoolField() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ABOOLFIELD_ISSET_ID); } /** Returns true if field aBoolField is set (has been assigned a value) and false otherwise */ public boolean isSetABoolField() { return EncodingUtils.testBit(__isset_bitfield, __ABOOLFIELD_ISSET_ID); } public void setABoolFieldIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ABOOLFIELD_ISSET_ID, value); } public TestingUnions getA_union() { return this.a_union; } public EventWrapper setA_union(TestingUnions a_union) { this.a_union = a_union; return this; } public void unsetA_union() { this.a_union = null; } /** Returns true if field a_union is set (has been assigned a value) and false otherwise */ public boolean isSetA_union() { return this.a_union != null; } public void setA_unionIsSet(boolean value) { if (!value) { this.a_union = null; } } public String getTypedefOfTypedef() { return this.typedefOfTypedef; } public EventWrapper setTypedefOfTypedef(String typedefOfTypedef) { this.typedefOfTypedef = typedefOfTypedef; return this; } public void unsetTypedefOfTypedef() { this.typedefOfTypedef = null; } /** Returns true if field typedefOfTypedef is set (has been assigned a value) and false otherwise */ public boolean isSetTypedefOfTypedef() { return this.typedefOfTypedef != null; } public void setTypedefOfTypedefIsSet(boolean value) { if (!value) { this.typedefOfTypedef = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetID(); } else { setID((Long)value); } break; case EV: if (value == null) { unsetEv(); } else { setEv((Event)value); } break; case EVENTS: if (value == null) { unsetEvents(); } else { setEvents((java.util.List<Event>)value); } break; case EVENTS2: if (value == null) { unsetEvents2(); } else { setEvents2((java.util.Set<Event>)value); } break; case EVENT_MAP: if (value == null) { unsetEventMap(); } else { setEventMap((java.util.Map<Long, Event>)value); } break; case NUMS: if (value == null) { unsetNums(); } else { setNums((java.util.List<java.util.List<Integer>>)value); } break; case ENUMS: if (value == null) { unsetEnums(); } else { setEnums((java.util.List<ItsAnEnum>)value); } break; case A_BOOL_FIELD: if (value == null) { unsetABoolField(); } else { setABoolField((Boolean)value); } break; case A_UNION: if (value == null) { unsetA_union(); } else { setA_union((TestingUnions)value); } break; case TYPEDEF_OF_TYPEDEF: if (value == null) { unsetTypedefOfTypedef(); } else { setTypedefOfTypedef((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return getID(); case EV: return getEv(); case EVENTS: return getEvents(); case EVENTS2: return getEvents2(); case EVENT_MAP: return getEventMap(); case NUMS: return getNums(); case ENUMS: return getEnums(); case A_BOOL_FIELD: return isABoolField(); case A_UNION: return getA_union(); case TYPEDEF_OF_TYPEDEF: return getTypedefOfTypedef(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetID(); case EV: return isSetEv(); case EVENTS: return isSetEvents(); case EVENTS2: return isSetEvents2(); case EVENT_MAP: return isSetEventMap(); case NUMS: return isSetNums(); case ENUMS: return isSetEnums(); case A_BOOL_FIELD: return isSetABoolField(); case A_UNION: return isSetA_union(); case TYPEDEF_OF_TYPEDEF: return isSetTypedefOfTypedef(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof EventWrapper) return this.equals((EventWrapper)that); return false; } public boolean equals(EventWrapper that) { if (that == null) return false; boolean this_present_ID = true && this.isSetID(); boolean that_present_ID = true && that.isSetID(); if (this_present_ID || that_present_ID) { if (!(this_present_ID && that_present_ID)) return false; if (this.ID != that.ID) return false; } boolean this_present_Ev = true && this.isSetEv(); boolean that_present_Ev = true && that.isSetEv(); if (this_present_Ev || that_present_Ev) { if (!(this_present_Ev && that_present_Ev)) return false; if (!this.Ev.equals(that.Ev)) return false; } boolean this_present_Events = true && this.isSetEvents(); boolean that_present_Events = true && that.isSetEvents(); if (this_present_Events || that_present_Events) { if (!(this_present_Events && that_present_Events)) return false; if (!this.Events.equals(that.Events)) return false; } boolean this_present_Events2 = true && this.isSetEvents2(); boolean that_present_Events2 = true && that.isSetEvents2(); if (this_present_Events2 || that_present_Events2) { if (!(this_present_Events2 && that_present_Events2)) return false; if (!this.Events2.equals(that.Events2)) return false; } boolean this_present_EventMap = true && this.isSetEventMap(); boolean that_present_EventMap = true && that.isSetEventMap(); if (this_present_EventMap || that_present_EventMap) { if (!(this_present_EventMap && that_present_EventMap)) return false; if (!this.EventMap.equals(that.EventMap)) return false; } boolean this_present_Nums = true && this.isSetNums(); boolean that_present_Nums = true && that.isSetNums(); if (this_present_Nums || that_present_Nums) { if (!(this_present_Nums && that_present_Nums)) return false; if (!this.Nums.equals(that.Nums)) return false; } boolean this_present_Enums = true && this.isSetEnums(); boolean that_present_Enums = true && that.isSetEnums(); if (this_present_Enums || that_present_Enums) { if (!(this_present_Enums && that_present_Enums)) return false; if (!this.Enums.equals(that.Enums)) return false; } boolean this_present_aBoolField = true; boolean that_present_aBoolField = true; if (this_present_aBoolField || that_present_aBoolField) { if (!(this_present_aBoolField && that_present_aBoolField)) return false; if (this.aBoolField != that.aBoolField) return false; } boolean this_present_a_union = true && this.isSetA_union(); boolean that_present_a_union = true && that.isSetA_union(); if (this_present_a_union || that_present_a_union) { if (!(this_present_a_union && that_present_a_union)) return false; if (!this.a_union.equals(that.a_union)) return false; } boolean this_present_typedefOfTypedef = true && this.isSetTypedefOfTypedef(); boolean that_present_typedefOfTypedef = true && that.isSetTypedefOfTypedef(); if (this_present_typedefOfTypedef || that_present_typedefOfTypedef) { if (!(this_present_typedefOfTypedef && that_present_typedefOfTypedef)) return false; if (!this.typedefOfTypedef.equals(that.typedefOfTypedef)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_ID = true && (isSetID()); list.add(present_ID); if (present_ID) list.add(ID); boolean present_Ev = true && (isSetEv()); list.add(present_Ev); if (present_Ev) list.add(Ev); boolean present_Events = true && (isSetEvents()); list.add(present_Events); if (present_Events) list.add(Events); boolean present_Events2 = true && (isSetEvents2()); list.add(present_Events2); if (present_Events2) list.add(Events2); boolean present_EventMap = true && (isSetEventMap()); list.add(present_EventMap); if (present_EventMap) list.add(EventMap); boolean present_Nums = true && (isSetNums()); list.add(present_Nums); if (present_Nums) list.add(Nums); boolean present_Enums = true && (isSetEnums()); list.add(present_Enums); if (present_Enums) list.add(Enums); boolean present_aBoolField = true; list.add(present_aBoolField); if (present_aBoolField) list.add(aBoolField); boolean present_a_union = true && (isSetA_union()); list.add(present_a_union); if (present_a_union) list.add(a_union); boolean present_typedefOfTypedef = true && (isSetTypedefOfTypedef()); list.add(present_typedefOfTypedef); if (present_typedefOfTypedef) list.add(typedefOfTypedef); return list.hashCode(); } @Override public int compareTo(EventWrapper other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetID()).compareTo(other.isSetID()); if (lastComparison != 0) { return lastComparison; } if (isSetID()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ID, other.ID); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEv()).compareTo(other.isSetEv()); if (lastComparison != 0) { return lastComparison; } if (isSetEv()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.Ev, other.Ev); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEvents()).compareTo(other.isSetEvents()); if (lastComparison != 0) { return lastComparison; } if (isSetEvents()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.Events, other.Events); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEvents2()).compareTo(other.isSetEvents2()); if (lastComparison != 0) { return lastComparison; } if (isSetEvents2()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.Events2, other.Events2); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEventMap()).compareTo(other.isSetEventMap()); if (lastComparison != 0) { return lastComparison; } if (isSetEventMap()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.EventMap, other.EventMap); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetNums()).compareTo(other.isSetNums()); if (lastComparison != 0) { return lastComparison; } if (isSetNums()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.Nums, other.Nums); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEnums()).compareTo(other.isSetEnums()); if (lastComparison != 0) { return lastComparison; } if (isSetEnums()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.Enums, other.Enums); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetABoolField()).compareTo(other.isSetABoolField()); if (lastComparison != 0) { return lastComparison; } if (isSetABoolField()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.aBoolField, other.aBoolField); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetA_union()).compareTo(other.isSetA_union()); if (lastComparison != 0) { return lastComparison; } if (isSetA_union()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.a_union, other.a_union); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetTypedefOfTypedef()).compareTo(other.isSetTypedefOfTypedef()); if (lastComparison != 0) { return lastComparison; } if (isSetTypedefOfTypedef()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.typedefOfTypedef, other.typedefOfTypedef); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("EventWrapper("); boolean first = true; if (isSetID()) { sb.append("ID:"); sb.append(this.ID); first = false; } if (!first) sb.append(", "); sb.append("Ev:"); if (this.Ev == null) { sb.append("null"); } else { sb.append(this.Ev); } first = false; if (!first) sb.append(", "); sb.append("Events:"); if (this.Events == null) { sb.append("null"); } else { sb.append(this.Events); } first = false; if (!first) sb.append(", "); sb.append("Events2:"); if (this.Events2 == null) { sb.append("null"); } else { sb.append(this.Events2); } first = false; if (!first) sb.append(", "); sb.append("EventMap:"); if (this.EventMap == null) { sb.append("null"); } else { sb.append(this.EventMap); } first = false; if (!first) sb.append(", "); sb.append("Nums:"); if (this.Nums == null) { sb.append("null"); } else { sb.append(this.Nums); } first = false; if (!first) sb.append(", "); sb.append("Enums:"); if (this.Enums == null) { sb.append("null"); } else { sb.append(this.Enums); } first = false; if (!first) sb.append(", "); sb.append("aBoolField:"); sb.append(this.aBoolField); first = false; if (!first) sb.append(", "); sb.append("a_union:"); if (this.a_union == null) { sb.append("null"); } else { sb.append(this.a_union); } first = false; if (!first) sb.append(", "); sb.append("typedefOfTypedef:"); if (this.typedefOfTypedef == null) { sb.append("null"); } else { sb.append(this.typedefOfTypedef); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (Ev == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'Ev' was not present for struct type 'EventWrapper'"); } // check for sub-struct validity if (Ev != null) { Ev.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class EventWrapperStandardSchemeFactory implements SchemeFactory { public EventWrapperStandardScheme getScheme() { return new EventWrapperStandardScheme(); } } private static class EventWrapperStandardScheme extends StandardScheme<EventWrapper> { public void read(org.apache.thrift.protocol.TProtocol iprot, EventWrapper struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.ID = iprot.readI64(); struct.setIDIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // EV if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.Ev = new Event(); struct.Ev.read(iprot); struct.setEvIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // EVENTS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { org.apache.thrift.protocol.TList elem106 = iprot.readListBegin(); struct.Events = new ArrayList<Event>(elem106.size); for (int elem107 = 0; elem107 < elem106.size; ++elem107) { Event elem108 = new Event(); elem108.read(iprot); struct.Events.add(elem108); } iprot.readListEnd(); struct.setEventsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // EVENTS2 if (schemeField.type == org.apache.thrift.protocol.TType.SET) { org.apache.thrift.protocol.TSet elem109 = iprot.readSetBegin(); struct.Events2 = new HashSet<Event>(2*elem109.size); for (int elem110 = 0; elem110 < elem109.size; ++elem110) { Event elem111 = new Event(); elem111.read(iprot); struct.Events2.add(elem111); } iprot.readSetEnd(); struct.setEvents2IsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // EVENT_MAP if (schemeField.type == org.apache.thrift.protocol.TType.MAP) { org.apache.thrift.protocol.TMap elem112 = iprot.readMapBegin(); struct.EventMap = new HashMap<Long,Event>(2*elem112.size); for (int elem113 = 0; elem113 < elem112.size; ++elem113) { long elem115 = iprot.readI64(); Event elem114 = new Event(); elem114.read(iprot); struct.EventMap.put(elem115, elem114); } iprot.readMapEnd(); struct.setEventMapIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NUMS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { org.apache.thrift.protocol.TList elem116 = iprot.readListBegin(); struct.Nums = new ArrayList<java.util.List<Integer>>(elem116.size); for (int elem117 = 0; elem117 < elem116.size; ++elem117) { org.apache.thrift.protocol.TList elem119 = iprot.readListBegin(); java.util.List<Integer> elem118 = new ArrayList<Integer>(elem119.size); for (int elem120 = 0; elem120 < elem119.size; ++elem120) { int elem121 = iprot.readI32(); elem118.add(elem121); } iprot.readListEnd(); struct.Nums.add(elem118); } iprot.readListEnd(); struct.setNumsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // ENUMS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { org.apache.thrift.protocol.TList elem122 = iprot.readListBegin(); struct.Enums = new ArrayList<ItsAnEnum>(elem122.size); for (int elem123 = 0; elem123 < elem122.size; ++elem123) { ItsAnEnum elem124 = ItsAnEnum.findByValue(iprot.readI32()); struct.Enums.add(elem124); } iprot.readListEnd(); struct.setEnumsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 8: // A_BOOL_FIELD if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.aBoolField = iprot.readBool(); struct.setABoolFieldIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 9: // A_UNION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.a_union = new TestingUnions(); struct.a_union.read(iprot); struct.setA_unionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 10: // TYPEDEF_OF_TYPEDEF if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.typedefOfTypedef = iprot.readString(); struct.setTypedefOfTypedefIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, EventWrapper struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.isSetID()) { oprot.writeFieldBegin(ID_FIELD_DESC); long elem125 = struct.ID; oprot.writeI64(elem125); oprot.writeFieldEnd(); } if (struct.Ev != null) { oprot.writeFieldBegin(EV_FIELD_DESC); struct.Ev.write(oprot); oprot.writeFieldEnd(); } if (struct.Events != null) { oprot.writeFieldBegin(EVENTS_FIELD_DESC); oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.Events.size())); for (Event elem126 : struct.Events) { elem126.write(oprot); } oprot.writeListEnd(); oprot.writeFieldEnd(); } if (struct.Events2 != null) { oprot.writeFieldBegin(EVENTS2_FIELD_DESC); oprot.writeSetBegin(new org.apache.thrift.protocol.TSet(org.apache.thrift.protocol.TType.STRUCT, struct.Events2.size())); for (Event elem127 : struct.Events2) { elem127.write(oprot); } oprot.writeSetEnd(); oprot.writeFieldEnd(); } if (struct.EventMap != null) { oprot.writeFieldBegin(EVENT_MAP_FIELD_DESC); oprot.writeMapBegin(new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.I64, org.apache.thrift.protocol.TType.STRUCT, struct.EventMap.size())); for (Map.Entry<Long, Event> elem128 : struct.EventMap.entrySet()) { long elem129 = elem128.getKey(); oprot.writeI64(elem129); elem128.getValue().write(oprot); } oprot.writeMapEnd(); oprot.writeFieldEnd(); } if (struct.Nums != null) { oprot.writeFieldBegin(NUMS_FIELD_DESC); oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.LIST, struct.Nums.size())); for (java.util.List<Integer> elem130 : struct.Nums) { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.I32, elem130.size())); for (int elem131 : elem130) { int elem132 = elem131; oprot.writeI32(elem132); } oprot.writeListEnd(); } oprot.writeListEnd(); oprot.writeFieldEnd(); } if (struct.Enums != null) { oprot.writeFieldBegin(ENUMS_FIELD_DESC); oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.I32, struct.Enums.size())); for (ItsAnEnum elem133 : struct.Enums) { ItsAnEnum elem134 = elem133; oprot.writeI32(elem134.getValue()); } oprot.writeListEnd(); oprot.writeFieldEnd(); } oprot.writeFieldBegin(A_BOOL_FIELD_FIELD_DESC); boolean elem135 = struct.aBoolField; oprot.writeBool(elem135); oprot.writeFieldEnd(); if (struct.a_union != null) { oprot.writeFieldBegin(A_UNION_FIELD_DESC); struct.a_union.write(oprot); oprot.writeFieldEnd(); } if (struct.typedefOfTypedef != null) { oprot.writeFieldBegin(TYPEDEF_OF_TYPEDEF_FIELD_DESC); String elem136 = struct.typedefOfTypedef; oprot.writeString(elem136); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class EventWrapperTupleSchemeFactory implements SchemeFactory { public EventWrapperTupleScheme getScheme() { return new EventWrapperTupleScheme(); } } private static class EventWrapperTupleScheme extends TupleScheme<EventWrapper> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, EventWrapper struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; struct.Ev.write(oprot); BitSet optionals = new BitSet(); if (struct.isSetID()) { optionals.set(0); } if (struct.isSetEvents()) { optionals.set(1); } if (struct.isSetEvents2()) { optionals.set(2); } if (struct.isSetEventMap()) { optionals.set(3); } if (struct.isSetNums()) { optionals.set(4); } if (struct.isSetEnums()) { optionals.set(5); } if (struct.isSetABoolField()) { optionals.set(6); } if (struct.isSetA_union()) { optionals.set(7); } if (struct.isSetTypedefOfTypedef()) { optionals.set(8); } oprot.writeBitSet(optionals, 9); if (struct.isSetID()) { long elem137 = struct.ID; oprot.writeI64(elem137); } if (struct.isSetEvents()) { oprot.writeI32(struct.Events.size()); for (Event elem138 : struct.Events) { elem138.write(oprot); } } if (struct.isSetEvents2()) { oprot.writeI32(struct.Events2.size()); for (Event elem139 : struct.Events2) { elem139.write(oprot); } } if (struct.isSetEventMap()) { oprot.writeI32(struct.EventMap.size()); for (Map.Entry<Long, Event> elem140 : struct.EventMap.entrySet()) { long elem141 = elem140.getKey(); oprot.writeI64(elem141); elem140.getValue().write(oprot); } } if (struct.isSetNums()) { oprot.writeI32(struct.Nums.size()); for (java.util.List<Integer> elem142 : struct.Nums) { oprot.writeI32(elem142.size()); for (int elem143 : elem142) { int elem144 = elem143; oprot.writeI32(elem144); } } } if (struct.isSetEnums()) { oprot.writeI32(struct.Enums.size()); for (ItsAnEnum elem145 : struct.Enums) { ItsAnEnum elem146 = elem145; oprot.writeI32(elem146.getValue()); } } if (struct.isSetABoolField()) { boolean elem147 = struct.aBoolField; oprot.writeBool(elem147); } if (struct.isSetA_union()) { struct.a_union.write(oprot); } if (struct.isSetTypedefOfTypedef()) { String elem148 = struct.typedefOfTypedef; oprot.writeString(elem148); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, EventWrapper struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; struct.Ev = new Event(); struct.Ev.read(iprot); struct.setEvIsSet(true); BitSet incoming = iprot.readBitSet(9); if (incoming.get(0)) { struct.ID = iprot.readI64(); struct.setIDIsSet(true); } if (incoming.get(1)) { org.apache.thrift.protocol.TList elem149 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.Events = new ArrayList<Event>(elem149.size); for (int elem150 = 0; elem150 < elem149.size; ++elem150) { Event elem151 = new Event(); elem151.read(iprot); struct.Events.add(elem151); } struct.setEventsIsSet(true); } if (incoming.get(2)) { org.apache.thrift.protocol.TSet elem152 = new org.apache.thrift.protocol.TSet(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.Events2 = new HashSet<Event>(2*elem152.size); for (int elem153 = 0; elem153 < elem152.size; ++elem153) { Event elem154 = new Event(); elem154.read(iprot); struct.Events2.add(elem154); } struct.setEvents2IsSet(true); } if (incoming.get(3)) { org.apache.thrift.protocol.TMap elem155 = new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.I64, org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.EventMap = new HashMap<Long,Event>(2*elem155.size); for (int elem156 = 0; elem156 < elem155.size; ++elem156) { long elem158 = iprot.readI64(); Event elem157 = new Event(); elem157.read(iprot); struct.EventMap.put(elem158, elem157); } struct.setEventMapIsSet(true); } if (incoming.get(4)) { org.apache.thrift.protocol.TList elem159 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.LIST, iprot.readI32()); struct.Nums = new ArrayList<java.util.List<Integer>>(elem159.size); for (int elem160 = 0; elem160 < elem159.size; ++elem160) { org.apache.thrift.protocol.TList elem162 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.I32, iprot.readI32()); java.util.List<Integer> elem161 = new ArrayList<Integer>(elem162.size); for (int elem163 = 0; elem163 < elem162.size; ++elem163) { int elem164 = iprot.readI32(); elem161.add(elem164); } struct.Nums.add(elem161); } struct.setNumsIsSet(true); } if (incoming.get(5)) { org.apache.thrift.protocol.TList elem165 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.I32, iprot.readI32()); struct.Enums = new ArrayList<ItsAnEnum>(elem165.size); for (int elem166 = 0; elem166 < elem165.size; ++elem166) { ItsAnEnum elem167 = ItsAnEnum.findByValue(iprot.readI32()); struct.Enums.add(elem167); } struct.setEnumsIsSet(true); } if (incoming.get(6)) { struct.aBoolField = iprot.readBool(); struct.setABoolFieldIsSet(true); } if (incoming.get(7)) { struct.a_union = new TestingUnions(); struct.a_union.read(iprot); struct.setA_unionIsSet(true); } if (incoming.get(8)) { struct.typedefOfTypedef = iprot.readString(); struct.setTypedefOfTypedefIsSet(true); } } } }
28.825356
198
0.683668
0b3d0dfaaa1622edf08a4789c65725173188346f
3,994
/* * Copyright © 2020 Treblereel * * 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.treblereel.gwt.xml.mapper.apt.generator; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.expr.NormalAnnotationExpr; import com.github.javaparser.ast.expr.StringLiteralExpr; import com.google.auto.common.MoreElements; import java.io.IOException; import java.io.PrintWriter; import javax.annotation.processing.FilerException; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.tools.JavaFileObject; import org.treblereel.gwt.xml.mapper.apt.TypeUtils; import org.treblereel.gwt.xml.mapper.apt.context.GenerationContext; import org.treblereel.gwt.xml.mapper.apt.definition.BeanDefinition; import org.treblereel.gwt.xml.mapper.apt.exception.GenerationException; import org.treblereel.gwt.xml.mapper.apt.logger.TreeLogger; /** @author Dmitrii Tikhomirov Created by treblereel 3/19/20 */ public abstract class AbstractGenerator { protected final GenerationContext context; protected final TypeUtils typeUtils; protected final TreeLogger logger; protected CompilationUnit cu; protected ClassOrInterfaceDeclaration declaration; public AbstractGenerator(GenerationContext context, TreeLogger logger) { this.context = context; this.logger = logger; this.typeUtils = context.getTypeUtils(); } public void generate(BeanDefinition type) { cu = new CompilationUnit(); cu.setPackageDeclaration(context.getTypeUtils().getPackage(type.getBean())); declaration = cu.addClass(getMapperName(type.getElement())); // addGeneratedAnnotation(declaration); configureClassType(type); addTypeParam(type, declaration); getType(type); init(type); write(type.getElement()); } private void addGeneratedAnnotation(ClassOrInterfaceDeclaration declaration) { NormalAnnotationExpr generated = new NormalAnnotationExpr(); generated.setName("javax.annotation.processing.Generated"); generated.addPair("value", new StringLiteralExpr(this.getClass().getCanonicalName())); declaration.addAnnotation(generated); } protected abstract String getMapperName(TypeElement type); protected abstract void configureClassType(BeanDefinition type); protected void addTypeParam(BeanDefinition type, ClassOrInterfaceDeclaration declaration) {} protected void getType(BeanDefinition type) {} protected abstract void init(BeanDefinition type); protected void write(TypeElement type) { logger.branch(TreeLogger.INFO, "Writing " + getMapperName(type)); TypeMirror property = context.getTypeUtils().removeOuterWildCards(type.asType()); if (!context.getTypeRegistry().containsDeserializer(property)) { try { build(MoreElements.getPackage(type) + "." + getMapperName(type), cu.toString()); } catch (javax.annotation.processing.FilerException e1) { logger.log(TreeLogger.ERROR, e1.getMessage()); } catch (IOException e1) { throw new GenerationException(e1); } } } private void build(String fileName, String source) throws IOException { JavaFileObject builderFile = context.getProcessingEnv().getFiler().createSourceFile(fileName); try (PrintWriter out = new PrintWriter(builderFile.openWriter())) { out.append(source); } catch (FilerException e) { throw new GenerationException(e); } } }
38.403846
98
0.763645