blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2 values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82 values | src_encoding stringclasses 28 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 5.41M | extension stringclasses 11 values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c01452948b4c30792f133bbed95cad6a8d363918 | 372dce529f3123c868cafb43e81936e039662b42 | /app/libs/jxl/biff/formula/Operator.java | 48378743a9049ff0347c48764db3dc47d83e6b60 | [] | no_license | zongshengruhai/grt-vdc | 9c357aa909d996aa8af1345a49f5c9e8c18f3f89 | a67b7f647769f3ded78f8bab0856f78750c4f497 | refs/heads/master | 2020-03-27T17:07:57.050321 | 2019-03-19T07:14:35 | 2019-03-19T07:14:35 | 146,830,292 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,429 | java | /*********************************************************************
*
* Copyright (C) 2002 Andrew Khan
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***************************************************************************/
package jxl.biff.formula;
import java.util.Stack;
import java.util.ArrayList;
/**
* An operator is a node in a parse tree. Its children can be other
* operators or operands
* Arithmetic operators and functions are all considered operators
*/
abstract class Operator extends ParseItem
{
/**
* The items which this operator manipulates. There will be at most two
*/
private ParseItem[] operands;
/**
* Constructor
*/
public Operator()
{
operands = new ParseItem[0];
}
/**
* Tells the operands to use the alternate code
*/
protected void setOperandAlternateCode()
{
for (int i = 0 ; i < operands.length ; i++)
{
operands[i].setAlternateCode();
}
}
/**
* Adds operands to this item
*/
protected void add(ParseItem n)
{
n.setParent(this);
// Grow the array
ParseItem[] newOperands = new ParseItem[operands.length + 1];
System.arraycopy(operands, 0, newOperands, 0, operands.length);
newOperands[operands.length] = n;
operands = newOperands;
}
/**
* Gets the operands for this operator from the stack
*/
public abstract void getOperands(Stack s);
/**
* Gets the operands ie. the children of the node
*/
protected ParseItem[] getOperands()
{
return operands;
}
/**
* Gets the precedence for this operator. Operator precedents run from
* 1 to 5, one being the highest, 5 being the lowest
*
* @return the operator precedence
*/
abstract int getPrecedence();
}
| [
"1104213258@qq.com"
] | 1104213258@qq.com |
9ef59aacbedf73dcba5a40e38900abd038dd5695 | 0fb25f145d5dbded3d795d0553071d9943e74fb1 | /src/fr/istic/ia/tp1/PlayerMCTS.java | debe9676965b1e4875acfab2dc1985da5a4ef04f | [] | no_license | Artkoto/Implemenattion_MCTS-Dames_Anglaise_-_Tic-Tac-Toe- | b9a638601af0087e96ecf4726addb3d87e180611 | cbcb41e4277911a8ce1cd867f104bb3e3243bd7d | refs/heads/main | 2023-04-30T22:51:27.177820 | 2021-05-17T19:56:46 | 2021-05-17T19:56:46 | 337,890,818 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 768 | java | package fr.istic.ia.tp1;
/**
* An implementation of {@link Player} that uses the MCTS algorithm
* @author vdrevell
*
*/
public class PlayerMCTS implements Player {
private int timeAllowedMillis;
/**
* Default constructor, sets a computation timeout of 1000 ms.
*/
public PlayerMCTS() {
this(1000);
}
/**
* Constructor with ability to set the maximum allowed computation time
* @param timeAllowedMillis: allowed computation time, in milliseconds.
*/
public PlayerMCTS(int timeAllowedMillis) {
this.timeAllowedMillis = timeAllowedMillis;
}
@Override
public Game.Move play(Game game) {
MonteCarloTreeSearch mcts = new MonteCarloTreeSearch(game);
mcts.evaluateTreeWithTimeLimit(timeAllowedMillis);
return mcts.getBestMove();
}
}
| [
"arnaudakoto@live.fr"
] | arnaudakoto@live.fr |
7affdc034032755db1a0760c42183be7c1b06ee7 | 2b2fcb1902206ad0f207305b9268838504c3749b | /WakfuClientSources/srcx/class_4042_blJ.java | 17883a0a9f5017d0f85f32253cd7d907cdc8f283 | [] | no_license | shelsonjava/Synx | 4fbcee964631f747efc9296477dee5a22826791a | 0cb26d5473ba1f36a3ea1d7163a5b9e6ebcb0b1d | refs/heads/master | 2021-01-15T13:51:41.816571 | 2013-11-17T10:46:22 | 2013-11-17T10:46:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,250 | java | import org.apache.log4j.Logger;
public final class blJ
{
private static Logger K = Logger.getLogger(blJ.class);
private static final bWH fCR = new anh();
public static bWH bwM() {
return fCR;
}
public static void a(int paramInt, bES parambES)
{
Object localObject;
switch (paramInt) {
case 4122:
localObject = new cbz();
break;
case 6200:
localObject = new cqM();
break;
case 6204:
localObject = new aqS();
break;
case 8014:
localObject = new dfW();
break;
case 4520:
localObject = new beB();
break;
case 4522:
localObject = new crB();
break;
case 8412:
localObject = new bla();
break;
case 8302:
localObject = new avi();
break;
case 8108:
localObject = new axW();
break;
case 4524:
localObject = new dBH();
break;
case 4528:
localObject = new cKA();
break;
case 8410:
localObject = new ato();
break;
case 4506:
localObject = new ben();
break;
case 8106:
localObject = new cUH();
break;
case 8002:
localObject = new cnF();
break;
case 8028:
localObject = new dgJ();
break;
case 8010:
localObject = new brM();
break;
case 8304:
localObject = new bDZ();
break;
case 4300:
localObject = new beM();
break;
case 202:
localObject = new tN();
break;
case 8033:
localObject = new Mk();
break;
case 8034:
localObject = new Wz();
break;
case 8120:
localObject = new ciP();
break;
case 8124:
localObject = new qp();
break;
case 8122:
localObject = new Rg();
break;
case 8110:
localObject = new aHs();
break;
case 8116:
localObject = new dMk();
break;
case 4123:
localObject = new dRd();
break;
case 8200:
localObject = new aJy();
break;
default:
K.warn("ATTENTION : l'id de message passé en parametre n'est pas géré par la factory : " + paramInt);
localObject = fCR;
}
((bWH)localObject).jl(paramInt);
parambES.a((bWH)localObject);
}
} | [
"music_inme@hotmail.fr"
] | music_inme@hotmail.fr |
29fe7f12cae4accb6a379cfb273da1145d47088d | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/24/24_47985c29e37aa210f58b86efdcca0264b36e5a03/ReviewItemTabPropertySection/24_47985c29e37aa210f58b86efdcca0264b36e5a03_ReviewItemTabPropertySection_s.java | bda49203bb9787a798cba0db531428250be26aea | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 17,557 | java | // $codepro.audit.disable com.instantiations.assist.eclipse.analysis.audit.rule.effectivejava.alwaysOverridetoString.alwaysOverrideToString, staticFieldSecurity, com.instantiations.assist.eclipse.analysis.deserializeabilitySecurity, com.instantiations.assist.eclipse.analysis.enforceCloneableUsageSecurity, explicitThisUsage
/*******************************************************************************
* Copyright (c) 2010, 2012 Ericsson AB and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ericsson AB - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.reviews.r4e.ui.internal.properties.tabbed;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.eclipse.emf.common.util.EList;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EItem;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EParticipant;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EReviewPhase;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EReviewState;
import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.OutOfSyncException;
import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.ResourceHandlingException;
import org.eclipse.mylyn.reviews.r4e.ui.R4EUIPlugin;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIModelController;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIReviewItem;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.R4EUIConstants;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.UIUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.views.properties.tabbed.ITabbedPropertyConstants;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetWidgetFactory;
/**
* This class implements the tabbed property section for the Review Item model element
*
* @author Sebastien Dubois
* @version $Revision: 1.0 $
*/
public class ReviewItemTabPropertySection extends ModelElementTabPropertySection {
// ------------------------------------------------------------------------
// Member variables
// ------------------------------------------------------------------------
/**
* Field fAuthorText.
*/
private Text fAuthorText = null;
/**
* Field fAuthorRepText.
*/
private Text fAuthorRepText = null;
/**
* Field fProjectIdList.
*/
private List fProjectIdList = null;
/**
* Field fRepositoryText.
*/
private Text fRepositoryText = null;
/**
* Field fDateSubmitted.
*/
private Text fDateSubmitted = null;
/**
* Field fDescriptionText.
*/
protected Text fDescriptionText = null;
/**
* Field fAssignedToComposite.
*/
private Composite fAssignedToComposite;
/**
* Field fAssignedToText.
*/
private Text fAssignedToText;
/**
* Field fAssignedToButton.
*/
private Button fAssignedToButton;
/**
* Field fUnassignedFromButton.
*/
private Button fUnassignedFromButton;
// ------------------------------------------------------------------------
// Methods
// ------------------------------------------------------------------------
/**
* Method shouldUseExtraSpace.
*
* @return boolean
* @see org.eclipse.ui.views.properties.tabbed.ISection#shouldUseExtraSpace()
*/
@Override
public boolean shouldUseExtraSpace() {
return true;
}
/**
* Method createControls.
*
* @param parent
* Composite
* @param aTabbedPropertySheetPage
* TabbedPropertySheetPage
* @see org.eclipse.ui.views.properties.tabbed.ISection#createControls(Composite, TabbedPropertySheetPage)
*/
@Override
public void createControls(Composite parent, TabbedPropertySheetPage aTabbedPropertySheetPage) {
super.createControls(parent, aTabbedPropertySheetPage);
//Tell element to build its own detailed tab layout
final TabbedPropertySheetWidgetFactory widgetFactory = aTabbedPropertySheetPage.getWidgetFactory();
final Composite composite = widgetFactory.createFlatFormComposite(parent);
FormData data = null;
//Author (read-only)
widgetFactory.setBorderStyle(SWT.NULL);
fAuthorText = widgetFactory.createText(composite, "", SWT.NULL);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(0, ITabbedPropertyConstants.VSPACE);
fAuthorText.setEditable(false);
fAuthorText.setToolTipText(R4EUIConstants.REVIEW_ITEM_AUTHOR_TOOLTIP);
fAuthorText.setLayoutData(data);
final CLabel authorLabel = widgetFactory.createCLabel(composite, R4EUIConstants.AUTHOR_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fAuthorText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fAuthorText, 0, SWT.CENTER);
authorLabel.setToolTipText(R4EUIConstants.REVIEW_ITEM_AUTHOR_TOOLTIP);
authorLabel.setLayoutData(data);
//AuthorRep (read-only)
fAuthorRepText = widgetFactory.createText(composite, "", SWT.NULL);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fAuthorText, ITabbedPropertyConstants.VSPACE);
fAuthorRepText.setEditable(false);
fAuthorRepText.setToolTipText(R4EUIConstants.REVIEW_ITEM_AUTHOR_REP_TOOLTIP);
fAuthorRepText.setLayoutData(data);
final CLabel authorRepLabel = widgetFactory.createCLabel(composite, R4EUIConstants.EMAIL_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fAuthorRepText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fAuthorRepText, 0, SWT.CENTER);
authorRepLabel.setToolTipText(R4EUIConstants.REVIEW_ITEM_AUTHOR_REP_TOOLTIP);
authorRepLabel.setLayoutData(data);
//ProjectId (read-only)
fProjectIdList = widgetFactory.createList(composite, SWT.READ_ONLY);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fAuthorRepText, ITabbedPropertyConstants.VSPACE);
fProjectIdList.setToolTipText(R4EUIConstants.REVIEW_ITEM_PROJECT_IDS_TOOLTIP);
fProjectIdList.setLayoutData(data);
final CLabel projectIdLabel = widgetFactory.createCLabel(composite, R4EUIConstants.PROJECT_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fProjectIdList, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fProjectIdList, 0, SWT.CENTER);
projectIdLabel.setToolTipText(R4EUIConstants.REVIEW_ITEM_PROJECT_IDS_TOOLTIP);
projectIdLabel.setLayoutData(data);
//Change Id (read-only)
fRepositoryText = widgetFactory.createText(composite, "", SWT.NULL);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fProjectIdList, ITabbedPropertyConstants.VSPACE);
fRepositoryText.setEditable(false);
fRepositoryText.setToolTipText(R4EUIConstants.REVIEW_ITEM_CHANGE_ID_TOOLTIP);
fRepositoryText.setLayoutData(data);
final CLabel repositoryLabel = widgetFactory.createCLabel(composite, R4EUIConstants.CHANGE_ID_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fRepositoryText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fRepositoryText, 0, SWT.CENTER);
repositoryLabel.setToolTipText(R4EUIConstants.REVIEW_ITEM_CHANGE_ID_TOOLTIP);
repositoryLabel.setLayoutData(data);
//Date Submitted (read-only)
fDateSubmitted = widgetFactory.createText(composite, "", SWT.NULL);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fRepositoryText, ITabbedPropertyConstants.VSPACE);
fDateSubmitted.setEditable(false);
fDateSubmitted.setToolTipText(R4EUIConstants.REVIEW_ITEM_DATE_SUBMITTED_TOOLTIP);
fDateSubmitted.setLayoutData(data);
final CLabel dateSubmittedLabel = widgetFactory.createCLabel(composite, R4EUIConstants.DATE_SUBMITTED_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fDateSubmitted, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fDateSubmitted, 0, SWT.CENTER);
dateSubmittedLabel.setToolTipText(R4EUIConstants.REVIEW_ITEM_DATE_SUBMITTED_TOOLTIP);
dateSubmittedLabel.setLayoutData(data);
//Description
widgetFactory.setBorderStyle(SWT.BORDER);
fDescriptionText = widgetFactory.createText(composite, "", SWT.MULTI);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fDateSubmitted, ITabbedPropertyConstants.VSPACE);
fDescriptionText.setToolTipText(R4EUIConstants.REVIEW_ITEM_DESCRIPTION_TOOLTIP);
fDescriptionText.setLayoutData(data);
fDescriptionText.addListener(SWT.FocusOut, new Listener() {
public void handleEvent(Event event) {
if (!fRefreshInProgress && fDescriptionText.getForeground().equals(UIUtils.ENABLED_FONT_COLOR)) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EItem modelItem = ((R4EUIReviewItem) fProperties.getElement()).getItem();
String newValue = fDescriptionText.getText().trim();
if (!newValue.equals(modelItem.getDescription())) {
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelItem, currentUser);
modelItem.setDescription(newValue);
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
}
fDescriptionText.setText(newValue);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
});
UIUtils.addTabbedPropertiesTextResizeListener(fDescriptionText);
final CLabel descriptionLabel = widgetFactory.createCLabel(composite, R4EUIConstants.DESCRIPTION_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fDescriptionText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fDescriptionText, 0, SWT.CENTER);
descriptionLabel.setToolTipText(R4EUIConstants.REVIEW_ITEM_DESCRIPTION_TOOLTIP);
descriptionLabel.setLayoutData(data);
//Assigned To
fAssignedToComposite = widgetFactory.createComposite(composite);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fDescriptionText, ITabbedPropertyConstants.VSPACE);
fAssignedToComposite.setToolTipText(R4EUIConstants.ASSIGNED_TO_TOOLTIP);
fAssignedToComposite.setLayoutData(data);
fAssignedToComposite.setLayout(new GridLayout(3, false));
fAssignedToText = widgetFactory.createText(fAssignedToComposite, "");
fAssignedToText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
fAssignedToText.setEditable(false);
fAssignedToButton = widgetFactory.createButton(fAssignedToComposite, R4EUIConstants.ADD_LABEL, SWT.NONE);
fAssignedToButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
fAssignedToButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
((R4EUIReviewItem) fProperties.getElement()).addAssignees(UIUtils.getAssignParticipants());
refresh();
R4EUIModelController.getNavigatorView().getTreeViewer().refresh();
}
});
fUnassignedFromButton = widgetFactory.createButton(fAssignedToComposite, R4EUIConstants.REMOVE_LABEL, SWT.NONE);
fUnassignedFromButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
fUnassignedFromButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event aEvent) {
((R4EUIReviewItem) fProperties.getElement()).removeAssignees(UIUtils.getUnassignParticipants(fProperties.getElement()));
refresh();
R4EUIModelController.getNavigatorView().getTreeViewer().refresh();
}
});
final CLabel assignedToLabel = widgetFactory.createCLabel(composite, R4EUIConstants.ASSIGNED_TO_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fAssignedToComposite, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fAssignedToComposite, 0, SWT.CENTER);
assignedToLabel.setToolTipText(R4EUIConstants.ASSIGNED_TO_TOOLTIP);
assignedToLabel.setLayoutData(data);
}
/**
* Method refresh.
*
* @see org.eclipse.ui.views.properties.tabbed.ISection#refresh()
*/
@Override
public void refresh() {
if (null == fProperties) {
return; //R4EUIPostponedContainer (subclass of R4EUIReviewItem) does not have any properties
}
fRefreshInProgress = true;
final R4EItem modelItem = ((R4EUIReviewItem) fProperties.getElement()).getItem();
fAuthorText.setText(modelItem.getAddedById());
if (null != modelItem.getAuthorRep()) {
fAuthorRepText.setText(modelItem.getAuthorRep());
} else {
try {
final R4EParticipant participant = R4EUIModelController.getActiveReview().getParticipant(
modelItem.getAddedById(), false);
if (null != participant && null != participant.getEmail()) {
fAuthorRepText.setText(participant.getEmail());
} else {
fAuthorRepText.setText("");
}
} catch (ResourceHandlingException e) {
R4EUIPlugin.Ftracer.traceWarning("Exception: " + e.toString() + " (" + e.getMessage() + ")");
fAuthorRepText.setText("");
}
}
fProjectIdList.setItems((String[]) modelItem.getProjectURIs().toArray());
fRepositoryText.setText(null != modelItem.getRepositoryRef() ? modelItem.getRepositoryRef() : "");
if (null != modelItem.getSubmitted()) {
final DateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.DEFAULT_DATE_FORMAT);
fDateSubmitted.setText(dateFormat.format(modelItem.getSubmitted()));
} else {
fDateSubmitted.setText("");
}
if (null != modelItem.getDescription()) {
fDescriptionText.setText(modelItem.getDescription());
} else {
fDescriptionText.setText("");
}
final EList<String> assignedParticipants = modelItem.getAssignedTo();
fAssignedToText.setText(UIUtils.formatAssignedParticipants(assignedParticipants));
setEnabledFields();
fRefreshInProgress = false;
}
/**
* Method setEnabledFields.
*/
@Override
protected void setEnabledFields() {
if (R4EUIModelController.isJobInProgress()
|| fProperties.getElement().isReadOnly()
|| null == R4EUIModelController.getActiveReview()
|| ((R4EReviewState) R4EUIModelController.getActiveReview().getReview().getState()).getState().equals(
R4EReviewPhase.R4E_REVIEW_PHASE_COMPLETED) || !fProperties.getElement().isEnabled()) {
fAuthorText.setForeground(UIUtils.DISABLED_FONT_COLOR);
fAuthorRepText.setForeground(UIUtils.DISABLED_FONT_COLOR);
fRepositoryText.setForeground(UIUtils.DISABLED_FONT_COLOR);
fDateSubmitted.setForeground(UIUtils.DISABLED_FONT_COLOR);
fProjectIdList.setEnabled(false);
fDescriptionText.setForeground(UIUtils.DISABLED_FONT_COLOR);
fDescriptionText.setEditable(false);
fAssignedToText.setForeground(UIUtils.DISABLED_FONT_COLOR);
fAssignedToButton.setEnabled(false);
fUnassignedFromButton.setEnabled(false);
} else {
fAuthorText.setForeground(UIUtils.ENABLED_FONT_COLOR);
fAuthorRepText.setForeground(UIUtils.ENABLED_FONT_COLOR);
fRepositoryText.setForeground(UIUtils.ENABLED_FONT_COLOR);
fDateSubmitted.setForeground(UIUtils.ENABLED_FONT_COLOR);
fProjectIdList.setEnabled(true);
fDescriptionText.setForeground(UIUtils.ENABLED_FONT_COLOR);
fDescriptionText.setEditable(true);
fAssignedToText.setForeground(UIUtils.ENABLED_FONT_COLOR);
fAssignedToButton.setEnabled(true);
if (fAssignedToText.getText().length() > 0) {
fUnassignedFromButton.setEnabled(true);
} else {
fUnassignedFromButton.setEnabled(false);
}
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
f14ca9805a392585d849b22b478057bee0aba894 | 6c0817a8255cff24aca92df8465573eb58dc77f3 | /src/main/java/MainGate.java | d6bf461dc1d5d589a18c3492220705b9459b5c4a | [] | no_license | dnguyen2107/SampleActiviti | 66e8b84eb4b7e385fb88696fec5c4dd0182678db | 2c983dcb04d194da5d5c055a22f1cea347d34b7b | refs/heads/master | 2021-01-01T15:51:12.140561 | 2015-02-08T09:53:31 | 2015-02-08T09:53:31 | 30,486,797 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,959 | java | import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
public class MainGate {
public static void main(String[] args) {
// START--load process definition to engine
ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
RepositoryService repositoryService = processEngine
.getRepositoryService();
repositoryService.createDeployment()
.addClasspathResource("diagrams/TicketRequest.bpmn20.xml")
.deploy();
System.out.println("Number of process definitions: "
+ repositoryService.createProcessDefinitionQuery().count());
// END--load process definition to engine
System.out.println("-------------------------------------------------");
// submit and approve
MainGate.submitAndApprove(processEngine);
System.out.println("-------------------------------------------------");
// submit and reject
MainGate.submitAndReject(processEngine);
}
private static void submitAndApprove(ProcessEngine processEngine) {
// create ticket for approval
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("ticketId", "POS001");
variables.put("assigneeName", "Pig Pig");
// start the task
RuntimeService runtimeService = processEngine.getRuntimeService();
ProcessInstance processInstance = runtimeService
.startProcessInstanceByKey("ticketRequest", variables);
// list pending tasks for this process
TaskService taskService = processEngine.getTaskService();
List<Task> tasks = taskService.createTaskQuery()
.taskCandidateGroup("management").list();
for (Task task : tasks) {
System.out.println("Task available: " + task.getName());
}
Task task = tasks.get(0);
System.out.println("Task Description: " + task.getDescription());
Map<String, Object> taskVariables = new HashMap<String, Object>();
taskVariables.put("ticketApproved", "true");
taskVariables.put("managerMotivation", "Qualified poster!");
taskService.complete(task.getId(), taskVariables);
// should be NO pending task
System.out.println("Task available: "
+ taskService.createTaskQuery()
.taskCandidateGroup("management").list().size());
}
private static void submitAndReject(ProcessEngine processEngine) {
// create ticket for approval
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("ticketId", "POS002");
variables.put("assigneeName", "Yo Yo");
// start the task
RuntimeService runtimeService = processEngine.getRuntimeService();
ProcessInstance processInstance = runtimeService
.startProcessInstanceByKey("ticketRequest", variables);
// list pending tasks for this process
TaskService taskService = processEngine.getTaskService();
List<Task> tasks = taskService.createTaskQuery()
.taskCandidateGroup("management").list();
for (Task task : tasks) {
System.out.println("Task available: " + task.getName());
}
Task task = tasks.get(0);
System.out.println("Task Description: " + task.getDescription());
Map<String, Object> taskVariables = new HashMap<String, Object>();
taskVariables.put("ticketApproved", "false");
taskVariables.put("managerMotivation", "Not qualified poster!");
taskService.complete(task.getId(), taskVariables);
// list out pending task
System.out.println("Task available: "
+ taskService.createTaskQuery().processVariableValueEquals("ticketId", "POS002").list().get(0).getName());
System.out.println("Task description: "
+ taskService.createTaskQuery().processVariableValueEquals("ticketId", "POS002").list().get(0).getDescription());
}
}
| [
"nguyenhd2107@gmail.com"
] | nguyenhd2107@gmail.com |
64413db71be86d190bc306764bc2b0d016080a84 | c50eea77ebfcb8dcea1dc8cb462bcc4ec76306ee | /src/test/java/com/SeleniumWeb/SeleniumWeb/XpathAxes.java | 0f65d7796f571043e1165f6f937043d75b01bf35 | [] | no_license | Deva88/Selenium-Concepts | cd7304be9d68d41bddd713ab3051513c0abbc8fe | a1a9035df7f5a13edff154b10fdb4ed1c46ad213 | refs/heads/master | 2023-07-22T13:12:46.850772 | 2021-09-09T11:36:52 | 2021-09-09T11:36:52 | 404,694,203 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,144 | java | package com.SeleniumWeb.SeleniumWeb;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class XpathAxes {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","A:/Automation/Selenium/SeleniumWeb/SeleniumWeb/Driver/Chromedriver/chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://money.rediff.com/gainers/bse/daily/groupa");
//self - Selects the current node
String textSelf=driver.findElement(By.xpath("//a[contains(text(),'India Tourism De')]/self::a")).getText();
System.out.println("Self Element :- " +textSelf);
//parent - Select the parents of the current node (always one)
String textParent=driver.findElement(By.xpath("//a[contains(text(),'India Tourism De')]/parent::td")).getText();
System.out.println("Parent Elements :- " +textParent);
//childs - Select all children of the current node (one or many)
List<WebElement> childs=driver.findElements(By.xpath("//a[contains(text(),'India Tourism De')]/ancestor::tr/child::td"));
System.out.println("Number of Childs Elements:- "+childs.size());
//Ancestor -Select all Ancestor (parents , grandparents etc)
String textAncestor=driver.findElement(By.xpath("//a[contains(text(),'India Tourism De')]/ancestor::tr")).getText();
System.out.println("Ancestor Elements :- " +textAncestor);
//Descendant - Selects all descendants (children, grandchildren. etc) of the current nodes
List<WebElement> textDescendant=driver.findElements(By.xpath("//a[contains(text(),'India Tourism De')]/ancestor::tr/descendant::*"));
System.out.println("Number of Descendant Nodes :- "+textDescendant.size());
//Following - Selects everything in the documents after the closing tag of the current node
List<WebElement> textFollowing=driver.findElements(By.xpath("//a[contains(text(),'India Tourism De')]/ancestor::tr/following::tr"));
System.out.println("Number of Following Nodes :- "+textFollowing.size());
//Following-sibling - Selects all sibling after the current node
List<WebElement> textFollowingSibling=driver.findElements(By.xpath("//a[contains(text(),'India Tourism De')]/ancestor::tr/following-sibling::tr"));
System.out.println("Number of Following-sibling Nodes :- "+textFollowingSibling.size());
//Preceding - Select all nodes that appear before the current node in the document
List<WebElement> textPreceding=driver.findElements(By.xpath("//a[contains(text(),'India Tourism De')]/ancestor::tr/preceding::tr"));
System.out.println("Number of Preceding Nodes :- "+textPreceding.size());
//Preceding-sibling - Select all Sibling before the current node
List<WebElement> textPrecedingSibling=driver.findElements(By.xpath("//a[contains(text(),'India Tourism De')]/ancestor::tr/preceding-sibling::tr"));
System.out.println("Number of Preceding-sibling Nodes :- "+textPrecedingSibling.size());
driver.close();
}
}
| [
"devendra.raj.sdm@gmail.com"
] | devendra.raj.sdm@gmail.com |
b66ef6daf5bc5f2690370407b031d9003da68005 | 42bdba3edc53ca6a17c751f281bbb9d0ebed5fc4 | /java-review/src/main/java/com/john/designpattern/filter/OrCriteria.java | a62bcb997dfbb02202e7775418e30f8c742d6783 | [] | no_license | git-john/showmecode | 39e4b3d0a3ee9fecf8fd68368120068365faeee1 | dab2625c90b58081f1ae04cc39435696a7bf6cd4 | refs/heads/master | 2022-11-10T23:04:01.472792 | 2019-09-23T09:49:38 | 2019-09-23T09:49:38 | 177,059,163 | 0 | 0 | null | 2022-10-12T20:27:08 | 2019-03-22T02:38:21 | HTML | UTF-8 | Java | false | false | 766 | java | package com.john.designpattern.filter;
import java.util.List;
public class OrCriteria implements Criteria {
private Criteria criteria;
private Criteria otherCriteria;
public OrCriteria(Criteria criteria, Criteria otherCriteria) {
this.criteria = criteria;
this.otherCriteria = otherCriteria;
}
public List<Person> meetCriteria(List<Person> persons) {
List<Person> firstCriteriaItems = criteria.meetCriteria(persons);
List<Person> otherCriteriaItems = otherCriteria.meetCriteria(persons);
for (Person person : otherCriteriaItems) {
if(!firstCriteriaItems.contains(person)){
firstCriteriaItems.add(person);
}
}
return firstCriteriaItems;
}
}
| [
"kangqiang999@163.com"
] | kangqiang999@163.com |
81b118d493b83e5e13260328ae5e950747cb9e42 | fdf51b3634c2f432a9a2026faa3fbe3aaf00d58e | /xfl-jugg/src/main/java/me/xfl/jugg/util/CollectionUtils.java | cfa476e508062f7fcf1d6d856b002a26e1166f3f | [] | no_license | hanpang8983/xfl_blog | 4abfdc00c93f0401f957c46a93b24ef04cfcab40 | fd50f54d3dc0dacdd1198a8d1930e26ce78ec650 | refs/heads/master | 2021-01-22T12:45:46.990741 | 2012-10-18T02:26:25 | 2012-10-18T02:26:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,011 | java | package me.xfl.jugg.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.json.JSONArray;
/**
* Collection utilities.
*
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.7, Jan 6, 2012
*/
public final class CollectionUtils {
/**
* Private default constructor.
*/
private CollectionUtils() {
}
/**
* Gets a list of integers(size specified by the given size) between the
* specified start(inclusion) and end(inclusion) randomly.
*
* @param start
* the specified start
* @param end
* the specified end
* @param size
* the given size
* @return a list of integers
*/
public static List<Integer> getRandomIntegers(final int start, final int end, final int size) {
if (size > (end - start + 1)) {
throw new IllegalArgumentException("The specified size more then (end - start + 1)!");
}
final List<Integer> integers = genIntegers(start, end);
final List<Integer> ret = new ArrayList<Integer>();
int remainsSize;
int index;
while (ret.size() < size) {
remainsSize = integers.size();
index = (int) (Math.random() * (remainsSize - 1));
final Integer i = integers.get(index);
ret.add(i);
integers.remove(i);
}
return ret;
}
/**
* Generates a list of integers from the specified start(inclusion) to the
* specified end(inclusion).
*
* @param start
* the specified start
* @param end
* the specified end
* @return a list of integers
*/
public static List<Integer> genIntegers(final int start, final int end) {
final List<Integer> ret = new ArrayList<Integer>();
for (int i = 0; i <= end; i++) {
ret.add(i + start);
}
return ret;
}
/**
* Converts the specified array to a set.
*
* @param <T>
* the type of elements maintained by the specified array
* @param array
* the specified array
* @return a hash set
*/
public static <T> Set<T> arrayToSet(final T[] array) {
if (null == array) {
return Collections.emptySet();
}
final Set<T> ret = new HashSet<T>();
for (int i = 0; i < array.length; i++) {
final T object = array[i];
ret.add(object);
}
return ret;
}
/**
* Converts the specified {@link List list} to a {@link JSONArray JSON
* array}.
*
* @param <T>
* the type of elements maintained by the specified list
* @param list
* the specified list
* @return a {@link JSONArray JSON array}
*/
public static <T> JSONArray listToJSONArray(final List<T> list) {
final JSONArray ret = new JSONArray();
if (null == list) {
return ret;
}
for (final T object : list) {
ret.put(object);
}
return ret;
}
/**
* Converts the specified {@link JSONArray JSON array} to a {@link List
* list}.
*
* @param <T>
* the type of elements maintained by the specified json array
* @param jsonArray
* the specified json array
* @return an {@link ArrayList array list}
*/
@SuppressWarnings("unchecked")
public static <T> Set<T> jsonArrayToSet(final JSONArray jsonArray) {
if (null == jsonArray) {
return Collections.emptySet();
}
final Set<T> ret = new HashSet<T>();
for (int i = 0; i < jsonArray.length(); i++) {
ret.add((T) jsonArray.opt(i));
}
return ret;
}
/**
* Converts the specified {@link JSONArray JSON array} to a {@link List
* list}.
*
* @param <T>
* the type of elements maintained by the specified json array
* @param jsonArray
* the specified json array
* @return an {@link ArrayList array list}
*/
@SuppressWarnings("unchecked")
public static <T> List<T> jsonArrayToList(final JSONArray jsonArray) {
if (null == jsonArray) {
return Collections.emptyList();
}
final List<T> ret = new ArrayList<T>();
for (int i = 0; i < jsonArray.length(); i++) {
ret.add((T) jsonArray.opt(i));
}
return ret;
}
/**
* Converts the specified {@link JSONArray JSON array} to an array.
*
* @param <T>
* the type of elements maintained by the specified json array
* @param jsonArray
* the specified json array
* @param newType
* the class of the copy to be returned
* @return an array
*/
@SuppressWarnings("unchecked")
public static <T> T[] jsonArrayToArray(final JSONArray jsonArray, final Class<? extends T[]> newType) {
if (null == jsonArray) {
return (T[]) new Object[] {};
}
final int newLength = jsonArray.length();
final Object[] original = new Object[newLength];
for (int i = 0; i < newLength; i++) {
original[i] = jsonArray.opt(i);
}
return Arrays.copyOf(original, newLength, newType);
}
} | [
"pumpkinjugg@gmail.com"
] | pumpkinjugg@gmail.com |
e91c1c81deb2c2f1a4a03a0d22941d3ad6af4881 | e2f47a54a2897aeb9c6986fc9c1620447862d5bc | /base/src/main/java/com/nucarf/base/utils/UriUtils.java | 21ffe6bd2a285461eb3276d745dd5caf1defa59f | [] | no_license | gocavschamp/livedemo | f488cd9210d050a49ed9750945742b5722d363dc | 6922b6bba453d25e7043908757ef1c16a288fbc5 | refs/heads/master | 2023-06-22T14:36:55.558189 | 2021-03-07T12:27:13 | 2021-03-07T12:27:13 | 326,583,689 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,088 | java | package com.nucarf.base.utils;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import androidx.annotation.RequiresApi;
public class UriUtils {
public static String getPicturePathFromUri(Context context, Uri uri) {
int sdkVersion = Build.VERSION.SDK_INT;
if (sdkVersion >= 19) {
return getPicturePathFromUriAboveApi19(context, uri);
} else {
return getPicturePathFromUriBelowAPI19(context, uri);
}
}
public static Bitmap compressPicture(String imgPath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgPath, options);
options.inSampleSize = calculateInSampleSize(options, 100, 100);
options.inJustDecodeBounds = false;
Bitmap afterCompressBm = BitmapFactory.decodeFile(imgPath, options);
return afterCompressBm;
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private static String getPicturePathFromUriBelowAPI19(Context context, Uri uri) {
return getDataColumn(context, uri, null, null);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private static String getPicturePathFromUriAboveApi19(Context context, Uri uri) {
String filePath = null;
if (DocumentsContract.isDocumentUri(context, uri)) {
String documentId = DocumentsContract.getDocumentId(uri);
if (isMediaDocument(uri)) {
String id = documentId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = {id};
filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
} else if (isDownloadsDocument(uri)) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
filePath = getDataColumn(context, contentUri, null, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
filePath = getDataColumn(context, uri, null, null);
} else if ("file".equals(uri.getScheme())) {
filePath = uri.getPath();
}
return filePath;
}
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
String path = null;
String[] projection = new String[]{MediaStore.Images.Media.DATA};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
path = cursor.getString(columnIndex);
}
} catch (Exception e) {
if (cursor != null) {
cursor.close();
}
}
return path;
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
}
| [
"yuwenming@nucarf.com"
] | yuwenming@nucarf.com |
eced48f99ad74a71e6b5c0c678f8a4c653b20d8d | 0fae65e32b3decd3af2e1a32f1b89bff7f95cf52 | /pkix/src/main/java/org/bouncycastle/cert/crmf/CertificateResponse.java | 4aeb8d2400e47938546932b8cf1e85777b4ce97f | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] | permissive | prashanthbn/bc-java | 4d4c45f376650fbf65693750ca9dee6e9b360d1d | d52d2be9799a9f59984dcd8a71faa618bd9e80e3 | refs/heads/master | 2022-11-22T03:49:02.445899 | 2022-11-09T00:05:45 | 2022-11-09T00:05:45 | 195,117,181 | 0 | 0 | NOASSERTION | 2019-07-03T19:44:21 | 2019-07-03T19:44:20 | null | UTF-8 | Java | false | false | 3,825 | java | package org.bouncycastle.cert.crmf;
import java.util.Collection;
import java.util.Iterator;
import org.bouncycastle.asn1.bc.BCObjectIdentifiers;
import org.bouncycastle.asn1.cmp.CMPCertificate;
import org.bouncycastle.asn1.cmp.CertResponse;
import org.bouncycastle.asn1.cmp.CertifiedKeyPair;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.Recipient;
import org.bouncycastle.cms.RecipientInformation;
import org.bouncycastle.cms.RecipientInformationStore;
import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
/**
* High level wrapper for the CertResponse CRMF structure.
*/
public class CertificateResponse
{
private final CertResponse certResponse;
public CertificateResponse(CertResponse certResponse)
{
this.certResponse = certResponse;
}
/**
* Return true if the response contains an encrypted certificate.
*
* @return true if certificate in response encrypted, false otherwise.
*/
public boolean hasEncryptecCertificate()
{
return certResponse.getCertifiedKeyPair().getCertOrEncCert().hasEncryptedCertificate();
}
/**
* Return a CMSEnvelopedData representing the encrypted certificate contained in the response.
*
* @return a CMEEnvelopedData if an encrypted certificate is present.
* @throws IllegalStateException if no encrypted certificate is present, or there is an issue with the enveloped data.
*/
public CMSEnvelopedData getEncryptedCertificate()
throws CMSException
{
if (!hasEncryptecCertificate())
{
throw new IllegalStateException("encrypted certificate asked for, none found");
}
CertifiedKeyPair receivedKeyPair = certResponse.getCertifiedKeyPair();
CMSEnvelopedData envelopedData = new CMSEnvelopedData(
new ContentInfo(PKCSObjectIdentifiers.envelopedData, receivedKeyPair.getCertOrEncCert().getEncryptedCert().getValue()));
if (envelopedData.getRecipientInfos().size() != 1)
{
throw new IllegalStateException("data encrypted for more than one recipient");
}
return envelopedData;
}
/**
* Return the CMPCertificate representing the plaintext certificate in the response.
*
* @return a CMPCertificate if a plaintext certificate is present.
* @throws IllegalStateException if no plaintext certificate is present.
*/
public CMPCertificate getCertificate(Recipient recipient)
throws CMSException
{
CMSEnvelopedData encryptedCert = getEncryptedCertificate();
RecipientInformationStore recipients = encryptedCert.getRecipientInfos();
Collection c = recipients.getRecipients();
RecipientInformation recInfo = (RecipientInformation)c.iterator().next();
return CMPCertificate.getInstance(recInfo.getContent(recipient));
}
/**
* Return the CMPCertificate representing the plaintext certificate in the response.
*
* @return a CMPCertificate if a plaintext certificate is present.
* @throws IllegalStateException if no plaintext certificate is present.
*/
public CMPCertificate getCertificate()
throws CMSException
{
if (hasEncryptecCertificate())
{
throw new IllegalStateException("plaintext certificate asked for, none found");
}
return certResponse.getCertifiedKeyPair().getCertOrEncCert().getCertificate();
}
/**
* Return this object's underlying ASN.1 structure.
*
* @return a CertResponse
*/
public CertResponse toASN1Structure()
{
return certResponse;
}
}
| [
"david.hook@keyfactor.com"
] | david.hook@keyfactor.com |
c8f9a93809e62e8bbd66b68e171cb5188a17514d | 6a1bb1647745a4a4c6ca17acff37867b1e4224f9 | /server/WebProject/src/main/java/com/afd/member/community/Itevent.java | 2463379ed88806586825a4a447974a679e0a7e65 | [] | no_license | ByunSoYun/backup | ffaecc818920af3b5e5a88d99b00ef23f12ce525 | 1ebf8c7fb292a2350a5e371ce203e4e38925f0e5 | refs/heads/main | 2023-07-03T23:25:55.966761 | 2021-08-11T00:12:11 | 2021-08-11T00:12:11 | 376,705,035 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,316 | java | package com.afd.member.community;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
*@author 3조
*
* 게시글의 데이터를 불러오고 검색,페이징을 위한 데이터들을 생성하고 itevent.jsp를 불러오는 클래스
*
* */
@WebServlet("/main/member/community/itevent.do")
public class Itevent extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPostGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPostGet(req, resp);
}
private void doPostGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//list.do
//1. 목록보기(게시판의 시작 페이지 역할)
// - select ..
//2. 검색 결과 보기(검색 버튼 눌러서 호출)
// - select where..
String column = req.getParameter("column");
String search = req.getParameter("search");
String orderRegdate = req.getParameter("orderRegdate");
String orderRecommendCount = req.getParameter("orderRecommendCount");
String orderComment = req.getParameter("orderComment");
String orderReadCount = req.getParameter("orderReadCount");
String isSearch = "n";
//System.out.println("column"+ column);
//System.out.println("search"+ search);
if(column != null && search != null && !column.equals("") && !search.equals("")) {
isSearch = "y";
}
HashMap<String, String> map = new HashMap<String,String>();
map.put("column", column);
map.put("search", search);
map.put("isSearch", isSearch);
map.put("orderRegdate", orderRegdate);
map.put("orderRecommendCount", orderRecommendCount);
map.put("orderComment", orderComment);
map.put("orderReadCount", orderReadCount);
//카테고리별로
//페이징 처리
// -> 보고 싶은 페이지를 정하기 위한 처리
int nowPage = 0; //현재 페이지 번호
int totalCount = 0; //총 게시물 수
int pageSize = 10; //한 페이지당 출력할 게시물 수
int totalPage = 0; //총 페이지 수
int begin = 0; //가져올 게시물 시작 위치
int end = 0; //가져올 게시물 끝 위치
int n = 0; //페이지바 제작
int loop = 0; //페이지바 제작
int blockSize = 10; //페이지바 제작
//list.do > list.do?page=1
//list.do?page=3
String page = req.getParameter("page");
if (page == null || page.equals("")) {
nowPage = 1;
} else {
nowPage = Integer.parseInt(page);
}
//nowPage > 지금 보게될 페이지 번호
//1page -> where rnum between 1 and 10
//2page -> where rnum between 11 and 20
//3page -> where rnum between 21 and 30
begin = ((nowPage - 1) * pageSize) + 1;
end = begin + pageSize - 1;
map.put("begin", begin + "");
map.put("end", end + "");
CommunityDAO dao = new CommunityDAO();
//총 게시물 수 알아내기
totalCount = dao.getIteventTotalCount(map);
//System.out.println(totalCount);
//총 페이지 수 알아내기
//393 / 10 = 39.3 > 40
totalPage = (int)Math.ceil((double)totalCount / pageSize);
//System.out.println(totalPage);
String pagebar = "<nav>\r\n"
+ " <ul class=\"pagination\">";
// for (int i=1; i<=totalPage; i++) {
// if (i == nowPage) {
// pagebar += String.format(" <a href='#!' style='color:tomato;'>%d</a>;", i, i);
// } else {
// pagebar += String.format(" <a href='/myapp/board/list.do?page=%d'>%d</a>", i, i);
// }
// }
loop = 1;//while 루프 변수
n = ((nowPage - 1) / blockSize) * blockSize + 1;//출력되는 페이지 번호
//이전 10 페이지
if (n == 1) {
pagebar += String.format(" <li class='disabled'><a href='#!' aria-label='Previous'><span aria-hidden='true'>«</span></a></li> ");
}else if (n != 1) {
if (map.get("isSearch").equals("y"))
pagebar += pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&column=%s&search=%s&isSearch=%s' aria-label='Previous'> <span aria-hidden='true'>«</span></a></li> ", n - 1, column, search, isSearch);
} else if (map.get("isSearch").equals("n")) {
if (map.get("orderRegdate") != null && map.get("orderRegdate").equals("regdate")) {
pagebar += pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderRegdate=regdate' aria-label='Previous'> <span aria-hidden='true'>«</span></a></li> ", n - 1);
} else if (map.get("orderRecommendCount") != null && map.get("orderRecommendCount").equals("recommendCount")) {
pagebar += pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderRecommendCount=recommendCount' aria-label='Previous'> <span aria-hidden='true'>«</span></a></li> ", n - 1);
} else if (map.get("orderComment") != null && map.get("orderComment").equals("ccnt")) {
pagebar += pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderComment=ccnt' aria-label='Previous'> <span aria-hidden='true'>«</span></a></li> ", n - 1);
} else if (map.get("orderReadCount") != null && map.get("orderReadCount").equals("readCount")) {
pagebar += pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderReadCount=readCount' aria-label='Previous'> <span aria-hidden='true'>«</span></a></li> ", n - 1);
} else if (map.get("orderRegdate") == null && map.get("orderRecommendCount") == null && map.get("orderComment") == null && map.get("orderReadCount") == null) {
pagebar += pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d' aria-label='Previous'> <span aria-hidden='true'>«</span></a></li> ", n - 1);
}
}
//페이지 링크
// while(!(loop > blockSize || n > totalPage)) {
// if (n == nowPage) {
// pagebar += String.format(" <a href='#!' style='color:tomato;'>%d</a>", n, n);
// } else {
// pagebar += String.format(" <a href='/myapp/board/list.do?page=%d'>%d</a>", n, n);
// }
// loop++;
// n++;
//
// };
if (totalPage == 0) {
pagebar += "<li class='active'><a href='#!'>1</a></li>";
}
while(!(loop > blockSize || n > totalPage)) {
if (n == nowPage) {
pagebar += String.format("<li class='active'><a href='#!'>%d</a></li>", n);
} else if (n != nowPage) {
if (map.get("isSearch").equals("y")) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderRegdate=regdate&column=%s&search=%s&isSearch=%s'>%d</a></li> ", n, column, search, isSearch, n);
} else if (map.get("isSearch").equals("n")) {
if (map.get("orderRegdate") != null && map.get("orderRegdate").equals("regdate")) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderRegdate=regdate'>%d</a></li> ", n, n);
} else if (map.get("orderRecommendCount") != null && map.get("orderRecommendCount").equals("recommendCount")) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderRecommendCount=recommendCount'>%d</a></li> ", n, n);
} else if (map.get("orderComment") != null && map.get("orderComment").equals("ccnt")) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderComment=ccnt'>%d</a></li> ", n, n);
} else if (map.get("orderReadCount") != null && map.get("orderReadCount").equals("readCount")) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderReadCount=readCount'>%d</a></li> ", n, n);
} else if (map.get("orderRegdate") == null && map.get("orderRecommendCount") == null && map.get("orderComment") == null && map.get("orderReadCount") == null) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d'>%d</a></li> ", n, n);
}
}
}
loop++;
n++;
};
//다음 10 페이지
// if ( n > totalPage) {
// pagebar += String.format(" <a href='#!'>[다음 %d페이지]</a>", blockSize);
// } else {
// pagebar += String.format(" <a href='/myapp/board/list.do?page=%d'>[다음 %d페이지]</a>", n, blockSize);
// }
if (n > totalPage) {
pagebar += String.format(" <li class='disabled'><a href='#!' aria-label='Next'><span aria-hidden='true'>»</span></a></li> ");
} else if (n != nowPage) {
if (map.get("isSearch").equals("y")) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderRegdate=regdate&column=%s&search=%s&isSearch=%s'>%d</a></li> ", n, column, search, isSearch, n);
} else if (map.get("isSearch").equals("n")) {
if (map.get("orderRegdate") != null && map.get("orderRegdate").equals("regdate")) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderRegdate=regdate'>%d</a></li> ", n, n);
} else if (map.get("orderRecommendCount") != null && map.get("orderRecommendCount").equals("recommendCount")) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderRecommendCount=recommendCount'>%d</a></li> ", n, n);
} else if (map.get("orderComment") != null && map.get("orderComment").equals("ccnt")) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderComment=ccnt'>%d</a></li> ", n, n);
} else if (map.get("orderReadCount") != null && map.get("orderReadCount").equals("readCount")) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d&orderReadCount=readCount'>%d</a></li> ", n, n);
} else if (map.get("orderRegdate") == null && map.get("orderRecommendCount") == null && map.get("orderComment") == null && map.get("orderReadCount") == null) {
pagebar += String.format(" <li><a href='/webproject/main/member/community/itevent.do?page=%d'>%d</a></li> ", n, n);
}
}
}
pagebar += "</ul>\r\n"
+ " </nav>";
//2.
ArrayList<CommunityDTO> list = dao.iteventlist(map);
//2.5
for (CommunityDTO dto : list) {
//날짜 > 가공
String regdate = dto.getRegdate();
regdate = regdate.substring(0, 10);
dto.setRegdate(regdate);
String title = dto.getTitle();
//무조건 글 제목과 내용에 들어있는 <script>태그는 비활성화!!!
//제목이 길면 > 자르기
if (title.length() > 25) {
title = title.substring(0, 25) + "..";
dto.setTitle(title);
}
if (isSearch.equals("y") && column.equals("title")) {
title = title.replace(search, "<span style='color:tomato; background-color:yellow;'>" + search + "</span>");
dto.setTitle(title);
}
}
HttpSession session = req.getSession();
session.setAttribute("read", "n");
//3.
req.setAttribute("list", list);
req.setAttribute("map", map); //*****
req.setAttribute("totalCount", totalCount);
req.setAttribute("totalPage", totalPage);
req.setAttribute("nowPage", nowPage);
req.setAttribute("pagebar", pagebar);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/main/member/community/itevent.jsp");
dispatcher.forward(req, resp);
}
} | [
"soyun22k@hanmail.net"
] | soyun22k@hanmail.net |
8b896f045aa7856f7b288eb16e4ec048636f8f47 | c6f6ff1f98cf7d3681b1994f9aa3b176b679e2c5 | /src/main/java/com/tpofof/conmon/client/HttpClientProvider.java | f4acd4fa8ed30771de7aa96bc98013360c4a4562 | [] | no_license | derek-walker404/charbox-rwst-client | e51d1e9e6e1b257936a9a01146bf3dd789b7eec1 | bcd8cb3596307d3a8881e1f855d651c95583e1f7 | refs/heads/master | 2020-04-09T11:41:14.563340 | 2015-03-12T00:49:41 | 2015-03-12T00:49:41 | 30,953,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 503 | java | package com.tpofof.conmon.client;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import com.google.common.collect.Maps;
public final class HttpClientProvider {
private static final Map<Long, HttpClient> clientMap = Maps.newConcurrentMap();
private HttpClientProvider() { }
public static HttpClient get() {
long tid = Thread.currentThread().getId();
if (!clientMap.containsKey(tid)) {
clientMap.put(tid, new HttpClient());
}
return clientMap.get(tid);
}
}
| [
"david@tpofof.com"
] | david@tpofof.com |
db9580c5f5ab6dbd9cbfa28d72bf1fc909eba65c | 43139d9623d55ee10ae2abd82ecaf1af0450b44d | /app/src/androidTest/java/com/example/greciaguzmn/munchiesuca/ExampleInstrumentedTest.java | 7f3528fc94090168d35ac2c27c7bfbbc2a69104e | [] | no_license | greciagr/Munchies-Uca | 8e0fe5c0f81fd6556e166fa6a53734601563f7ed | 74d48f95828a6d0e80a401b198d7d6049c7e49a1 | refs/heads/master | 2021-01-11T14:25:23.162478 | 2017-02-13T00:08:41 | 2017-02-13T00:08:41 | 81,404,006 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 774 | java | package com.example.greciaguzmn.munchiesuca;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.greciaguzmn.munchiesuca", appContext.getPackageName());
}
}
| [
"greece.ita@gmail.com"
] | greece.ita@gmail.com |
0b6d4fc57a806cf6fec9e7b57ecab95d36fab698 | 09c2139e8457d2be240edc331a75b8df6f8efc81 | /src/codingbat/string1/ExtraFront.java | 218346a45a240ee0ce06a71c283c173ef2dd7ac2 | [] | no_license | golantr/javacore-homework | 9dd7f5ac5985fb25bad5cd83d86989216a366c01 | 29362c725bf6c998b5bc8f5fc764745c557f8911 | refs/heads/master | 2021-05-05T05:03:11.455411 | 2018-01-23T19:25:01 | 2018-01-23T19:25:03 | 118,657,756 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 732 | java | package codingbat.string1;
public class ExtraFront {
/*
Given a string, return a new string made of 3 copies of the first 2 chars of the original string.
The string may be any length. If there are fewer than 2 chars, use whatever is there.
extraFront("Hello") → "HeHeHe"
extraFront("ab") → "ababab"
extraFront("H") → "HHH"
*/
public static String extraFront(String str) {
int stringLen = Math.min(str.length(), 2);
String res = str.substring(0, stringLen);
return res + res + res;
}
public static void main(String[] args) {
System.out.println(extraFront("Hello"));
System.out.println(extraFront("ab"));
System.out.println(extraFront("H"));
}
}
| [
"golant_a@rambler.ru"
] | golant_a@rambler.ru |
fda510a16c99e4c11a2bc9770e84f9bae8596ece | b517899ce48da90f4bd9c855b95be1cc111b7d45 | /src/main/java/com/itsight/signbox/service/serviceImpl/EmailServiceImpl.java | 26bf69b73a8f9f03d5af2e340b7f1638b0fe71d5 | [] | no_license | itsightconsulting/SignBox | dd0883a7337f9764ab5966a5597175a413bc245b | f46ca0d50910c0692667b72564d88ab0cc271660 | refs/heads/master | 2022-12-23T03:26:10.668574 | 2019-12-14T00:59:09 | 2019-12-14T00:59:09 | 216,626,202 | 0 | 0 | null | 2022-12-16T05:09:37 | 2019-10-21T17:28:31 | JavaScript | UTF-8 | Java | false | false | 1,433 | java | package com.itsight.signbox.service.serviceImpl;
import com.itsight.signbox.generic.EmailGeneric;
import com.itsight.signbox.service.EmailService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
@Service
public class EmailServiceImpl extends EmailGeneric implements EmailService {
@Value("${spring.profiles.active}")
private String profile;
@Value("${spring.mail.username}")
private String emitterMail;
private JavaMailSender emailSender;
// private BandejaTemporalRepository bandejaTemporalRepository;
public static final Logger LOGGER = LogManager.getLogger(EmailServiceImpl.class);
public EmailServiceImpl(JavaMailSender emailSender) {
this.emailSender = emailSender;
}
@Override
public void enviarMensajeCredenciales(String asunto, String receptor, String contenido) {
MimeMessagePreparator preparator = mimeMessagePreparator(asunto, receptor, contenido);
try {
emailSender.send(preparator);
} catch (MailException ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
}
| [
"josejch11@gmail.com"
] | josejch11@gmail.com |
27b0a26725a55ade6e6636b7e3374f93857cfcc1 | e0bc89ed1fc97c6d5a7009473582fa2b54e0a1a0 | /app/src/androidTest/java/com/example/paco/preferencias/ExampleInstrumentedTest.java | d6a3b6fd4fc2772a993c5a36047c24f00a07db8f | [] | no_license | Saulmarti/PreferenciasAndroid | 0fbb589e11c3950b5d5d8bbe2c73712b9d61aa5f | 2ee7186b08d28b8fd757ff953ae66126fc0b7e35 | refs/heads/master | 2021-08-10T15:09:12.940279 | 2017-11-12T18:34:56 | 2017-11-12T18:34:56 | 110,458,733 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 762 | java | package com.example.paco.preferencias;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.paco.preferencias", appContext.getPackageName());
}
}
| [
"saulmartivila@gmail.com"
] | saulmartivila@gmail.com |
94bd9959bacfaf259885972ada8e84441fcdc4c9 | dba369d59f22cc19eda000e349a58493fe687150 | /ScoreCalculator/app/src/androidTest/java/com/example/mark_egan/scorecalculator/ExampleInstrumentedTest.java | 1cf2f955c1c092d92bd5a1d0353c96765403388c | [
"MIT"
] | permissive | markegan44/HelloButton | 4dc7b5e4fabd992d1bfdb3556f5f63696239b76c | b77d1e431fbc77fdef671e22bb98f9dc26697d62 | refs/heads/master | 2020-03-28T12:48:06.898326 | 2018-09-26T14:48:09 | 2018-09-26T14:48:09 | 148,335,252 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 758 | java | package com.example.mark_egan.scorecalculator;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.mark_egan.scorecalculator", appContext.getPackageName());
}
}
| [
"43178320+markegan44@users.noreply.github.com"
] | 43178320+markegan44@users.noreply.github.com |
130e96d4eb85b762eb6705a23bc8e5750b1a43da | 3b91ed788572b6d5ac4db1bee814a74560603578 | /com/tencent/mm/plugin/wallet/pay/b$15.java | 51d5ee13601831b0d2431a735f5d41124f4099c3 | [] | no_license | linsir6/WeChat_java | a1deee3035b555fb35a423f367eb5e3e58a17cb0 | 32e52b88c012051100315af6751111bfb6697a29 | refs/heads/master | 2020-05-31T05:40:17.161282 | 2018-08-28T02:07:02 | 2018-08-28T02:07:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,291 | java | package com.tencent.mm.plugin.wallet.pay;
import android.os.Parcelable;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.wallet.pay.a.e.b;
import com.tencent.mm.plugin.wallet.pay.a.e.c;
import com.tencent.mm.plugin.wallet.pay.a.e.d;
import com.tencent.mm.plugin.wallet.pay.a.e.e;
import com.tencent.mm.plugin.wallet.pay.a.e.f;
import com.tencent.mm.plugin.wallet.pay.b.a;
import com.tencent.mm.plugin.wallet_core.model.Orders;
import com.tencent.mm.plugin.wallet_core.model.p;
import com.tencent.mm.pluginsdk.wallet.PayInfo;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.d.i;
import com.tencent.mm.wallet_core.ui.WalletBaseUI;
class b$15 extends a {
final /* synthetic */ b peU;
b$15(b bVar, WalletBaseUI walletBaseUI, i iVar) {
this.peU = bVar;
super(bVar, walletBaseUI, iVar);
}
public final /* synthetic */ CharSequence ui(int i) {
return this.fEY.getString(com.tencent.mm.plugin.wxpay.a.i.wallet_set_password_pay_tips);
}
public final boolean d(int i, int i2, String str, l lVar) {
if (super.d(i, i2, str, lVar)) {
return true;
}
if (!(lVar instanceof f) || i != 0 || i2 != 0) {
return false;
}
f fVar = (f) lVar;
if (fVar.pgm) {
b.o(this.peU).putParcelable("key_orders", fVar.pfb);
}
Parcelable parcelable = fVar.lJN;
if (parcelable != null) {
b.p(this.peU).putParcelable("key_realname_guide_helper", parcelable);
}
this.peU.a(this.fEY, 0, b.q(this.peU));
return true;
}
public final boolean m(Object... objArr) {
l lVar;
p pVar = (p) objArr[0];
Orders orders = (Orders) b.r(this.peU).getParcelable("key_orders");
if (pVar == null || orders == null) {
x.e("MicroMsg.CgiManager", "empty verify or orders");
lVar = null;
} else {
PayInfo payInfo = pVar.mpb;
String str = "";
if (payInfo != null) {
x.i("MicroMsg.CgiManager", "get reqKey from payInfo");
str = payInfo.bOd;
}
if (bi.oW(str)) {
x.i("MicroMsg.CgiManager", "get reqKey from orders");
str = orders.bOd;
}
if (bi.oW(str)) {
x.i("MicroMsg.CgiManager", "empty reqKey!");
lVar = new f(pVar, orders);
} else {
if (payInfo != null) {
x.d("MicroMsg.CgiManager", "reqKey: %s, %s", new Object[]{payInfo.bOd, orders.bOd});
}
x.i("MicroMsg.CgiManager", "verifyreg reqKey: %s", new Object[]{str});
x.i("MicroMsg.CgiManager", "verifyreg go new split cgi");
lVar = str.startsWith("sns_aa_") ? new com.tencent.mm.plugin.wallet.pay.a.e.a(pVar, orders) : str.startsWith("sns_tf_") ? new e(pVar, orders) : str.startsWith("sns_ff_") ? new b(pVar, orders) : str.startsWith("ts_") ? new c(pVar, orders) : str.startsWith("sns_") ? new d(pVar, orders) : new f(pVar, orders);
}
}
if (lVar != null) {
this.uXK.a(lVar, true, 1);
}
return true;
}
}
| [
"707194831@qq.com"
] | 707194831@qq.com |
8a40c6f8bcb5aaabda55b8757693d08350dd547c | 97d89db1d629f86fd0e98b8a87b560257b2ed759 | /safemed-modele/src/main/java/com/bafal/dev/patient/modele/dao/RendezVousDao.java | a859ff7189a92ec151682ae2a2eeb131aad7a981 | [] | no_license | SafeMedTeam/safemed | 49d4bb0147050d5ddc793d71a02fe977c6a51a80 | 86dfbcf314f7c3496a0bdbdfd46169b00f277515 | refs/heads/master | 2021-01-19T11:05:36.109661 | 2017-07-01T20:37:58 | 2017-07-01T20:38:32 | 95,698,621 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 240 | java | package com.bafal.dev.patient.modele.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.bafal.dev.patient.modele.entite.RendezVous;
public interface RendezVousDao extends JpaRepository<RendezVous, Long> {
}
| [
"babacar.fall1@gmail.com"
] | babacar.fall1@gmail.com |
3e26759ea53b08923b2c6db7cc19f87290084a8e | f6809c16a9a73c1b1c8137077771bac392aafca9 | /src/main/java/com/example/botmanager/exception/NoSuchCityException.java | 2413e2ee0993d625fe478c7732659a8587f6fc2c | [] | no_license | abdasik25/TouristBot | 0ab63f14dc7d8fda3e592b216a26ec5174e55957 | 979248a82719a1eaad328d0ca0a2ee1a1ee5d252 | refs/heads/bot | 2022-12-11T10:09:56.415479 | 2019-08-17T17:22:04 | 2019-08-17T17:22:04 | 202,183,805 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 600 | java | package com.example.botmanager.exception;
/**
* @author Alexander Lomat
* @version 0.0.4
* Custom exception class
*/
public class NoSuchCityException extends Exception {
public NoSuchCityException() {
super();
}
public NoSuchCityException(String message) {
super(message);
}
public NoSuchCityException(String message, Throwable cause) {
super(message, cause);
}
@Override
public String getMessage() {
return super.getMessage();
}
@Override
public void printStackTrace() {
super.printStackTrace();
}
}
| [
"abdasik@gmail.com"
] | abdasik@gmail.com |
6deda6a8ce4218e004ea06d21f7a20dc7af14374 | 06ff7e021666fb660f0ef74bea10789e162ea874 | /src/main/java/com/example/QuartsTasksMetro/Device/BuildAllTransaccionTasks.java | 00f29cf87168beefea0b6319f0911849c0046b41 | [] | no_license | Ignaciojeria/M1 | e6e75345df3ff26e6f797b34e60bca17b30e4116 | 0d027b961f6155b0208e2dcc3dddaef96e517e76 | refs/heads/master | 2020-06-27T14:49:52.606748 | 2017-07-12T17:29:00 | 2017-07-12T17:29:00 | 97,034,372 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 314 | java | package com.example.QuartsTasksMetro.Device;
public class BuildAllTransaccionTasks {
public BuildAllTransaccionTasks(){}
public void buildAll(){
for (int i = 0; i < BuildAllConnections.getConnections().length; i++) {
new TransaccionTasks(BuildAllConnections.getConnections()[i]).start();
}
}
}
| [
"Ignaciovl.j@gmail.com"
] | Ignaciovl.j@gmail.com |
6ef37e06cb90389f2de4748104b84f2ebfceab40 | c704ba6ff9ceb443a7e88d36a0341cfadd38092d | /Initium-Odp/src/com/universeprojects/miniup/server/services/ODPKnowledgeService.java | f279c1814b16cb74e099bc4c9eb6b2db00d65692 | [] | no_license | Nixon4Ever/Initium-ODP | 7bac0ead790f7ae822bdb0c7f2486425c2635f79 | 3e20513f0c3ca7a6573078028b29f6ec588afb5e | refs/heads/master | 2021-01-19T22:16:59.146183 | 2017-04-18T22:25:05 | 2017-04-18T22:25:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,998 | java | package com.universeprojects.miniup.server.services;
import java.util.List;
import com.google.appengine.api.datastore.Key;
import com.universeprojects.cacheddatastore.CachedEntity;
import com.universeprojects.miniup.server.ODPDBAccess;
public abstract class ODPKnowledgeService extends Service
{
final protected Key characterKey;
/**
* This will query for all knowledge entities associated with the character.
*
* This method will return null only if the number of knowledge entities is
* 100 or more. In this case, other techniques will need to be used to fetch
* the knowledge tree (like only fetching in parts). This limit is imposed
* for UX purposes.
*
* @return
*/
public ODPKnowledgeService(ODPDBAccess db, Key characterKey)
{
super(db);
this.characterKey = characterKey;
}
/**
* This will query for all knowledge entities associated with the character.
*
* This method will return null only if the number of knowledge entities is
* 100 or more. In this case, other techniques will need to be used to fetch
* the knowledge tree (like only fetching in parts). This limit is imposed
* for UX purposes.
*
* @return
*/
public List<CachedEntity> getAllKnowledge()
{
// TODO Auto-generated method stub
return null;
}
/**
* This method will return the ancestors and any related knowledge entities that apply
* when the given entity is used by the character.
*
* This method currently supports the following entity types: Item
*
* @param entity Currently this must be an Item entity but this will likely be expanded.
* @return
*/
public List<CachedEntity> getKnowledgeEntitiesFor(CachedEntity entity, boolean createIfNoExist)
{
// TODO Auto-generated method stub
return null;
}
/**
* This method will add the given amount of experience points to all the knowledge entities associated with
* the given entity.
*
* This method currently supports the following entity types: Item
*
* @param entity Currently this must be an Item entity but this will likely be expanded.
* @param amount The number of experience points to add to each knowledge entity found associated with
* @return Returns true if the increase was successful, false if it wasn't. It will only return false if the entity is not properly configured for learning (like if there is no itemClass specified on an Item).
*/
public boolean increaseKnowledgeFor(CachedEntity entity, int amount)
{
return false;
}
/**
* Gets the knowledge entity that matches the given entity requirement.
*
*
* @param inventionService
* @param entityRequirement
* @return Null will be returned if no knowledge entity is found. Otherwise, all knowledge entities that match the requirement will be returned.
*/
public List<CachedEntity> fetchKnowledgeEntityByEntityRequirement(ODPInventionService inventionService, CachedEntity entityRequirement)
{
// TODO Auto-generated method stub
return null;
}
}
| [
"nikolasarmstrong@gmail.com"
] | nikolasarmstrong@gmail.com |
93fde26d79c563fc7a89ee3e7eabe8bc3ace760e | 079667715c00dbca84447fbf2937ec2dd2a9b637 | /android/app/src/main/java/com/nocompany/awesomeflutter/MainActivity.java | db292ccde9601518a5de8bcf010c3bd46daacd43 | [] | no_license | hbk671104/flutter-practice | 145904ce73acf3bf728a6f8cd58004de66a954a8 | c815cb883b56ada4d9085e8ce251c06044889a84 | refs/heads/master | 2020-04-07T13:08:58.595810 | 2018-03-07T09:45:04 | 2018-03-07T09:45:04 | 124,213,936 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 374 | java | package com.nocompany.awesomeflutter;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
}
}
| [
"hbk671104@gmail.com"
] | hbk671104@gmail.com |
7d6ae7c821491aa4665158a5abb862cec1f133c5 | 71007018bfae36117fd2f779dbe6e6d7bb9bde9c | /src/main/java/com/magento/test/handler/ReportComparedProductIndexHandler.java | b23909bcdcd76324321161854a209191004b15d8 | [] | no_license | gmai2006/magentotest | 819201760b720a90d55ef853be964651ace125ac | ca67d16d6280ddaefbf57fa1129b6ae7bd80408f | refs/heads/main | 2023-09-03T05:14:27.788984 | 2021-10-17T06:25:09 | 2021-10-17T06:25:09 | 418,040,494 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,481 | java | /**
* %% Copyright (C) 2021 DataScience 9 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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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. #L%
*
* <p>This code is 100% AUTO generated. Please do not modify it DIRECTLY If you need new features or
* function or changes please update the templates then submit the template through our web
* interface.
*/
package com.magento.test.handler;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import java.nio.charset.StandardCharsets;
import com.magento.test.entity.ReportComparedProductIndex;
import com.magento.test.dao.JpaDao;
import com.magento.test.utils.DelimiterParser;
// @Stateless
@Named("ReportComparedProductIndexHandler")
public class ReportComparedProductIndexHandler
extends DelimiterFileHandler<ReportComparedProductIndex> {
@Inject
@Named("DefaultJpaDao")
public ReportComparedProductIndexHandler(final JpaDao dao) {
super(dao);
}
@Override
protected ReportComparedProductIndex parseLine(List<String> headers, List<String> tokens) {
ReportComparedProductIndex record = new ReportComparedProductIndex();
for (int i = 0; i < tokens.size(); i++) {
switch (headers.get(i)) {
case "indexId":
record.setIndexId(java.lang.Long.valueOf((tokens.get(i))));
break;
case "visitorId":
record.setVisitorId(java.lang.Integer.valueOf((tokens.get(i))));
break;
case "customerId":
record.setCustomerId(java.lang.Integer.valueOf((tokens.get(i))));
break;
case "productId":
record.setProductId(java.lang.Integer.valueOf((tokens.get(i))));
break;
case "storeId":
record.setStoreId(java.lang.Integer.valueOf((tokens.get(i))));
break;
case "addedAt":
record.setAddedAt(new java.sql.Timestamp(parseTime(tokens.get(i))));
break;
default:
logger.severe("Unknown col " + headers.get(i));
}
}
return record;
}
}
| [
"gmai2006@gmail.com"
] | gmai2006@gmail.com |
3532dad481d3c0f63dc3e810d5eee3726934fe23 | e57c414efd32a1b64a635ded1f2895c629284add | /src/cap12/CadastroNotas.java | 419fb504a57e79d2feba466f51593bf889649539 | [] | no_license | henriquepin/Java-Programmer | 05c6e44e2de33d4f6b3d3780c561017f79a6ea85 | 0df6e1465bde729b842469f65f3cb8e25d8e2af5 | refs/heads/master | 2020-12-25T05:36:56.166297 | 2016-08-12T11:32:01 | 2016-08-12T11:32:01 | 63,692,461 | 0 | 0 | null | null | null | null | ISO-8859-2 | Java | false | false | 289 | java | package cap12;
public class CadastroNotas {
public static void main(String[] args) {
try{
Nota nota = new Nota("Maria", 11);
}catch(NotainvalidaException e){
System.out.println("Nota inválida = " + e.getMessage());
e.printStackTrace();
}
}
}
| [
"pin.henrique03@yahoo.com"
] | pin.henrique03@yahoo.com |
1cac0282c6783b7c90be0ea948f1fdd272d4861f | abec8a798e8d72da00fb1a1572741a3c88e37a90 | /api/src/test/java/com/example/demo/user/cart/CartItemProductResponseTests.java | dcb0c2a3527bf1cbc74f192b7a70be46cd7bd406 | [] | no_license | whanwells/shopping-portal | a7c09f1c1e88655c154c1757dac0957fa7e61e1c | 9b7f72b17f8f69127ea74e7dab5f30aa3938dbb2 | refs/heads/main | 2023-07-03T20:03:10.951908 | 2021-08-12T21:51:09 | 2021-08-12T21:51:09 | 390,517,997 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 865 | java | package com.example.demo.user.cart;
import com.example.demo.product.Product;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class CartItemProductResponseTests {
@Mock
private Product product;
@Test
void from() {
when(product.getId()).thenReturn(1L);
when(product.getName()).thenReturn("foo");
when(product.getMsrp()).thenReturn(9.99);
var response = CartItemProductResponse.from(product);
assertThat(response.getId()).isEqualTo(1L);
assertThat(response.getName()).isEqualTo("foo");
assertThat(response.getMsrp()).isEqualTo(9.99);
}
}
| [
"whanwells@gmail.com"
] | whanwells@gmail.com |
aeab230818d5a89f83f0fd9dad76cd5438f323d7 | 3e16e84a43450a94f51d3c2f57765fcee7a8fb8a | /src/main/java/patterns/iterator/example1/GeekyStoreCatalog.java | 40d8bf70b775840e4d9e0a14b4cc56a567314486 | [] | no_license | kaitus/designpatternorigins | 6ccd4376114b2d48ee361977a24cfc96211c3dc7 | e43d55e0d2f3209bf02f901ae696eaf0d5f3d30e | refs/heads/master | 2020-05-02T10:02:19.039531 | 2019-07-30T03:29:27 | 2019-07-30T03:29:32 | 177,886,769 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 973 | java | package patterns.iterator.example1;
import patterns.iterator.example1.Interfaces.Catalog;
import patterns.iterator.example1.Interfaces.GeekyStoreIterator;
import java.util.ArrayList;
public class GeekyStoreCatalog implements Catalog {
private ArrayList<Product> catalog;
public GeekyStoreCatalog() {
catalog = new ArrayList<Product>();
addItem("Superman Comic", "The best in town", 12.99);
addItem("Batman Comic", "Okay, but still good", 11.99);
addItem("Start Wars", "Can't live without it", 39.99);
addItem("Jedi T-Shirt", "Gotta have it", 29.99);
}
private void addItem(String name, String description, double price) {
Product product = new Product(name, description, price);
catalog.add(product);
}
// public ArrayList<Product> getCatalog() {
// return catalog;
// }
public GeekyStoreIterator createIterator() {
return new GeekyStoreIterator(catalog);
}
}
| [
"carlos.diaz@ceiba.com.co"
] | carlos.diaz@ceiba.com.co |
472ec2d5e9996ace84b39ee7854598b574947d16 | a7fc38393cd03af88a517247249f4e137acb14ee | /misc/head_first/XCopy.java | edaabcd8b52823188c39d7881253d038750c7106 | [] | no_license | OOGASAN/classwork | c21d9bfdfadad0bcc4e633035fac1bae713c3799 | ad2ab878dea5d6a94c9538285751051010b8a1fd | refs/heads/master | 2020-04-14T15:12:14.822884 | 2010-12-08T03:52:35 | 2010-12-08T03:52:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 268 | java | class XCopy {
public static void main(String[] args) {
int orig = 42;
XCopy x = new XCopy();
int y = x.go(orig);
System.out.println(orig + " " + y);
}
int go(int arg) {
arg = arg * 2;
return arg;
}
}
| [
"sam@custommade.com"
] | sam@custommade.com |
2fa071155d7bcacfa8044380513a36f735e1c54b | 2043a1dc9736dc2ac273b7c23213c26fb64629e9 | /ui/src/main/java/com/stockholders/ui/service/dto/UserDTO.java | 4daa76083adfd3f1c456832a9f0ab4b51cc343ef | [] | no_license | bouluad/hackathon | 79f1904231663f8de957b46ba955686e793964c1 | 92f7d9fc80002f7316c22037f0d14bfa60795e37 | refs/heads/master | 2021-08-23T03:01:55.751560 | 2017-12-02T15:06:45 | 2017-12-02T15:06:45 | 112,801,777 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,646 | java | package com.stockholders.ui.service.dto;
import com.stockholders.ui.config.Constants;
import com.stockholders.ui.domain.Authority;
import com.stockholders.ui.domain.User;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.*;
import java.time.Instant;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A DTO representing a user, with his authorities.
*/
public class UserDTO {
private String id;
@NotBlank
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
private String login;
@Size(max = 50)
private String firstName;
@Size(max = 50)
private String lastName;
@Email
@Size(min = 5, max = 100)
private String email;
@Size(max = 256)
private String imageUrl;
private boolean activated = false;
@Size(min = 2, max = 6)
private String langKey;
private String createdBy;
private Instant createdDate;
private String lastModifiedBy;
private Instant lastModifiedDate;
private Set<String> authorities;
public UserDTO() {
// Empty constructor needed for Jackson.
}
public UserDTO(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.email = user.getEmail();
this.activated = user.getActivated();
this.imageUrl = user.getImageUrl();
this.langKey = user.getLangKey();
this.createdBy = user.getCreatedBy();
this.createdDate = user.getCreatedDate();
this.lastModifiedBy = user.getLastModifiedBy();
this.lastModifiedDate = user.getLastModifiedDate();
this.authorities = user.getAuthorities().stream()
.map(Authority::getName)
.collect(Collectors.toSet());
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Set<String> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<String> authorities) {
this.authorities = authorities;
}
@Override
public String toString() {
return "UserDTO{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated=" + activated +
", langKey='" + langKey + '\'' +
", createdBy=" + createdBy +
", createdDate=" + createdDate +
", lastModifiedBy='" + lastModifiedBy + '\'' +
", lastModifiedDate=" + lastModifiedDate +
", authorities=" + authorities +
"}";
}
}
| [
"ubuntu@docker.dev"
] | ubuntu@docker.dev |
5c3bd74f96cd951fe625cfe7c80f03d4784dcd74 | 45033710ad1ccd451d0fc436ae928aeaee2ba45a | /fixture/src/main/java/au/com/scds/agric/fixture/scenarios/RecreateSimpleObjects.java | 832c69f600f1f3d14f3e4506131eadc6ecf4614c | [
"MIT"
] | permissive | jifffffy/isis-agri | 95ebeddd2a1c5a12762aca640590d5da28d81dc3 | 7563bf328aba3dfebf39a3a86413916276e05a8e | refs/heads/master | 2023-03-22T09:56:02.158095 | 2017-04-19T21:40:07 | 2017-04-19T21:40:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,002 | java | /*
* 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 au.com.scds.agric.fixture.scenarios;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.common.collect.Lists;
import au.com.scds.agric.dom.simple.SimpleObject;
import au.com.scds.agric.fixture.dom.simple.SimpleObjectCreate;
import au.com.scds.agric.fixture.dom.simple.SimpleObjectsTearDown;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.fixturescripts.FixtureScript;
public class RecreateSimpleObjects extends FixtureScript {
public final List<String> NAMES = Collections.unmodifiableList(Arrays.asList(
"Foo", "Bar", "Baz", "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo"));
public RecreateSimpleObjects() {
withDiscoverability(Discoverability.DISCOVERABLE);
}
//region > number (optional input)
private Integer number;
/**
* The number of objects to create, up to 10; optional, defaults to 3.
*/
public Integer getNumber() {
return number;
}
public RecreateSimpleObjects setNumber(final Integer number) {
this.number = number;
return this;
}
//endregion
//region > simpleObjects (output)
private final List<SimpleObject> simpleObjects = Lists.newArrayList();
/**
* The simpleobjects created by this fixture (output).
*/
@Programmatic
public List<SimpleObject> getSimpleObjects() {
return simpleObjects;
}
//endregion
@Override
protected void execute(final ExecutionContext ec) {
// defaults
final int number = defaultParam("number", ec, 3);
// validate
if(number < 0 || number > NAMES.size()) {
throw new IllegalArgumentException(String.format("number must be in range [0,%d)", NAMES.size()));
}
//
// execute
//
ec.executeChild(this, new SimpleObjectsTearDown());
for (int i = 0; i < number; i++) {
final SimpleObjectCreate fs = new SimpleObjectCreate().setName(NAMES.get(i));
ec.executeChild(this, fs.getName(), fs);
simpleObjects.add(fs.getSimpleObject());
}
}
}
| [
"steve.cameron.62@gmail.com"
] | steve.cameron.62@gmail.com |
361a69a5a4b1125d2f02a4c0f91cb4e3441dccef | dbd57b6c19b68e2a92a4d4ab7cfb19981494e84f | /kafka-connect-rest-plugin/src/test/java/com/tm/kafka/connect/rest/util/StringToMapTest.java | e68f9ab8a512797e1c40a5e5c1e0ddccf585bbc4 | [
"Apache-2.0"
] | permissive | rmoff/kafka-connect-rest | 1085567a8995c465adf22d1b4bb13f342ef6db1d | b0f213d3359ea829d596d1c7321b253975ab5ab6 | refs/heads/master | 2020-04-27T17:38:36.238239 | 2019-03-08T12:03:36 | 2019-03-08T12:03:36 | 174,530,179 | 1 | 0 | Apache-2.0 | 2019-03-08T11:59:21 | 2019-03-08T11:59:20 | null | UTF-8 | Java | false | false | 1,567 | java | package com.tm.kafka.connect.rest.util;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class StringToMapTest {
@Test
public void testUpdate() {
Map<String, Object> converted = StringToMap.update("test.foo.bar", "value");
Map<String, Object> level3 = new HashMap<>();
level3.put("bar", "value");
Map<String, Object> level2 = new HashMap<>();
level2.put("foo", level3);
Map<String, Object> expected = new HashMap<>();
expected.put("test", level2);
assertEquals(expected, converted);
}
@Test
public void testExtract() {
Map<String, Object> level3 = new HashMap<>();
level3.put("bar", "value");
Map<String, Object> level2 = new HashMap<>();
level2.put("foo", level3);
Map<String, Object> map = new HashMap<>();
map.put("test", level2);
String extracted = StringToMap.extract("test.foo.bar", map);
assertEquals("value", extracted);
}
@Test
public void testRemove() {
Map<String, Object> level3 = new HashMap<>();
level3.put("bar", "value");
Map<String, Object> level2 = new HashMap<>();
level2.put("foo", level3);
Map<String, Object> map = new HashMap<>();
map.put("test", level2);
StringToMap.remove("test.foo.bar", map);
Map<String, Object> level2Expected = new HashMap<>();
level2Expected.put("foo", new HashMap<>());
Map<String, Object> mapExpected = new HashMap<>();
mapExpected.put("test", level2Expected);
assertEquals(mapExpected, map);
}
}
| [
"Max.Sakharov@ticketmaster.com"
] | Max.Sakharov@ticketmaster.com |
2c0f36a63034f0f80e5b9a8a8903ed5f451571b8 | 1e74c9f68aacc011e65be0998262e364ef7aaa75 | /osa03-Osa03_06.EnsimmainenJaViimeinenArvo/src/main/java/EnsimmainenJaViimeinenArvo.java | 6d3e15d44c4a96361bdcf1a7349e50fcba582dd3 | [] | no_license | Hiirihii/JAVA-MOOC-2019 | 67cab91e2e78167f1f5d6ea0e3f5a82654bd72a0 | 4a1891baea3ef90210b90800cb94191d69419f62 | refs/heads/master | 2020-05-25T09:03:43.103704 | 2019-05-21T13:36:19 | 2019-05-21T13:36:19 | 187,725,074 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 576 | java |
import java.util.ArrayList;
import java.util.Scanner;
public class EnsimmainenJaViimeinenArvo {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
ArrayList<String> lista = new ArrayList<>();
while (true) {
String luettu = lukija.nextLine();
if (luettu.equals("")) {
break;
}
lista.add(luettu);
}
int viimeisin = lista.size() - 1;
System.out.println(lista.get(0));
System.out.println(lista.get(viimeisin));
}
}
| [
"otto.liuhtonen@gmail.com"
] | otto.liuhtonen@gmail.com |
769c1753bdc93c5b0164f850bebf5733e4ced865 | 6b4125b3d69cbc8fc291f93a2025f9f588d160d3 | /tests/com/limegroup/gnutella/MessageRouterImplRefactoringTest.java | fba53d8e24e29e2a37fd7c47cf3b5d62d35e2885 | [] | no_license | mnutt/limewire5-ruby | d1b079785524d10da1b9bbae6fe065d461f7192e | 20fc92ea77921c83069e209bb045b43b481426b4 | refs/heads/master | 2022-02-10T12:20:02.332362 | 2009-09-11T15:47:07 | 2009-09-11T15:47:07 | 89,669 | 2 | 3 | null | 2022-01-27T16:18:46 | 2008-12-12T19:40:01 | Java | UTF-8 | Java | false | false | 7,589 | java | package com.limegroup.gnutella;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.limewire.io.GUID;
import org.limewire.util.BaseTestCase;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.limegroup.gnutella.connection.ConnectionCapabilities;
import com.limegroup.gnutella.connection.RoutedConnection;
import com.limegroup.gnutella.messages.PushRequest;
import com.limegroup.gnutella.search.QueryDispatcher;
import com.limegroup.gnutella.util.MessageTestUtils;
import com.limegroup.gnutella.util.TestConnectionManager;
/**
* Temporary test class to ensure that MessageRouterImpl works as before
* after refactoring. Test cases should be moved to new top level handler
* classes eventually.
*/
public class MessageRouterImplRefactoringTest extends BaseTestCase {
private Mockery context;
// private TestConnectionFactory testConnectionFactory;
private MessageRouterImpl messageRouterImpl;
// private TestConnectionManager connectionManager;
public MessageRouterImplRefactoringTest(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
context = new Mockery();
}
/**
* Helper method to configure the injector and return it. It also sets
*
* Neeeded as each test method needs its own participants.
*/
private Injector createInjectorAndInitialize(Module... modules) {
Injector injector = LimeTestUtils.createInjector(modules);
// testConnectionFactory = injector.getInstance(TestConnectionFactory.class);
messageRouterImpl = (MessageRouterImpl) injector.getInstance(MessageRouter.class);
messageRouterImpl.start();
return injector;
}
/**
* Calls {@link #createInjectorAndInitialize(Module...)} and with a module
* that sets up the TestConnectionManager.
*/
private Injector createDefaultInjector(Module... modules) {
Module m = new AbstractModule() {
@Override
protected void configure() {
bind(ConnectionManager.class).to(TestConnectionManager.class);
}
};
List<Module> list = new ArrayList<Module>();
list.addAll(Arrays.asList(modules));
list.add(m);
Injector injector = createInjectorAndInitialize(list.toArray(new Module[0]));
// connectionManager = (TestConnectionManager)injector.getInstance(ConnectionManager.class);
return injector;
}
/**
* Tests if tcp push requests are correctly handled before and after refactoring.
*/
public void testHandlePushRequestTCP() {
createDefaultInjector();
final PushRequest pushRequest = context.mock(PushRequest.class);
final ReplyHandler senderHandler = context.mock(ReplyHandler.class);
final GUID guid = new GUID ();
context.checking(new Expectations() {{
allowing(pushRequest).getClientGUID();
will(returnValue(guid.bytes()));
one(senderHandler).countDroppedMessage();
}});
context.checking(MessageTestUtils.createDefaultMessageExpectations(pushRequest, PushRequest.class));
// test without installed reply handler
messageRouterImpl.handleMessage(pushRequest, senderHandler);
context.assertIsSatisfied();
final ReplyHandler replyHandler = context.mock(ReplyHandler.class);
context.checking(new Expectations() {{
allowing(replyHandler).isOpen();
will(returnValue(true));
one(replyHandler).handlePushRequest(with(same(pushRequest)), with(same(senderHandler)));
}});
messageRouterImpl.getPushRouteTable().routeReply(guid.bytes(), replyHandler);
// test with installed reply handler
messageRouterImpl.handleMessage(pushRequest, senderHandler);
context.assertIsSatisfied();
}
/**
* Tests if udp/multicast push requests are correctly handled before and after refactoring.
*/
public void testhandlePushRequestUDPMulticast() {
final UDPReplyHandlerCache udpReplyHandlerCache = context.mock(UDPReplyHandlerCache.class);
createDefaultInjector(new AbstractModule() {
@Override
protected void configure() {
bind(UDPReplyHandlerCache.class).toInstance(udpReplyHandlerCache);
}
});
final PushRequest pushRequest = context.mock(PushRequest.class);
final ReplyHandler senderHandler = context.mock(ReplyHandler.class);
final GUID guid = new GUID ();
final InetSocketAddress address = InetSocketAddress.createUnresolved("127.0.0.1", 4545);
context.checking(new Expectations() {{
allowing(pushRequest).getClientGUID();
will(returnValue(guid.bytes()));
one(senderHandler).countDroppedMessage();
allowing(udpReplyHandlerCache).getUDPReplyHandler(with(any(InetSocketAddress.class)));
will(returnValue(senderHandler));
}});
context.checking(MessageTestUtils.createDefaultMessageExpectations(pushRequest, PushRequest.class));
// test without installed reply handler
messageRouterImpl.handleUDPMessage(pushRequest, address);
context.assertIsSatisfied();
// same for multicast
messageRouterImpl.handleMulticastMessage(pushRequest, address);
context.assertIsSatisfied();
final ReplyHandler replyHandler = context.mock(ReplyHandler.class);
context.checking(new Expectations() {{
allowing(replyHandler).isOpen();
will(returnValue(true));
one(replyHandler).handlePushRequest(with(same(pushRequest)), with(same(senderHandler)));
}});
messageRouterImpl.getPushRouteTable().routeReply(guid.bytes(), replyHandler);
// test with installed reply handler
messageRouterImpl.handleUDPMessage(pushRequest, address);
context.assertIsSatisfied();
// same for multicast
messageRouterImpl.handleMulticastMessage(pushRequest, address);
context.assertIsSatisfied();
}
public void testConnectionsAreRemoved() {
final QueryDispatcher queryDispatcher = context.mock(QueryDispatcher.class);
Injector injector = createDefaultInjector(new AbstractModule() {
@Override
protected void configure() {
bind(QueryDispatcher.class).toInstance(queryDispatcher);
}
});
ConnectionManager connectionManager = injector.getInstance(ConnectionManager.class);
final RoutedConnection connection = context.mock(RoutedConnection.class);
final ConnectionCapabilities connectionCapabilities = context.mock(ConnectionCapabilities.class);
context.checking(new Expectations() {{
allowing(connection).getConnectionCapabilities();
will(returnValue(connectionCapabilities));
allowing(connection).getAddress();
will(returnValue("127.0.0.1"));
ignoring(connection);
ignoring(connectionCapabilities);
one(queryDispatcher).removeReplyHandler(with(same(connection)));
}});
connectionManager.remove(connection);
context.assertIsSatisfied();
}
}
| [
"michael@nuttnet.net"
] | michael@nuttnet.net |
c295d3832276e49911a016e154dc4532b29454fc | 79ffde9b150c09f2dfacfa365efe0481246a05aa | /app/src/main/java/br/com/deyvidjlira/bollyfilmes/FilmesAdapter.java | aae612123f6bbea26b2c779a57ce2fa2e50ee7dc | [] | no_license | DeyvidJLira/bolly-filmes | 5f08e27b9790bd4b8c39a03b00ba8880a0113a7b | a229e1f17c02796520d8285ceba48865e28a7b21 | refs/heads/master | 2021-01-02T09:16:19.790738 | 2017-08-03T01:24:25 | 2017-08-03T01:24:25 | 99,176,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,252 | java | package br.com.deyvidjlira.bollyfilmes;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.ArrayList;
import br.com.deyvidjlira.bollyfilmes.data.FilmesContract;
/**
* Created by Deyvid on 14/05/2017.
*/
public class FilmesAdapter extends CursorAdapter {
private final int VIEW_TYPE_DESTAQUE = 0;
private final int VIEW_TYPE_ITEM = 1;
private boolean useFilmeDestaque = false;
public FilmesAdapter(Context context, Cursor cursor) {
super(context, cursor, 0); //O 0 é uma flag que indica o comportamento a ser adotado, 0 é o padrão.
}
public static class ItemFilmeHolder {
ImageView poster;
ImageView capa;
TextView title;
TextView description;
TextView data;
RatingBar rate;
public ItemFilmeHolder(View view) {
poster = (ImageView) view.findViewById(R.id.imageViewPoster);
capa = (ImageView) view.findViewById(R.id.imageViewCapa);
title = (TextView) view.findViewById(R.id.textViewTitle);
description = (TextView) view.findViewById(R.id.textViewDescription);
data = (TextView) view.findViewById(R.id.textViewData);
rate = (RatingBar) view.findViewById(R.id.ratingBarRate);
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int viewType = getItemViewType(cursor.getPosition());
int layoutId = -1;
switch(viewType) {
case VIEW_TYPE_DESTAQUE:
layoutId = R.layout.item_filme_destaque;
break;
case VIEW_TYPE_ITEM:
layoutId = R.layout.item_filme;
break;
}
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
ItemFilmeHolder holder = new ItemFilmeHolder(view);
view.setTag(holder);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ItemFilmeHolder holder = (ItemFilmeHolder) view.getTag();
int viewType = getItemViewType(cursor.getPosition());
int tituloIndex = cursor.getColumnIndex(FilmesContract.FilmeEntry.COLUMN_TITULO);
int descricaoIndex = cursor.getColumnIndex(FilmesContract.FilmeEntry.COLUMN_DESCRICAO);
int dataReleaseIndex = cursor.getColumnIndex(FilmesContract.FilmeEntry.COLUMN_DATA_RELEASE);
int posterIndex = cursor.getColumnIndex(FilmesContract.FilmeEntry.COLUMN_POSTER_PATH);
int capaIndex = cursor.getColumnIndex(FilmesContract.FilmeEntry.COLUMN_CAPA_PATH);
int avaliacaoIndex = cursor.getColumnIndex(FilmesContract.FilmeEntry.COLUMN_AVALIACAO);
switch (viewType) {
case VIEW_TYPE_DESTAQUE:
holder.title.setText(cursor.getString(tituloIndex));
holder.rate.setRating(cursor.getFloat(avaliacaoIndex));
new DownloadImageTask(holder.capa).execute(cursor.getString(capaIndex));
break;
case VIEW_TYPE_ITEM:
holder.title.setText(cursor.getString(tituloIndex));
holder.description.setText(cursor.getString(descricaoIndex));
holder.data.setText(cursor.getString(dataReleaseIndex));
holder.rate.setRating(cursor.getFloat(avaliacaoIndex));
new DownloadImageTask(holder.poster).execute(cursor.getString(posterIndex));
break;
}
}
@Override
public int getItemViewType(int position) {
return (position == 0 && useFilmeDestaque ? VIEW_TYPE_DESTAQUE : VIEW_TYPE_ITEM);
}
@Override
public int getViewTypeCount() {
return 2;
}
public void setUseFilmeDestaque(boolean useFilmeDestaque) {
this.useFilmeDestaque = useFilmeDestaque;
}
} | [
"deyvidjlira@gmail.com"
] | deyvidjlira@gmail.com |
b1c71437d634b87791bb09eac0d34e4364af53a6 | a13ab684732add3bf5c8b1040b558d1340e065af | /java7-src/org/omg/PortableServer/POAPackage/AdapterAlreadyExistsHelper.java | a3982366ab7095a8fead8e280a807c0c8fb8b763 | [] | no_license | Alivop/java-source-code | 554e199a79876343a9922e13ccccae234e9ac722 | f91d660c0d1a1b486d003bb446dc7c792aafd830 | refs/heads/master | 2020-03-30T07:21:13.937364 | 2018-10-25T01:49:39 | 2018-10-25T01:51:38 | 150,934,150 | 5 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,344 | java | package org.omg.PortableServer.POAPackage;
/**
* org/omg/PortableServer/POAPackage/AdapterAlreadyExistsHelper.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from ../../../../src/share/classes/org/omg/PortableServer/poa.idl
* Friday, July 25, 2014 8:50:00 AM PDT
*/
abstract public class AdapterAlreadyExistsHelper
{
private static String _id = "IDL:omg.org/PortableServer/POA/AdapterAlreadyExists:1.0";
public static void insert (org.omg.CORBA.Any a, org.omg.PortableServer.POAPackage.AdapterAlreadyExists that)
{
org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
a.type (type ());
write (out, that);
a.read_value (out.create_input_stream (), type ());
}
public static org.omg.PortableServer.POAPackage.AdapterAlreadyExists extract (org.omg.CORBA.Any a)
{
return read (a.create_input_stream ());
}
private static org.omg.CORBA.TypeCode __typeCode = null;
private static boolean __active = false;
synchronized public static org.omg.CORBA.TypeCode type ()
{
if (__typeCode == null)
{
synchronized (org.omg.CORBA.TypeCode.class)
{
if (__typeCode == null)
{
if (__active)
{
return org.omg.CORBA.ORB.init().create_recursive_tc ( _id );
}
__active = true;
org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0];
org.omg.CORBA.TypeCode _tcOf_members0 = null;
__typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (org.omg.PortableServer.POAPackage.AdapterAlreadyExistsHelper.id (), "AdapterAlreadyExists", _members0);
__active = false;
}
}
}
return __typeCode;
}
public static String id ()
{
return _id;
}
public static org.omg.PortableServer.POAPackage.AdapterAlreadyExists read (org.omg.CORBA.portable.InputStream istream)
{
org.omg.PortableServer.POAPackage.AdapterAlreadyExists value = new org.omg.PortableServer.POAPackage.AdapterAlreadyExists ();
// read and discard the repository ID
istream.read_string ();
return value;
}
public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.PortableServer.POAPackage.AdapterAlreadyExists value)
{
// write the repository ID
ostream.write_string (id ());
}
}
| [
"liulp@zjhjb.com"
] | liulp@zjhjb.com |
43e677c0f891fd40f113be2319dc4714799c4a8a | ab7619cb640580c931b087d85f7f26fa176702e2 | /h2/src/main/org/h2/index/PageDataCursor.java | c29412d1850c98ccf5e9e89e9ed34fcb04a1b222 | [] | no_license | pkouki/icdm2017 | 440da58c66f56a36e98853ff34b14e2c066ed0f7 | e05618c285c43416d7615bf41c812b6dede596bc | refs/heads/master | 2021-01-21T13:29:22.566573 | 2017-11-19T04:29:47 | 2017-11-19T04:29:47 | 102,126,018 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,858 | java | /*
* Copyright 2004-2009 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.sql.SQLException;
import java.util.Iterator;
import org.h2.engine.Session;
import org.h2.message.Message;
import org.h2.result.Row;
import org.h2.result.SearchRow;
/**
* The cursor implementation for the page scan index.
*/
class PageDataCursor implements Cursor {
private PageDataLeaf current;
private int idx;
private final long max;
private Row row;
private final boolean multiVersion;
private final Session session;
private Iterator<Row> delta;
PageDataCursor(Session session, PageDataLeaf current, int idx, long max, boolean multiVersion) {
this.current = current;
this.idx = idx;
this.max = max;
this.multiVersion = multiVersion;
this.session = session;
if (multiVersion) {
delta = current.index.getDelta();
}
}
public Row get() {
return row;
}
public long getKey() {
return row.getKey();
}
public SearchRow getSearchRow() {
return get();
}
public boolean next() throws SQLException {
if (!multiVersion) {
nextRow();
return checkMax();
}
while (true) {
if (delta != null) {
if (!delta.hasNext()) {
delta = null;
row = null;
continue;
}
row = delta.next();
if (!row.isDeleted() || row.getSessionId() == session.getId()) {
continue;
}
} else {
nextRow();
if (row != null && row.getSessionId() != 0 && row.getSessionId() != session.getId()) {
continue;
}
}
break;
}
return checkMax();
}
private boolean checkMax() throws SQLException {
if (row != null) {
if (max != Long.MAX_VALUE) {
long x = current.index.getLong(row, Long.MAX_VALUE);
if (x > max) {
row = null;
return false;
}
}
return true;
}
return false;
}
private void nextRow() throws SQLException {
if (idx >= current.getEntryCount()) {
current = current.getNextPage();
idx = 0;
if (current == null) {
row = null;
return;
}
}
row = current.getRowAt(idx);
idx++;
}
public boolean previous() {
throw Message.throwInternalError();
}
}
| [
"pkouki@umiacs.umd.edu"
] | pkouki@umiacs.umd.edu |
d15f7369617f9696e6568b957f6028a8bc4c3aa2 | 1a8bed788239b5ed784539f820fc0117e5f89ddc | /src/main/java/com/readboy/ssm/appnsh/service/TB_TJFX_DKDKHService.java | a6bc8fcf35161ef5b4202d63a52555b0eac4b74d | [] | no_license | jlf1997/bank_pm | 9cfbc3d63d8d0db782491f31539b102bbb17f043 | ce301773e11d451045bfacd53d0bd762316cc634 | refs/heads/master | 2020-03-29T22:14:05.261212 | 2019-04-29T08:17:06 | 2019-04-29T08:17:06 | 150,410,112 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,210 | java | package com.readboy.ssm.appnsh.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import com.readboy.ssm.appnsh.dto.TB_TJFX_CKDKHDto;
import com.readboy.ssm.appnsh.dto.TB_TJFX_DKDKHDto;
import com.readboy.ssm.appnsh.jpa.JdbcTemplatePageHelper;
import com.readboy.ssm.appnsh.model.TB_TJFX_BLDKKH;
import com.readboy.ssm.appnsh.model.TB_TJFX_DKDKH;
@Service
public class TB_TJFX_DKDKHService {
@Autowired
private OrgService orgService;
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private JdbcTemplatePageHelper jdbcTemplatePageHelper;
public int getCount(String yggh,int khlx) {
String sql = "select * from tb_tjfx_dkdkh where yggh=? and khlx=? ";
List<TB_TJFX_DKDKH> list = jdbcTemplate.query(sql, new Object[] {yggh,khlx}
,new BeanPropertyRowMapper<TB_TJFX_DKDKH>(TB_TJFX_DKDKH.class));
if(list!=null) {
return list.size();
}
return 0;
}
public List<TB_TJFX_DKDKHDto> getTB_TJFX_BLDKKHByYgghAndKHLX(String yggh,Integer khlx){
String sql = "select * from tb_tjfx_dkdkh where yggh=? and khlx=? order by dkye desc ";
List<TB_TJFX_DKDKH> list = jdbcTemplate.query(sql, new Object[] {yggh,khlx}
,new BeanPropertyRowMapper<TB_TJFX_DKDKH>(TB_TJFX_DKDKH.class));
return TB_TJFX_DKDKHDto.copyList(list,orgService);
}
public Map getPages(String yggh, Integer khlx, Integer pageSize, Integer pageIndex) {
// TODO Auto-generated method stub
String sql = "select count(*) from tb_tjfx_dkdkh where yggh=? and khlx=? ";
String sqlPage = "select tb.*,org.ZZJC as jgmc from tb_tjfx_dkdkh tb "
+ "left join hr_bas_organization org on tb.jgdm = org.YWJGDM where yggh=? and khlx=? order by dkye desc ,tb.khmc desc,tb.jgdm desc ";
RowMapper<TB_TJFX_DKDKHDto> rowMap = new BeanPropertyRowMapper<TB_TJFX_DKDKHDto>(TB_TJFX_DKDKHDto.class);
Map map = jdbcTemplatePageHelper.getPageMap(sqlPage,sql, pageIndex, pageSize, rowMap, yggh,khlx);
return map;
}
}
| [
"jlf1997@163.com"
] | jlf1997@163.com |
7ffd5d54ae516cd8fca7f6d65bf42350a9a74357 | 3191170078c3f9e48ac59a7f549b754543bf81cd | /src/behavior/chainofresponsibility/SecurityControl.java | cfe8a67a171af9daf53be58a1f90656ec493bc01 | [] | no_license | PetrFokin/pattern | b4b3b436811627528149e26007a210ac541ef367 | fae42714274dd1f7a4a70fdabc025910fc366983 | refs/heads/master | 2022-09-20T06:24:25.725336 | 2020-06-01T12:24:15 | 2020-06-01T12:26:28 | 268,512,594 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 187 | java | package behavior.chainofresponsibility;
public interface SecurityControl {
void checkCustomer(Customer customer);
SecurityControl setNext(SecurityControl nextSecurityControl);
}
| [
"bllakus@yandex.ru"
] | bllakus@yandex.ru |
ecb8f8892798445c9a6359f2cb2fd0727caefe1c | 6324ba3857e09e1ff891dc547f05bb7c9ed6f449 | /backend/bootstrap-parent/application/src/main/java/com/yunkang/saas/bootstrap/application/business/security/dao/AccountRoleRelationSpecification.java | 6dc6848038e6f6aa1d926a6a4a547063a642fa64 | [] | no_license | ai-coders/devp | 68a0431007ebd5796dbf48a321ee08ff2dd87708 | 9dfe34374048cea2e613fa01fd9f584c5090361d | refs/heads/master | 2023-01-09T12:16:06.197363 | 2018-11-24T09:16:25 | 2018-11-24T09:16:25 | 134,250,514 | 0 | 2 | null | 2022-12-26T05:54:12 | 2018-05-21T09:53:00 | Java | UTF-8 | Java | false | false | 1,841 | java | package com.yunkang.saas.bootstrap.application.business.security.dao;
import com.yunkang.saas.bootstrap.application.business.security.domain.AccountRoleRelation;
import com.yunkang.saas.bootstrap.platform.business.account.dto.AccountRoleRelationCondition;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
public class AccountRoleRelationSpecification implements Specification<AccountRoleRelation>{
AccountRoleRelationCondition condition;
public AccountRoleRelationSpecification(AccountRoleRelationCondition condition){
this.condition = condition;
}
@Override
public Predicate toPredicate(Root<AccountRoleRelation> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicateList = new ArrayList<>();
if(condition==null){
return null;
}
tryAddAccountIdPredicate(predicateList, root, cb);
tryAddRoleIdPredicate(predicateList, root, cb);
Predicate[] pre = new Predicate[predicateList.size()];
pre = predicateList.toArray(pre);
return cb.and(pre);
}
private void tryAddAccountIdPredicate(List<Predicate> predicateList, Root<AccountRoleRelation> root, CriteriaBuilder cb){
if (null != condition.getAccountId() ) {
predicateList.add(cb.equal(root.get(AccountRoleRelation.PROPERTY_ACCOUNT_ID).as(Long.class), condition.getAccountId()));
}
}
private void tryAddRoleIdPredicate(List<Predicate> predicateList, Root<AccountRoleRelation> root, CriteriaBuilder cb){
if (null != condition.getRoleId() ) {
predicateList.add(cb.equal(root.get(AccountRoleRelation.PROPERTY_ROLE_ID).as(Long.class), condition.getRoleId()));
}
}
}
| [
"13962217@qq.com"
] | 13962217@qq.com |
c33e015c8a192a3133dab2ae8eca4d04a5edb245 | 5a598dc8842c2b28e1c7bbaca954f3240dd53f38 | /src/main/java/com/mall/pojo/Student.java | e3f6c92d32274260dbb845f6a7b808a5a41f645d | [] | no_license | silixiaoshen/vmalltest | cd9192e60b568c384d89b191263cbff570411caa | 153801afa25d2bb1141a1683c91a7a5c84878ee8 | refs/heads/master | 2021-05-08T09:21:50.698605 | 2017-10-21T15:07:44 | 2017-10-21T15:07:44 | 107,118,317 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 103 | java | package com.mall.pojo;
public class Student {
private String name;
private String address;
}
| [
"646234481@qq.com"
] | 646234481@qq.com |
b6d1e3a288d06e3f7c7d8c36a6a2a0360293f724 | 1f66bfb915044c2f175aa066ec367fdbdb5099b7 | /trunk/arf/de.pure.diva.arf.service/src/service/arf/question/Question.java | 8ad6ce26ffb02a5025f1e0cba57d1786efa0ecc4 | [] | no_license | BackupTheBerlios/diva-unix-svn | c3fc67c1177bc94499ba4ede86f9159bfc75ccb6 | 94615f2aea19b41d1d7ed57dce3090988113c8f0 | refs/heads/master | 2021-01-21T12:46:46.328416 | 2011-04-15T18:42:15 | 2011-04-15T18:42:15 | 40,615,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,129 | java | package service.arf.question;
import service.arf.InputHandle;
import service.arf.ModelHandle;
import service.arf.reasoner.ReasonerHandle;
/**
* A question interface specifies what to do by the framework.
*/
public interface Question {
/**
* Get the name of the question.
*
* @return The name.
*/
public String getName();
/**
* Get the question.
*
* @return The question.
*/
public String getQuestion();
/**
* get the question attributes, which characterise the question.
*
* @return The question attributes.
*/
public QuestionAttributes getAttributes();
/**
* Called when the framework is asked for reasoning and validation.
*
* @param reasoner
* The reasoner handle.
* @param model
* The work model handle.
* @param input
* The work input handle.
* @param question
* The question handle.
* @return The result object of the reasoner.
*/
public Result ask(ReasonerHandle reasoner, ModelHandle model, InputHandle input, QuestionHandle question);
}
| [
"amaass@5a7442ad-50dd-4e77-902d-d7be168dd7a3"
] | amaass@5a7442ad-50dd-4e77-902d-d7be168dd7a3 |
5ab6a43b6b411d5072323dca89cbf861c6cf616a | d2dbc71cca6b864f2c2a4b641a9f570c4ec78dcb | /eladmin-system/src/main/java/me/zhengjie/modules/monitor/service/impl/VisitsServiceImpl.java | d2f439613b713a118d45866dd4448fb1e390541d | [
"Apache-2.0"
] | permissive | JawZhang/eladmin-dev | aace53fcfd20402f904cad095c37b0ca54b39056 | 3cbbc8fabe6dfb680ae80ab46d17fd0b9219fc63 | refs/heads/master | 2022-07-18T14:00:08.560086 | 2020-06-15T20:56:28 | 2020-06-15T20:56:28 | 252,428,471 | 0 | 0 | Apache-2.0 | 2022-06-17T03:05:16 | 2020-04-02T10:49:29 | Java | UTF-8 | Java | false | false | 3,449 | java | package me.zhengjie.modules.monitor.service.impl;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.monitor.domain.Visits;
import me.zhengjie.modules.monitor.repository.VisitsRepository;
import me.zhengjie.modules.monitor.service.VisitsService;
import me.zhengjie.repository.LogRepository;
import me.zhengjie.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author Zheng Jie
* @date 2018-12-13
*/
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class VisitsServiceImpl implements VisitsService {
private final VisitsRepository visitsRepository;
private final LogRepository logRepository;
public VisitsServiceImpl(VisitsRepository visitsRepository, LogRepository logRepository) {
this.visitsRepository = visitsRepository;
this.logRepository = logRepository;
}
@Override
public void save() {
LocalDate localDate = LocalDate.now();
Visits visits = visitsRepository.findByDate(localDate.toString());
if (visits == null) {
visits = new Visits();
visits.setWeekDay(StringUtils.getWeekDay());
visits.setPvCounts(1L);
visits.setIpCounts(1L);
visits.setDate(localDate.toString());
visitsRepository.save(visits);
}
}
@Override
public void count(HttpServletRequest request) {
LocalDate localDate = LocalDate.now();
Visits visits = visitsRepository.findByDate(localDate.toString());
visits.setPvCounts(visits.getPvCounts() + 1);
long ipCounts = logRepository.findIp(localDate.toString(), localDate.plusDays(1).toString());
visits.setIpCounts(ipCounts);
visitsRepository.save(visits);
}
@Override
public Object get() {
Map<String, Object> map = new HashMap<>(4);
LocalDate localDate = LocalDate.now();
Visits visits = visitsRepository.findByDate(localDate.toString());
List<Visits> list = visitsRepository.findAllVisits(localDate.minusDays(6).toString(), localDate.plusDays(1).toString());
long recentVisits = 0, recentIp = 0;
for (Visits data : list) {
recentVisits += data.getPvCounts();
recentIp += data.getIpCounts();
}
map.put("newVisits", visits.getPvCounts());
map.put("newIp", visits.getIpCounts());
map.put("recentVisits", recentVisits);
map.put("recentIp", recentIp);
return map;
}
@Override
public Object getChartData() {
Map<String, Object> map = new HashMap<>(3);
LocalDate localDate = LocalDate.now();
List<Visits> list = visitsRepository.findAllVisits(localDate.minusDays(6).toString(), localDate.plusDays(1).toString());
map.put("weekDays", list.stream().map(Visits::getWeekDay).collect(Collectors.toList()));
map.put("visitsData", list.stream().map(Visits::getPvCounts).collect(Collectors.toList()));
map.put("ipData", list.stream().map(Visits::getIpCounts).collect(Collectors.toList()));
return map;
}
}
| [
"luxuanwang@hangzhouhaoniu.com"
] | luxuanwang@hangzhouhaoniu.com |
658eccf7024a863f73fac38b8fe7d197aed00627 | 874e9ea8775d886b87390575231a5f05572abd5d | /workspace/javase/core/src/thread/syndemo/TestTicket4.zdq | b6768a4eb4953a3e1fa8cd52c3ac769ac66806f1 | [] | no_license | helifee/corp-project | f801d191ed9a6164b9b28174217ad917ef0380c8 | 97f8cdfc72ea7ef7a470723de46e91d8c4ecd8c9 | refs/heads/master | 2020-03-28T12:10:14.956362 | 2018-09-13T02:43:01 | 2018-09-13T02:43:01 | 148,274,917 | 2 | 3 | null | null | null | null | UTF-8 | Java | false | false | 249 | zdq | package thread.syndemo;
public class TestTicket4 {
public static void main(String[] args) {
Ticket4 t = new Ticket4();
new Thread(t, "A").start();
new Thread(t, "B").start();
new Thread(t, "C").start();
new Thread(t, "D").start();
}
}
| [
"helifee@gmail.com"
] | helifee@gmail.com |
29f6de3398d5d76327f565d9a1a40b11723b8e39 | 2fa924a55adebe32e77b5cb9965392d4313b9b8f | /meta/src/com/mobius/task/daily/DailyTaskForBinance.java | bb0a8fd58cdd68d4dffeeab9508d212f80d2daea | [] | no_license | light-work/mobius | 35e0edd58093a7fa5280e0de7f989df674cd4160 | bc296d74c3030abca33427ac1599d2233329cff9 | refs/heads/master | 2020-03-18T09:15:06.382618 | 2018-08-18T11:17:38 | 2018-08-18T11:17:38 | 134,553,158 | 1 | 4 | null | 2018-07-28T07:57:19 | 2018-05-23T10:26:40 | Java | UTF-8 | Java | false | false | 14,150 | java | /*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
package com.mobius.task.daily;
import com.google.inject.Injector;
import com.mobius.Utils;
import com.mobius.entity.spot.SpotDailyBtc;
import com.mobius.entity.spot.SpotDailyEth;
import com.mobius.entity.spot.SpotDailyUsdt;
import com.mobius.entity.spot.SpotSymbol;
import com.mobius.entity.sys.SysTrade;
import com.mobius.entity.utils.DrdsIDUtils;
import com.mobius.entity.utils.DrdsTable;
import com.mobius.providers.store.spot.SpotDailyBtcStore;
import com.mobius.providers.store.spot.SpotDailyEthStore;
import com.mobius.providers.store.spot.SpotDailyUsdtStore;
import com.mobius.providers.store.spot.SpotSymbolStore;
import com.mobius.providers.store.sys.SysTradeStore;
import net.sf.json.JSONArray;
import org.guiceside.commons.OKHttpUtil;
import org.guiceside.commons.lang.DateFormatUtil;
import org.guiceside.commons.lang.StringUtils;
import org.guiceside.persistence.hibernate.dao.enums.Persistent;
import org.guiceside.support.hsf.HSFServiceFactory;
import org.quartz.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* <p>
* This is just a simple job that says "Hello" to the world.
* </p>
*
* @author Bill Kratzer
*/
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class DailyTaskForBinance implements Job {
private String tradeSign = "BINANCE";
/**
* <p>
* Empty constructor for job initilization
* </p>
* <p>
* Quartz requires a public empty constructor so that the
* scheduler can instantiate the class whenever it needs.
* </p>
*/
public DailyTaskForBinance() {
}
/**
* <p>
* Called by the <code>{@link Scheduler}</code> when a
* <code>{@link Trigger}</code> fires that is associated with
* the <code>Job</code>.
* </p>
*
* @throws JobExecutionException if there is an exception while executing the job.
*/
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("run DailyTaskForBinance ");
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
Injector injector = (Injector) dataMap.get("injector");
System.out.println(injector);
if (injector != null) {
HSFServiceFactory hsfServiceFactory = injector.getInstance(HSFServiceFactory.class);
if (hsfServiceFactory != null) {
try {
buildDaily(hsfServiceFactory);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void buildDaily(HSFServiceFactory hsfServiceFactory) throws Exception {
SysTradeStore sysTradeStore = hsfServiceFactory.consumer(SysTradeStore.class);
if (sysTradeStore != null) {
SysTrade sysTrade = sysTradeStore.getBySign(tradeSign);
if (sysTrade != null) {
List<String> marketList = new ArrayList<>();
marketList.add("usdt");
marketList.add("btc");
marketList.add("eth");
SpotSymbolStore spotSymbolStore = hsfServiceFactory.consumer(SpotSymbolStore.class);
SpotDailyUsdtStore spotDailyUsdtStore = hsfServiceFactory.consumer(SpotDailyUsdtStore.class);
SpotDailyBtcStore spotDailyBtcStore = hsfServiceFactory.consumer(SpotDailyBtcStore.class);
SpotDailyEthStore spotDailyEthStore = hsfServiceFactory.consumer(SpotDailyEthStore.class);
if (spotSymbolStore != null && spotDailyUsdtStore != null && spotDailyBtcStore != null && spotDailyEthStore != null) {
for (String market : marketList) {
List<SpotSymbol> symbolList = spotSymbolStore.getListByTradeMarket(sysTrade.getId(), market);
if (symbolList != null && !symbolList.isEmpty()) {
Map<String, String> params = new HashMap<>();
Date d = DateFormatUtil.getCurrentDate(false);
d = DateFormatUtil.addDay(d, -1);
params.put("startTime", d.getTime() + "");//从前一天开始返回
params.put("limit", "1");//只显示前一天数据
params.put("interval", "1d");//按天返回
for (SpotSymbol spotSymbol : symbolList) {
params.put("symbol", spotSymbol.getSymbol());
try {
String resultStr = OKHttpUtil.get("https://api.binance.com/api/v1/klines", params);
if (StringUtils.isNotBlank(resultStr)) {
JSONArray klineArray = JSONArray.fromObject(resultStr);
if (klineArray != null && !klineArray.isEmpty()) {
List<SpotDailyUsdt> dailyUsdtList = new ArrayList<>();
List<SpotDailyBtc> dailyBtcList = new ArrayList<>();
List<SpotDailyEth> dailyEthList = new ArrayList<>();
JSONArray dayAttr = klineArray.getJSONArray(0);
if (dayAttr != null && !dayAttr.isEmpty()) {
Long times = dayAttr.getLong(0);
Double lastPrice = dayAttr.getDouble(4);
Double volume = dayAttr.getDouble(5);
Double turnover = dayAttr.getDouble(7);
Date timeDate = new Date(times);
String dateStr = DateFormatUtil.format(timeDate, DateFormatUtil.YEAR_MONTH_DAY_PATTERN);
Date tradingDate = DateFormatUtil.parse(dateStr, DateFormatUtil.YEAR_MONTH_DAY_PATTERN);
if (market.equals("usdt")) {
Integer count = spotDailyUsdtStore.getCountTradeSymbolDay(sysTrade.getId(),
spotSymbol.getId(), tradingDate);
if (count == null) {
count = 0;
}
if(count.intValue()>0){
System.out.println(dateStr + " " + spotSymbol.getSymbol() + " count >1");
}
if (count.intValue() == 0) {
SpotDailyUsdt spotDailyUsdt = new SpotDailyUsdt();
spotDailyUsdt.setId(DrdsIDUtils.getID(DrdsTable.SPOT));
spotDailyUsdt.setTradeId(sysTrade);
spotDailyUsdt.setSymbolId(spotSymbol);
spotDailyUsdt.setTradingDay(timeDate);
spotDailyUsdt.setLastPrice(lastPrice);
spotDailyUsdt.setVolume(volume);
spotDailyUsdt.setTurnover(turnover);
Utils.bind(spotDailyUsdt, "task");
dailyUsdtList.add(spotDailyUsdt);
}
} else if (market.equals("btc")) {
Integer count = spotDailyBtcStore.getCountTradeSymbolDay(sysTrade.getId(),
spotSymbol.getId(), tradingDate);
if (count == null) {
count = 0;
} if(count.intValue()>0){
System.out.println(dateStr + " " + spotSymbol.getSymbol() + " count >1");
}
if (count.intValue() == 0) {
SpotDailyBtc spotDailyBtc = new SpotDailyBtc();
spotDailyBtc.setId(DrdsIDUtils.getID(DrdsTable.SPOT));
spotDailyBtc.setTradeId(sysTrade);
spotDailyBtc.setSymbolId(spotSymbol);
spotDailyBtc.setTradingDay(timeDate);
spotDailyBtc.setLastPrice(lastPrice);
spotDailyBtc.setVolume(volume);
spotDailyBtc.setTurnover(turnover);
Utils.bind(spotDailyBtc, "task");
dailyBtcList.add(spotDailyBtc);
}
} else if (market.equals("eth")) {
Integer count = spotDailyEthStore.getCountTradeSymbolDay(sysTrade.getId(),
spotSymbol.getId(), tradingDate);
if (count == null) {
count = 0;
} if(count.intValue()>0){
System.out.println(dateStr + " " + spotSymbol.getSymbol() + " count >1");
}
if (count.intValue() == 0) {
SpotDailyEth spotDailyEth = new SpotDailyEth();
spotDailyEth.setId(DrdsIDUtils.getID(DrdsTable.SPOT));
spotDailyEth.setTradeId(sysTrade);
spotDailyEth.setSymbolId(spotSymbol);
spotDailyEth.setTradingDay(timeDate);
spotDailyEth.setLastPrice(lastPrice);
spotDailyEth.setVolume(volume);
spotDailyEth.setTurnover(turnover);
Utils.bind(spotDailyEth, "task");
dailyEthList.add(spotDailyEth);
}
}
}
if (dailyUsdtList != null && !dailyUsdtList.isEmpty()) {
spotDailyUsdtStore.save(dailyUsdtList, Persistent.SAVE);
System.out.println(spotSymbol.getSymbol() + " save success ===task========" + dailyUsdtList.size());
}
if (dailyBtcList != null && !dailyBtcList.isEmpty()) {
spotDailyBtcStore.save(dailyBtcList, Persistent.SAVE);
System.out.println(spotSymbol.getSymbol() + " save success ====task=======" + dailyBtcList.size());
}
if (dailyEthList != null && !dailyEthList.isEmpty()) {
spotDailyEthStore.save(dailyEthList, Persistent.SAVE);
System.out.println(spotSymbol.getSymbol() + " save success ====task=======" + dailyEthList.size());
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("============********======task======sleep start");
TimeUnit.MILLISECONDS.sleep(500);//秒
System.out.println("============********======task======sleep end");
}
}
}
}
}
}
}
}
}
| [
"zhenjiawang@gmail.com"
] | zhenjiawang@gmail.com |
517e4c8f93ba6369a4d41089b2d56aa67921c1f1 | 719c74dd574cf6a98b2cd28984c3cdc286cd7141 | /src/main/java/com/jcohy/pay/utils/XMLUtils.java | 0a7cc1cd1b4a013a465ee99df94a8e4ea6612765 | [] | no_license | jiachao23/pay | 97d14611f13b55b82ed693781f2cc10ce6ff1bc3 | 486270897699d85324d5113e0e11a55908494b21 | refs/heads/master | 2022-07-04T13:35:44.303327 | 2019-06-14T10:37:55 | 2019-06-14T10:37:55 | 191,925,500 | 0 | 0 | null | 2022-06-17T02:12:46 | 2019-06-14T10:37:35 | Java | UTF-8 | Java | false | false | 11,246 | java | package com.jcohy.pay.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.management.modelmbean.XMLParseException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.Map;
/**
* Created by jiac on 2019/6/11 16:08.
* ClassName : XMLUtils
* Description :
* version 1.0
*/
public class XMLUtils {
/**
* 解析xml并转化为json值
*
* @param in 输入流
* @return Json值
*/
public static JSONObject toJSONObject(InputStream in) throws XMLParseException {
if (null == in) {
return null;
}
try {
return (JSONObject) inputStream2Map(in, null);
} catch (IOException e) {
throw new XMLParseException("XML failure XML解析失败\n" + e.getMessage());
}
}
/**
* 解析xml并转化为Json值
*
* @param content json字符串
* @return Json值
*/
public static JSONObject toJSONObject(String content) throws XMLParseException {
return toJSONObject(content, Charset.defaultCharset());
}
/**
* 解析xml并转化为Json值
*
* @param content json字符串
* @param charset 字符编码
* @return Json值
*/
public static JSONObject toJSONObject(String content, Charset charset) throws XMLParseException {
if (StringUtils.isEmpty(content)) {
return null;
}
return toJSONObject(content.getBytes(charset));
}
/**
* 解析xml并转化为Json值
*
* @param content json字符串
* @return Json值
*/
public static JSONObject toJSONObject(byte[] content) throws XMLParseException {
if (null == content) {
return null;
}
try (InputStream in = new ByteArrayInputStream(content)) {
return (JSONObject) inputStream2Map(in, null);
} catch (IOException e) {
throw new XMLParseException("XML failure XML解析失败\n" + e.getMessage());
}
}
/**
* 解析xml并转化为Json值
*
* @param content json字符串
* @param clazz 需要转化的类
* @param <T> 返回对应类型
* @return Json值
*/
public static <T> T toBean(String content, Class<T> clazz) throws XMLParseException {
if (null == content || "".equals(content)) {
return null;
}
try (InputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"))) {
return inputStream2Bean(in, clazz);
} catch (IOException e) {
throw new XMLParseException("XML failure XML解析失败\n" + e.getMessage());
}
}
/**
* 获取子结点的xml
*
* @param children 集合
* @return String 子结点的xml
*/
public static JSON getChildren(NodeList children) {
JSON json = null;
for (int idx = 0; idx < children.getLength(); ++idx) {
Node node = children.item(idx);
NodeList nodeList = node.getChildNodes();
if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() <= 1) {
if (null == json) {
json = new JSONObject();
}
((JSONObject) json).put(node.getNodeName(), node.getTextContent());
} else if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() > 1) {
if (null == json) {
json = new JSONObject();
}
if (json instanceof JSONObject) {
JSONObject j = ((JSONObject) json);
if (j.containsKey(node.getNodeName())) {
JSONArray array = new JSONArray();
array.add(json);
json = array;
} else {
j.put(node.getNodeName(), getChildren(nodeList));
}
}
if (json instanceof JSONArray) {
JSONObject c = new JSONObject();
c.put(node.getNodeName(), getChildren(nodeList));
((JSONArray) json).add(c);
}
}
}
return json;
}
public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
return documentBuilderFactory.newDocumentBuilder();
}
public static Document newDocument() throws ParserConfigurationException {
return newDocumentBuilder().newDocument();
}
/***
* xml 解析成对应的对象
* @param in 输入流
* @param clazz 需要转化的类
* @param <T> 类型
* @return 对应的对象
* @throws IOException xml io转化异常
*/
public static <T> T inputStream2Bean(InputStream in, Class<T> clazz) throws IOException, XMLParseException {
try {
DocumentBuilder documentBuilder = newDocumentBuilder();
Document doc = documentBuilder.parse(in);
doc.getDocumentElement().normalize();
NodeList children = doc.getDocumentElement().getChildNodes();
JSON json = getChildren(children);
return json.toJavaObject(clazz);
} catch (Exception e) {
throw new XMLParseException("XML failure XML解析失败\n" + e.getMessage());
} finally {
in.close();
}
}
/**
* @param in xml输入流
* @param m 参数集
* @return 整理完成的参数集
* @throws IOException xml io转化异常
*/
public static Map inputStream2Map(InputStream in, Map m) throws IOException, XMLParseException {
if (null == m) {
m = new JSONObject();
}
try {
DocumentBuilder documentBuilder = newDocumentBuilder();
Document doc = documentBuilder.parse(in);
doc.getDocumentElement().normalize();
NodeList children = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < children.getLength(); ++idx) {
Node node = children.item(idx);
NodeList nodeList = node.getChildNodes();
if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() <= 1) {
m.put(node.getNodeName(), node.getTextContent());
} else if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() > 1) {
m.put(node.getNodeName(), getChildren(nodeList));
}
}
} catch (Exception e) {
// e.printStackTrace();
throw new XMLParseException("XML failure XML解析失败\n" + e.getMessage());
} finally {
in.close();
}
return m;
}
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @return XML格式的字符串
*/
public static String getMap2Xml(Map<String, Object> data) throws XMLParseException {
return getMap2Xml(data, "xml", "UTF-8");
}
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @param rootElementName 最外层节点名称
* @param encoding 字符编码
* @return XML格式的字符串
*/
public static String getMap2Xml(Map<String, Object> data, String rootElementName, String encoding) throws XMLParseException {
Document document = null;
try {
document = newDocument();
} catch (ParserConfigurationException e) {
throw new XMLParseException("XML failure XML解析失败\n" + e.getMessage());
}
org.w3c.dom.Element root = document.createElement(rootElementName);
document.appendChild(root);
/* for (Map.Entry<String, Object> entry : data.entrySet()) {
Object value = entry.getValue();
if (value == null) {
value = "";
}
value = value.toString().trim();
org.w3c.dom.Element filed = document.createElement(entry.getKey());
filed.appendChild(document.createTextNode(value.toString()));
root.appendChild(filed);
}*/
map2Xml(data, document, root);
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
return "";
}
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @param document 文档
* @param element 节点
*/
public static void map2Xml(Map<String, Object> data, Document document, org.w3c.dom.Element element) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
Object value = entry.getValue();
if (value == null) {
value = "";
}
org.w3c.dom.Element filed = document.createElement(entry.getKey());
if (value instanceof Map){
map2Xml((Map)value, document, filed);
}else {
value = value.toString().trim();
filed.appendChild(document.createTextNode(value.toString()));
}
element.appendChild(filed);
}
}
}
| [
"jia_chao23@126.com"
] | jia_chao23@126.com |
6e3607ad936037158eac343c8ade1a062e329dec | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/4/4_2b264060e5d98ea9a1de1746c1a07d7231f00254/FormScriptingTest/4_2b264060e5d98ea9a1de1746c1a07d7231f00254_FormScriptingTest_s.java | 1baf68fef2cd3a0a11b1c130d7d19991695e92cf | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 94,711 | java | package com.meterware.httpunit.javascript;
/********************************************************************************************************************
* $Id$
*
* Copyright (c) 2002-2008, Russell Gold
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*******************************************************************************************************************/
import com.meterware.httpunit.*;
import com.meterware.httpunit.controls.SelectionFormControl;
import com.meterware.httpunit.protocol.UploadFileSpec;
import com.meterware.pseudoserver.PseudoServlet;
import com.meterware.pseudoserver.WebResource;
import java.io.IOException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import junit.textui.TestRunner;
import junit.framework.TestSuite;
import org.xml.sax.SAXException;
/**
*
* @author <a href="mailto:russgold@acm.org">Russell Gold</a>
**/
public class FormScriptingTest extends HttpUnitTest {
public static void main( String args[] ) {
TestRunner.run( suite() );
}
public static TestSuite suite() {
return new TestSuite( FormScriptingTest.class );
}
public FormScriptingTest( String name ) {
super( name );
}
/**
* test to access form name in java script
* @throws Exception
*/
public void testFormNameProperty() throws Exception {
defineWebPage( "OnCommand", "<form name='the_form_with_name'/>" +
"<script type='JavaScript'>" +
" alert( document.forms[0].name );" +
"</script>" +
"<form id='the_form_with_id'/>" +
"<script type='JavaScript'>" +
" alert( document.forms[1].name );" +
"</script>" );
WebConversation wc = new WebConversation();
wc.getResponse( getHostPath() + "/OnCommand.html" );
assertEquals( "Message 1", "the_form_with_name", wc.popNextAlert() );
assertEquals( "Message 2", "the_form_with_id", wc.popNextAlert() );
}
/**
* test to access attributes from java script
* @throws Exception
*/
public void testGetAttributeForBody() throws Exception {
if (HttpUnitOptions.DEFAULT_SCRIPT_ENGINE_FACTORY.equals(HttpUnitOptions.ORIGINAL_SCRIPTING_ENGINE_FACTORY)) {
// TODO try making this work
return;
}
defineWebPage( "OnCommand", "<html><head><title>test</title>\n"+
"<script type='text/javascript'>\n"+
"function show (attr) {\n"+
// TODO make this work
" var body=document.body;\n"+
" //var body=document.getElementById('thebody');\n"+
" alert(body.getAttribute(attr));\n"+
"}\n"+
"</script></head>\n"+
"<body id='thebody' bgcolor='#FFFFCC' text='#E00000' link='#0000E0' alink='#000080' vlink='#000000'>\n"+
"<a href=\"javascript:show('bgcolor')\">background color?</a><br>\n"+
"<a href=\"javascript:show('text')\">text color?</a><br>\n"+
"<a href=\"javascript:show('link')\">linkcolor non visited</a><br>\n"+
"<a href=\"javascript:show('alink')\">link color activated links?</a>\n"+
"<a href=\"javascript:show('vlink')\">link color non visited</a><br>\n"+
"</body></html>");
WebConversation wc = new WebConversation();
WebResponse response=wc.getResponse( getHostPath() + "/OnCommand.html" );
// the page for testing externally
// System.err.println(response.getText());
WebLink[] links=response.getLinks();
for (int i=0;i<links.length;i++) {
links[ i ].click();
}
String expected[]={
"#FFFCC","#E0000","#000E0","#00080","#40000"
};
for (int i=0;i<links.length;i++) {
assertEquals( "Message for link "+i, expected[i], wc.popNextAlert() );
}
}
/**
* test to access attributes from java script
* @throws Exception
*/
public void testGetAttributeForDiv() throws Exception {
if (HttpUnitOptions.DEFAULT_SCRIPT_ENGINE_FACTORY.equals(HttpUnitOptions.ORIGINAL_SCRIPTING_ENGINE_FACTORY)) {
// TODO try making this work
return;
}
defineWebPage( "OnCommand", "<html><head><title>test</title>\n"+
"<script type='text/javascript'>\n"+
"function show (id,attr) {\n"+
" var element=document.getElementById(id);\n"+
" alert(element.getAttribute(attr));\n"+
"}\n"+
"</script></head>\n"+
"<body> <div id='div1' align='left'>\n"+
"<a href=\"javascript:show('div1','align')\">align attribute of div</a><br>\n"+
"</div></body></html>");
WebConversation wc = new WebConversation();
WebResponse response=wc.getResponse( getHostPath() + "/OnCommand.html" );
// the page for testing externally
// System.err.println(response.getText());
WebLink[] links=response.getLinks();
for (int i=0;i<links.length;i++) {
links[ i ].click();
}
String expected[]={
"left"
};
for (int i=0;i<links.length;i++) {
assertEquals( "Message for link "+i, expected[i], wc.popNextAlert() );
}
}
public void testElementsProperty() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function listElements( form ) {\n" +
" elements = form.elements;\n" +
" alert( 'form has ' + elements.length + ' elements' );\n" +
" alert( 'value is ' + elements['first'].value );\n" +
" alert( 'index is ' + elements[1].selectedIndex );\n" +
" elements[2].checked=true;\n" +
"}" +
"</script></head>" +
"<body>" +
"<form name='the_form'>" +
" <input type=text name=first value='Initial Text'>" +
" <select name='choices'>" +
" <option>red" +
" <option selected>blue" +
" </select>" +
" <input type=checkbox name=ready>" +
"</form>" +
"<a href='#' onClick='listElements( document.the_form )'>elements</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
final WebForm form = response.getFormWithName( "the_form" );
assertEquals( "Initial state", null, form.getParameterValue( "ready" ) );
response.getLinks()[ 0 ].click();
assertEquals( "Message 1", "form has 3 elements", wc.popNextAlert() );
assertEquals( "Message 2", "value is Initial Text", wc.popNextAlert() );
assertEquals( "Message 3", "index is 1", wc.popNextAlert() );
assertEquals( "Changed state", "on", form.getParameterValue( "ready" ) );
}
/**
* test clicking on a span
* inspired by Mail from Christoph to developer mailinglist of 2008-04-01
*/
public void testClickSpan() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function crtCtrla(obj,otherArg) {"+
" alert(otherArg);"+
"}"+
"</script></head>" +
"<body>" +
"<table><tr><td class='cl'><span onClick='crtCtrla(this, \"rim_ModuleSearchResult=Drilldown=key_\", null, null);' class='feact'><span>489</span></span></td></tr></table>"+
"</body></html>");
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
String elementNames[]=response.getElementNames();
HTMLElement elements[]=response.getElementsByTagName("span");
assertTrue("Two span elements should be found ",elements.length==2);
HTMLElement span1=elements[0];
String onclick="crtCtrla(this, \"rim_ModuleSearchResult=Drilldown=key_\", null, null);";
assertEquals(span1.getAttribute("onclick"),onclick);
span1.handleEvent("onclick");
String alert=wc.popNextAlert();
assertEquals("function should have been triggered to alert",alert,"rim_ModuleSearchResult=Drilldown=key_");
elements=response.getElementsWithAttribute("onclick", onclick);
int expected=1;
// TODO check how 2 could be correct ...
expected=2;
assertTrue(expected+"elements should be found ",elements.length==expected);
span1=elements[0];
span1.handleEvent("onclick");
alert=wc.popNextAlert();
assertEquals("function should have been triggered to alert",alert,"rim_ModuleSearchResult=Drilldown=key_");
// TODO remove this part
span1=elements[1];
span1.handleEvent("onclick");
alert=wc.popNextAlert();
assertEquals("function should have been triggered to alert",alert,"rim_ModuleSearchResult=Drilldown=key_");
}
public void testResetViaScript() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt'>" +
" <input type=text name=color value=green>" +
" <input type=text name=change value=color>" +
"</form>" +
"<a href='#' onClick='document.spectrum.reset(); return false;'>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "spectrum" );
form.setParameter( "color", "blue" );
response.getLinks()[ 0 ].click();
assertEquals( "Value after reset", "green", form.getParameterValue( "color" ) );
}
public void testOnResetEvent() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt' onreset='alert( \"Ran the event\" );'>" +
" <input type=text name=color value=green>" +
" <input type=reset id='clear'>" +
"</form>" +
"<a href='#' onClick='document.spectrum.reset(); return false;'>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "spectrum" );
form.setParameter( "color", "blue" );
form.getButtonWithID( "clear" ).click();
assertEquals( "Value after reset", "green", form.getParameterValue( "color" ) );
assertEquals( "Alert message", "Ran the event", wc.popNextAlert() );
form.setParameter( "color", "blue" );
response.getLinks()[ 0 ].click();
assertEquals( "Value after reset", "green", form.getParameterValue( "color" ) );
assertNull( "Event ran unexpectedly", wc.getNextAlert() );
}
public void testSubmitViaScript() throws Exception {
defineResource( "DoIt?color=green", "You made it!" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt'>" +
" <input type=text name=color value=green>" +
" <input type=submit name=change value=color>" +
" <input type=submit name=keep value=nothing>" +
"</form>" +
"<a href='#' onClick='document.spectrum.submit(); return false;'>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getLinks()[ 0 ].click();
assertEquals( "Result of submit", "You made it!", wc.getCurrentPage().getText() );
}
/**
* Verifies bug #959918
*/
public void testNumericParameterSetting1() throws Exception {
defineResource( "DoIt?id=1234", "You made it!" );
defineResource( "OnCommand.html", "<html><head>" +
"<script>" +
" function myFunction(value) {" +
" document.mainForm.id = value;" +
" document.mainForm.submit();" +
" }</script>" +
"</head>" +
"<body>" +
"<form name=mainForm action='DoIt'>" +
" <a href='javascript:myFunction(1234)'>View Asset</a>" +
" <input type='hidden' name='id'>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getLinks()[ 0 ].click();
assertEquals( "Result of submit", "You made it!", wc.getCurrentPage().getText() );
}
/**
* Verifies bug #1087180
*/
public void testNumericParameterSetting2() throws Exception {
defineResource( "DoIt.html?id=1234", "You made it!" );
defineResource( "OnCommand.html", "<html><head>" +
"<script>" +
" function myFunction(value) {" +
" document.mainForm.id.value = value;" +
" document.mainForm.submit();" +
" }</script>" +
"</head>" +
"<body>" +
"<form name=mainForm action='DoIt.html'>" +
" <a href='javascript:myFunction(1234)'>View Asset</a>" +
" <input type='hidden' name='id'>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getLinks()[ 0 ].click();
assertEquals( "Result of submit", "You made it!", wc.getCurrentPage().getText() );
}
/**
* Verifies bug #1073810 (Null pointer exception if javascript sets control value to null)
*/
public void testNullParameterSetting() throws Exception {
defineResource( "OnCommand.html", "<html><head>" +
"<script>" +
" function myFunction(value) {" +
" document.mainForm.id.value = null;" +
" }</script>" +
"</head>" +
"<body>" +
"<form name=mainForm action='DoIt'>" +
" <a href='javascript:myFunction()'>View Asset</a>" +
" <input type='hidden' name='id'>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getLinks()[ 0 ].click();
}
/**
* test changing form Action from JavaScript
* @throws Exception
*/
public void testFormActionFromJavaScript() throws Exception {
// pending Patch 1155792 wf 2007-12-30
// TODO activate in due course
dotestFormActionFromJavaScript("param");
}
/**
* verify bug 1155792 ] problems setting form action from javascript [patch]
*/
public void xtestFormActionFromJavaScript2() throws Exception {
// pending Patch 1155792 wf 2007-12-30
// TODO activate in due course
dotestFormActionFromJavaScript("action");
}
/**
* test doing a form action from Javascript
* @param paramName
* @throws Exception
*/
public void dotestFormActionFromJavaScript(String paramName) throws Exception {
if (HttpUnitOptions.DEFAULT_SCRIPT_ENGINE_FACTORY.equals(HttpUnitOptions.ORIGINAL_SCRIPTING_ENGINE_FACTORY)) {
return;
}
defineWebPage("foo","foocontent");
defineResource("bar.html","<html><head><script>"+
"function submitForm()"+
"{"+
" document.test.action='/foo.html';"+
" document.test.submit()"+
" }"+
"</script></head>" +
"<form name=\"test\" method=\"post\""+
" action=\"bar.html?"+paramName+"=bar\">"+
"</form>"+
" <a href=\"javascript:submitForm()\">go</a></html>");
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/foo.html" );
String fooContent=wc.getCurrentPage().getText();
// System.err.println(fooContent);
response = wc.getResponse( getHostPath() + "/bar.html" );
try {
response.getLinks()[ 0 ].click();
String result=wc.getCurrentPage().getText();
// System.err.println(result);
assertEquals( "Result of submit", fooContent, result );
} catch (RuntimeException rte) {
// TODO activate this test
// There is currently a
// org.mozilla.javascript.JavaScriptException: com.meterware.httpunit.HttpNotFoundException: Error on HTTP request: 404 unable to find /foo.html [http://localhost:1929/foo.html]
// here
fail("There should be no "+rte.getMessage()+" Runtime exception here");
}
}
/**
* test indirect invocation
* feature request
* [ 796961 ] Support indirect invocation of JavaScript events on elements
* by David D. Kilzer
* @throws Exception
*/
public void testIndirectEventInvocation() throws Exception {
defineResource( "OnCommand.html", "<html><head></head><body>" +
"<form name=\"testForm\">" +
"<input type=\"text\" name=\"one\" value=\"default value\" onchange=\"this.form.two.value = this.form.one.value;\">" +
"<input type=\"text\" name=\"two\" value=\"not the same value\">" +
"</form>" +
"<script language=\"javascript\" type=\"text/javascript\">\n" +
"document.forms[\"testForm\"].elements[\"one\"].onchange();\n" +
"</script>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "testForm" );
assertEquals( "field one equals field two", form.getParameterValue("one"), form.getParameterValue( "two" ) );
}
/**
* test disabling a submit button via script
* @throws Exception
*/
public void testEnablingDisabledSubmitButtonViaScript() throws Exception {
defineResource( "DoIt?color=green&change=success", "You made it!" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt'>" +
" <input type=text name=color value=green>" +
" <input type=button name=enableChange id=enableChange value=Hello onClick='document.spectrum.change.disabled=false;'>" +
" <input type=submit disabled name=change value=success>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "spectrum" );
assertSubmitButtonDisabled( form );
assertDisabledSubmitButtonCanNotBeClicked( form );
form = runJavaScriptToToggleEnabledStateOfButton( form, wc );
assertSubmitButtonEnabled( form );
clickSubmitButtonToProveThatItIsEnabled( form );
assertEquals( "Result of submit", "You made it!", wc.getCurrentPage().getText() );
}
public void testDisablingEnabledSubmitButtonViaScript() throws Exception {
defineResource( "DoIt?color=green&change=success", "You made it!" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt'>" +
" <input type=text name=color value=green>" +
" <input type=button name=enableChange id=enableChange value=Hello onClick='document.spectrum.change.disabled=true;'>" +
" <input type=submit name=change value=success>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "spectrum" );
assertSubmitButtonEnabled( form );
form = runJavaScriptToToggleEnabledStateOfButton( form, wc );
assertNotNull( form );
assertSubmitButtonDisabled( form );
assertDisabledSubmitButtonCanNotBeClicked( form );
}
public void testEnablingDisabledNormalButtonViaScript() throws Exception {
defineResource( "DoIt?color=green", "You made it!" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt'>" +
" <input type=text name=color value=green>" +
" <input type=button name=enableChange id=enableChange value=Hello onClick='document.spectrum.changee.disabled=false;'>" +
" <input type=button disabled name=changee id=changee value=Hello onClick='document.spectrum.submit();'>" +
" <input type=submit name=change value=success>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "spectrum" );
assertNormalButtonDisabled( form, "changee" );
assertDisabledNormalButtonCanNotBeClicked( form, "changee" );
form = runJavaScriptToToggleEnabledStateOfButton( form, wc );
assertNormalButtonEnabled( form, "changee" );
clickButtonToProveThatItIsEnabled( form, "changee" );
assertEquals( "Result of submit", "You made it!", wc.getCurrentPage().getText() );
}
public void testDisablingEnableddNormalButtonViaScript() throws Exception {
defineResource( "DoIt?color=green", "You made it!" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt'>" +
" <input type=text name=color value=green>" +
" <input type=button name=enableChange id=enableChange value=Hello onClick='document.spectrum.changee.disabled=true;'>" +
" <input type=button name=changee id=changee value=Hello onClick='document.spectrum.submit();'>" +
" <input type=submit name=change value=success>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "spectrum" );
assertNormalButtonEnabled( form, "changee" );
form = runJavaScriptToToggleEnabledStateOfButton( form, wc );
assertNormalButtonDisabled( form, "changee" );
assertDisabledNormalButtonCanNotBeClicked( form, "changee" );
}
/**
* also fix for [ 1124024 ] Formcontrol and isDisabled should be public
* by wolfgang fahl
* @param form
*/
private void assertSubmitButtonDisabled( WebForm form ) {
assertTrue( "Button should have been Disabled", form.getSubmitButton( "change" ).isDisabled() );
}
private void assertNormalButtonDisabled( WebForm form, String buttonID ) {
assertTrue( "Button should have been Disabled", form.getButtonWithID( buttonID ).isDisabled() );
}
private void assertSubmitButtonEnabled( WebForm form ) {
assertFalse( "Button should have been enabled or NOT-Disabled", form.getSubmitButton( "change" ).isDisabled() );
}
private void assertNormalButtonEnabled( WebForm form, String buttonID ) {
assertFalse( "Button should have been enabled or NOT-Disabled", form.getButtonWithID( buttonID ).isDisabled() );
}
/**
* click submit button to prove that it is enabled
* @param form
* @throws IOException
* @throws SAXException
*/
private void clickSubmitButtonToProveThatItIsEnabled( WebForm form ) throws IOException, SAXException {
WebResponse response = form.submit();
assertNotNull( response );
}
private void clickButtonToProveThatItIsEnabled( WebForm form, String buttonID ) throws IOException, SAXException {
form.getButtonWithID( buttonID ).click();
}
/**
* change the enable State of Button via Javascript
* @param form
* @param wc
* @return
* @throws IOException
* @throws SAXException
*/
private WebForm runJavaScriptToToggleEnabledStateOfButton( WebForm form, WebConversation wc ) throws IOException, SAXException {
Button enableChange = form.getButtonWithID( "enableChange" );
enableChange.click();
WebResponse currentPage = wc.getCurrentPage();
form = currentPage.getFormWithName( "spectrum" );
return form;
}
private void assertDisabledSubmitButtonCanNotBeClicked( WebForm form ) {
try {
SubmitButton button = form.getSubmitButton( "change" );
form.submit( button );
} catch (Exception e) {
String msg=e.getMessage();
assertTrue(msg.indexOf( "The specified button (name='change' value='success' is disabled and may not be used to submit this form" ) > -1 );
}
}
private void assertDisabledNormalButtonCanNotBeClicked( WebForm form, String buttonID ) {
try {
Button button = form.getButtonWithID( buttonID );
button.click();
} catch (Exception e) {
assertTrue( e.toString().indexOf( "Button 'changee' is disabled and may not be clicked" ) > -1 );
}
}
public void testEnablingDisabledRadioButtonViaScript() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt'>" +
"<input type='radio' name='color' value='red' checked>" +
"<input type='radio' name='color' value='green' disabled>" +
"<input type=button name=enableChange id=enableChange value=Hello onClick='document.spectrum.color[1].disabled=false;'>" +
"<input type=submit name=change value=success>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "spectrum" );
assertMatchingSet( "Color choices", new String[] { "red" }, form.getOptionValues( "color" ) );
try {
form.setParameter( "color", "green" );
fail( "Should not have been able to set color" );
} catch (Exception e) {}
form.getScriptableObject().doEventScript( "document.spectrum.color[1].disabled=false" );
assertMatchingSet( "Color choices", new String[] { "red", "green" }, form.getOptionValues( "color" ) );
form.setParameter( "color", "green" );
}
public void testSubmitViaScriptWithPostParams() throws Exception {
defineResource( "/servlet/TestServlet?param3=value3¶m4=value4", new PseudoServlet() {
public WebResource getPostResponse() {
return new WebResource( "You made it!", "text/plain" );
}
} );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form method=POST enctype='multipart/form-data' name='TestForm'>" +
" <input type=hidden name=param1 value='value1'>" +
" <input type=text name=param2 value=''>" +
"</form>" +
"<a href='#' onclick='SubmitForm(\"/servlet/TestServlet?param3=value3¶m4=value4\")'>" +
"<img SRC='/gifs/submit.gif' ALT='Submit' TITLE='Submit' NAME='Submit'></a>" +
"<script language=JavaScript type='text/javascript'>" +
" function SubmitForm(submitLink) {" +
" var ltestForm = document.TestForm;" +
" ltestForm.action = submitLink;" +
" ltestForm.submit();" +
" }" +
"</script>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getLinks()[0].click();
assertEquals( "Result of submit", "You made it!", wc.getCurrentPage().getText() );
}
public void testSubmitButtonlessFormViaScript() throws Exception {
defineResource( "DoIt?color=green", "You made it!" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt'>" +
" <input type=text name=color value=green>" +
"</form>" +
"<a href='#' onClick='document.spectrum.submit(); return false;'>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getLinks()[ 0 ].click();
assertEquals( "Result of submit", "You made it!", wc.getCurrentPage().getText() );
}
public void testSubmitViaScriptButton() throws Exception {
defineResource( "DoIt?color=green", "You made it!" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt' onsubmit='return false;'>" +
" <input type=text name=color value=green>" +
" <input type=button id=submitButton value=submit onClick='this.form.submit();'>" +
"</form>" +
"<a href='#' onClick='document.spectrum.submit(); return false;'>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getFormWithName( "spectrum" ).getButtons()[0].click();
assertEquals( "Result of submit", "You made it!", wc.getCurrentPage().getText() );
}
public void testDisabledScriptButton() throws Exception {
defineResource( "DoIt?color=green", "You made it!" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt' onsubmit='return false;'>" +
" <input type=text name=color value=green>" +
" <input type=button id=submitButton disabled value=submit onClick='this.form.submit();'>" +
"</form>" +
"<a href='#' onClick='document.spectrum.submit(); return false;'>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
try {
response.getFormWithName( "spectrum" ).getButtons()[0].click();
fail( "Should not have permitted click of disabled button" );
} catch (IllegalStateException e) {}
}
public void testUpdateBeforeSubmit() throws Exception {
defineResource( "DoIt?color=green", "You made it!" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt'>" +
" <input type=text name=color value=red>" +
" <input type=submit onClick='form.color.value=\"green\";'>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getFormWithName( "spectrum" ).getButtons()[0].click();
assertEquals( "Result of submit", "You made it!", wc.getCurrentPage().getText() );
}
public void testSubmitButtonScript() throws Exception {
defineResource( "DoIt?color=green", "You made it!" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name=spectrum action='DoIt'>" +
" <input type=text name=color value=red>" +
" <input type=submit onClick='form.color.value=\"green\";'>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getFormWithName( "spectrum" ).submit();
assertEquals( "Result of submit", "You made it!", wc.getCurrentPage().getText() );
}
public void testSetFormTextValue() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body onLoad=\"document.realform.color.value='green'\">" +
"<form name='realform'><input name='color' value='blue'></form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "realform" );
assertEquals( "color parameter value", "green", form.getParameterValue( "color" ) );
}
/**
* test for onMouseDownEvent support patch 884146
* by Bjrn Beskow - bbeskow
* @throws Exception
*/
public void testCheckboxOnMouseDownEvent() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name='the_form'>" +
" <input type='checkbox' name='color' value='blue' " +
" onMouseDown='alert( \"color-blue is now \" + document.the_form.color.checked );'>" +
"</form>" +
"<a href='#' onMouseDown='document.the_form.color.checked=true;'>blue</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "the_form" );
assertEquals( "Initial state", null, form.getParameterValue( "color" ) );
assertEquals( "Alert message before change", null, wc.getNextAlert() );
form.removeParameter( "color" );
assertEquals( "Alert message w/o change", null, wc.getNextAlert() );
form.setParameter( "color", "blue" );
assertEquals( "Alert after change", "color-blue is now true", wc.popNextAlert() );
form.removeParameter( "color" );
assertEquals( "Alert after change", "color-blue is now false", wc.popNextAlert() );
assertEquals( "Changed state", null, form.getParameterValue( "color" ) );
response.getLinks()[ 0 ].click();
assertEquals( "Final state", "blue", form.getParameterValue( "color" ) );
assertEquals( "Alert message after JavaScript change", null, wc.getNextAlert() );
}
/**
* test the onChange event
* @throws Exception
*/
public void testSetFormTextOnChangeEvent() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name='the_form'>" +
" <input name='color' value='blue' " +
" onChange='alert( \"color is now \" + document.the_form.color.value );'>" +
"</form>" +
"<a href='#' onClick='document.the_form.color.value=\"green\";'>green</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "the_form" );
assertEquals( "Initial state", "blue", form.getParameterValue( "color" ) );
assertEquals( "Alert message before change", null, wc.getNextAlert() );
form.setParameter( "color", "red" );
assertEquals( "Alert after change", "color is now red", wc.popNextAlert() );
assertEquals( "Changed state", "red", form.getParameterValue( "color" ) );
response.getLinks()[ 0 ].click();
assertEquals( "Final state", "green", form.getParameterValue( "color" ) );
assertEquals( "Alert message after JavaScript change", null, wc.getNextAlert() );
}
public void testCheckboxProperties() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function viewCheckbox( checkbox ) { \n" +
" alert( 'checkbox ' + checkbox.name + ' default = ' + checkbox.defaultChecked )\n;" +
" alert( 'checkbox ' + checkbox.name + ' checked = ' + checkbox.checked )\n;" +
" alert( 'checkbox ' + checkbox.name + ' value = ' + checkbox.value )\n;" +
"}\n" +
"</script></head>" +
"<body>" +
"<form name='realform'><input type='checkbox' name='ready' value='good'></form>" +
"<a href='#' name='clear' onMouseOver='document.realform.ready.checked=false;'>clear</a>" +
"<a href='#' name='set' onMouseOver='document.realform.ready.checked=true;'>set</a>" +
"<a href='#' name='change' onMouseOver='document.realform.ready.value=\"waiting\";'>change</a>" +
"<a href='#' name='report' onMouseOver='viewCheckbox( document.realform.ready );'>report</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "realform" );
response.getLinkWithName( "report" ).mouseOver();
verifyCheckbox( /* default */ wc, false, /* checked */ false, /* value */ "good" );
assertEquals( "initial parameter value", null, form.getParameterValue( "ready" ) );
response.getLinkWithName( "set" ).mouseOver();
assertEquals( "changed parameter value", "good", form.getParameterValue( "ready" ) );
response.getLinkWithName( "clear" ).mouseOver();
assertEquals( "final parameter value", null, form.getParameterValue( "ready" ) );
response.getLinkWithName( "change" ).mouseOver();
assertEquals( "final parameter value", null, form.getParameterValue( "ready" ) );
response.getLinkWithName( "report" ).mouseOver();
verifyCheckbox( /* default */ wc, false, /* checked */ false, /* value */ "waiting" );
form.setParameter( "ready", "waiting" );
}
public void testIndexedCheckboxProperties() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function viewCheckbox( checkbox ) { \n" +
" alert( 'checkbox ' + checkbox.name + ' default = ' + checkbox.defaultChecked )\n;" +
" alert( 'checkbox ' + checkbox.name + ' checked = ' + checkbox.checked )\n;" +
" alert( 'checkbox ' + checkbox.name + ' value = ' + checkbox.value )\n;" +
"}\n" +
"</script></head>" +
"<body onload='viewCheckbox( document.realform.ready[0] ); viewCheckbox( document.realform.ready[1] );'>" +
"<form name='realform'>" +
"<input type='checkbox' name='ready' value='good' checked>" +
"<input type='checkbox' name='ready' value='bad'>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getFormWithName( "realform" );
verifyCheckbox( /* default */ wc, true, /* checked */ true, /* value */ "good" );
verifyCheckbox( /* default */ wc, false, /* checked */ false, /* value */ "bad" );
}
private void verifyCheckbox( WebClient wc, boolean defaultChecked, boolean checked, String value ) {
assertEquals( "Message " + 1 + "-1", "checkbox ready default = " + defaultChecked, wc.popNextAlert() );
assertEquals( "Message " + 1 + "-2", "checkbox ready checked = " + checked, wc.popNextAlert() );
assertEquals( "Message " + 1 + "-3", "checkbox ready value = " + value, wc.popNextAlert() );
}
public void testCheckboxOnClickEvent() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name='the_form'>" +
" <input type='checkbox' name='color' value='blue' " +
" onClick='alert( \"color-blue is now \" + document.the_form.color.checked );'>" +
"</form>" +
"<a href='#' onClick='document.the_form.color.checked=true;'>blue</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "the_form" );
assertEquals( "Initial state", null, form.getParameterValue( "color" ) );
assertEquals( "Alert message before change", null, wc.getNextAlert() );
form.removeParameter( "color" );
assertEquals( "Alert message w/o change", null, wc.getNextAlert() );
form.setParameter( "color", "blue" );
assertEquals( "Alert after change", "color-blue is now true", wc.popNextAlert() );
form.removeParameter( "color" );
assertEquals( "Alert after change", "color-blue is now false", wc.popNextAlert() );
assertEquals( "Changed state", null, form.getParameterValue( "color" ) );
response.getLinks()[ 0 ].click();
assertEquals( "Final state", "blue", form.getParameterValue( "color" ) );
assertEquals( "Alert message after JavaScript change", null, wc.getNextAlert() );
}
public void testSetCheckboxOnClickEvent() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name='the_form'>" +
" <input type='checkbox' name='color' value='blue' " +
" onClick='alert( \"color-blue is now \" + document.the_form.color.checked );'>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "the_form" );
form.toggleCheckbox( "color" );
assertEquals( "Alert after change", "color-blue is now true", wc.popNextAlert() );
form.setCheckbox( "color", false );
assertEquals( "Alert after change", "color-blue is now false", wc.popNextAlert() );
}
/**
* test the radio button properties via index
* @throws Exception
*/
public void testIndexedRadioProperties() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function viewRadio( radio ) { \n" +
" alert( 'radio ' + radio.name + ' default = ' + radio.defaultChecked )\n;" +
" alert( 'radio ' + radio.name + ' checked = ' + radio.checked )\n;" +
" alert( 'radio ' + radio.name + ' value = ' + radio.value )\n;" +
"}\n" +
"</script></head>" +
"<body onload='viewRadio( document.realform.ready[0] ); viewRadio( document.realform.ready[1] );'>" +
"<form name='realform'>" +
"<input type='radio' name='ready' value='good' checked>" +
"<input type='radio' name='ready' value='bad'>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getFormWithName( "realform" );
verifyRadio( /* default */ wc, true, /* checked */ true, /* value */ "good" );
verifyRadio( /* default */ wc, false, /* checked */ false, /* value */ "bad" );
}
/**
* test onMouseDownEvent for radio buttons
* @throws Exception
*/
public void testRadioOnMouseDownEvent() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name='the_form'>" +
" <input type='radio' name='color' value='blue' " +
" onMouseDown='alert( \"color is now blue\" );'>" +
" <input type='radio' name='color' value='red' checked" +
" onMouseDown='alert( \"color is now red\" );'>" +
"</form>" +
"<a href='#' onMouseDown='document.the_form.color[1].checked=false; document.the_form.color[0].checked=true;'>blue</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "the_form" );
assertEquals( "Initial state", "red", form.getParameterValue( "color" ) );
assertEquals( "Alert message before change", null, wc.getNextAlert() );
form.setParameter( "color", "red" );
assertEquals( "Alert message w/o change", null, wc.getNextAlert() );
form.setParameter( "color", "blue" );
assertEquals( "Alert after change", "color is now blue", wc.popNextAlert() );
form.setParameter( "color", "red" );
assertEquals( "Alert after change", "color is now red", wc.popNextAlert() );
assertEquals( "Changed state", "red", form.getParameterValue( "color" ) );
response.getLinks()[ 0 ].click();
assertEquals( "Final state", "blue", form.getParameterValue( "color" ) );
assertEquals( "Alert message after JavaScript change", null, wc.getNextAlert() );
}
private void verifyRadio( WebClient wc, boolean defaultChecked, boolean checked, String value ) {
assertEquals( "Message " + 1 + "-1", "radio ready default = " + defaultChecked, wc.popNextAlert() );
assertEquals( "Message " + 1 + "-2", "radio ready checked = " + checked, wc.popNextAlert() );
assertEquals( "Message " + 1 + "-3", "radio ready value = " + value, wc.popNextAlert() );
}
public void testRadioOnClickEvent() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name='the_form'>" +
" <input type='radio' name='color' value='blue' " +
" onClick='alert( \"color is now blue\" );'>" +
" <input type='radio' name='color' value='red' checked" +
" onClick='alert( \"color is now red\" );'>" +
"</form>" +
"<a href='#' onClick='document.the_form.color[1].checked=false; document.the_form.color[0].checked=true;'>blue</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "the_form" );
assertEquals( "Initial state", "red", form.getParameterValue( "color" ) );
assertEquals( "Alert message before change", null, wc.getNextAlert() );
form.setParameter( "color", "red" );
assertEquals( "Alert message w/o change", null, wc.getNextAlert() );
form.setParameter( "color", "blue" );
assertEquals( "Alert after change", "color is now blue", wc.popNextAlert() );
form.setParameter( "color", "red" );
assertEquals( "Alert after change", "color is now red", wc.popNextAlert() );
assertEquals( "Changed state", "red", form.getParameterValue( "color" ) );
response.getLinks()[ 0 ].click();
assertEquals( "Final state", "blue", form.getParameterValue( "color" ) );
assertEquals( "Alert message after JavaScript change", null, wc.getNextAlert() );
}
public void testFormActionProperty() throws Exception {
WebConversation wc = new WebConversation();
defineWebPage( "Default", "<form method=GET name='the_form' action = 'ask'>" +
"<Input type=text name=age>" +
"<Input type=submit value=Go>" +
"</form>" +
"<a href='#' name='doTell' onClick='document.the_form.action=\"tell\";'>tell</a>" +
"<a href='#' name='doShow' onClick='alert( document.the_form.action );'>show</a>" );
WebResponse page = wc.getResponse( getHostPath() + "/Default.html" );
page.getLinkWithName( "doShow" ).click();
assertEquals( "Current action", "ask", wc.popNextAlert() );
page.getLinkWithName( "doTell" ).click();
WebRequest request = page.getForms()[0].getRequest();
request.setParameter( "age", "23" );
assertEquals( getHostPath() + "/tell?age=23", request.getURL().toExternalForm() );
}
public void testFormTargetProperty() throws Exception {
WebConversation wc = new WebConversation();
defineWebPage( "Default", "<form method=GET name='the_form' action = 'ask'>" +
"<Input type=text name=age>" +
"<Input type=submit value=Go>" +
"</form>" +
"<a href='#' name='doTell' onClick='document.the_form.target=\"_blank\";'>tell</a>" +
"<a href='#' name='doShow' onClick='alert( document.the_form.target );'>show</a>" );
WebResponse page = wc.getResponse( getHostPath() + "/Default.html" );
page.getLinkWithName( "doShow" ).click();
assertEquals( "Initial target", "_top", wc.popNextAlert() );
page.getLinkWithName( "doTell" ).click();
page.getLinkWithName( "doShow" ).click();
assertEquals( "Current target", "_blank", wc.popNextAlert() );
WebRequest request = page.getForms()[0].getRequest();
assertEquals( "_blank", request.getTarget() );
}
public void testFormValidationOnSubmit() throws Exception {
defineResource( "doIt?color=pink", "You got it!", "text/plain" );
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function verifyForm() { " +
" if (document.realform.color.value == 'pink') {" +
" return true;" +
" } else {" +
" alert( 'wrong color' );" +
" return false;" +
" }" +
"}" +
"</script></head>" +
"<body>" +
"<form name='realform' action='doIt' onSubmit='return verifyForm();'>" +
" <input name='color' value='blue'>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "realform" );
form.submit();
assertEquals( "Alert message", "wrong color", wc.popNextAlert() );
assertSame( "Current response", response, wc.getCurrentPage() );
form.setParameter( "color", "pink" );
WebResponse newResponse = form.submit();
assertEquals( "Result of submit", "You got it!", newResponse.getText() );
}
public void testFormSelectReadableProperties() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function viewSelect( choices ) { \n" +
" alert( 'select has ' + choices.options.length + ' options' )\n;" +
" alert( 'select still has ' + choices.length + ' options' )\n;" +
" alert( 'select option ' + choices.options[0].index + ' is ' + choices.options[0].text )\n;" +
" alert( 'select 2nd option value is ' + choices.options[1].value )\n;" +
" if (choices.options[0].selected) alert( 'red selected' );\n" +
" if (choices.options[1].selected) alert( 'blue selected' );\n" +
" if (choices[1].selected) alert( 'blue selected again' );\n" +
"}\n" +
"</script></head>" +
"<body onLoad='viewSelect( document.the_form.choices )'>" +
"<form name='the_form'>" +
" <select name='choices'>" +
" <option value='1'>red" +
" <option value='3' selected>blue" +
" </select>" +
"</form>" +
"<a href='#' onMouseOver=\"alert( 'selected #' + document.the_form.choices.selectedIndex );\">which</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
assertEquals( "1st message", "select has 2 options", wc.popNextAlert() );
assertEquals( "2nd message", "select still has 2 options", wc.popNextAlert() );
assertEquals( "3rd message", "select option 0 is red", wc.popNextAlert() );
assertEquals( "4th message", "select 2nd option value is 3", wc.popNextAlert() );
assertEquals( "5th message", "blue selected", wc.popNextAlert() );
assertEquals( "6th message", "blue selected again", wc.popNextAlert() );
response.getLinks()[0].mouseOver();
assertEquals( "before change message", "selected #1", wc.popNextAlert() );
response.getFormWithName( "the_form" ).setParameter( "choices", "1" );
response.getLinks()[0].mouseOver();
assertEquals( "after change message", "selected #0", wc.popNextAlert() );
}
/**
* test that in case of an Index out of bounds problem an exception is thrown
* with a meaningful message (not nullpointer exception)
* Bug report [ 1124057 ] Out of Bounds Exception should be avoided
* by Wolfgang Fahl of 2005-02-16 17:25
*
*/
public void testSelectIndexOutOfBoundsCatching() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function viewSelect( choices ) { \n" +
" // try accessing out of bounds\n"+
" alert( choices.options[5].value )\n;" +
"}\n" +
"</script></head>" +
"<body onLoad='viewSelect( document.the_form.choices )'>" +
"<form name='the_form'>" +
" <select name='choices'>" +
" <option value='1'>red" +
" <option value='3' selected>blue" +
" </select>" +
"</form>" +
"<a href='#' onMouseOver=\"alert( 'selected #' + document.the_form.choices.selectedIndex );\">which</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
boolean oldDebug= HttpUnitUtils.setEXCEPTION_DEBUG(false);
try {
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
fail("There should be a runtime exeption here");
// java.lang.RuntimeException: Event 'viewSelect( document.the_form.choices )' failed: java.lang.RuntimeException: invalid index 5 for Options redblue,
} catch (java.lang.RuntimeException rte) {
assertTrue(rte.getMessage().indexOf("invalid index 5 for Options red,blue")>0);
} finally {
HttpUnitUtils.setEXCEPTION_DEBUG(oldDebug);
}
}
public void testFormSelectDefaults() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function viewSelect( form ) { \n" +
" alert( 'first default index= ' + form.first.selectedIndex )\n;" +
" alert( 'second default index= ' + form.second.selectedIndex )\n;" +
" alert( 'third default index= ' + form.third.selectedIndex )\n;" +
" alert( 'fourth default index= ' + form.fourth.selectedIndex )\n;" +
"}\n" +
"</script></head>" +
"<body onLoad='viewSelect( document.the_form )'>" +
"<form name='the_form'>" +
" <select name='first'><option value='1'>red<option value='3'>blue</select>" +
" <select name='second' multiple><option value='1'>red<option value='3'>blue</select>" +
" <select name='third' size=2><option value='1'>red<option value='3'>blue</select>" +
" <select name='fourth' multiple size=1><option value='1'>red<option value='3'>blue</select>" +
"</form>" +
"</body></html>" );
WebConversation wc = new WebConversation();
wc.getResponse( getHostPath() + "/OnCommand.html" );
assertEquals( "1st message", "first default index= 0", wc.popNextAlert() );
assertEquals( "2nd message", "second default index= -1", wc.popNextAlert() );
assertEquals( "3rd message", "third default index= -1", wc.popNextAlert() );
assertEquals( "4th message", "fourth default index= 0", wc.popNextAlert() );
}
public void testFileSubmitProperties() throws Exception {
File file = new File( "temp.html" );
defineResource( "OnCommand.html", "<html><head></head>" +
"<body'>" +
"<form name='the_form'>" +
" <input type='file' name='file'>" +
"</form>" +
"<a href='#' onMouseOver=\"alert( 'file selected is [' + document.the_form.file.value + ']' );\">which</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getLinks()[0].mouseOver();
assertEquals( "1st message", "file selected is []", wc.popNextAlert() );
WebForm form = response.getFormWithName( "the_form" );
form.setParameter( "file", new UploadFileSpec[] { new UploadFileSpec( file ) } );
response.getLinks()[0].mouseOver();
assertEquals( "2nd message", "file selected is [" + file.getAbsolutePath() + "]", wc.popNextAlert() );
}
public void testFormSelectOnChangeEvent() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function selectOptionNum( the_select, index ) { \n" +
" for (var i = 0; i < the_select.length; i++) {\n" +
" the_select.options[i].selected = (i == index);\n" +
" }\n" +
"}\n" +
"</script></head>" +
"<body>" +
"<form name='the_form'>" +
" <select name='choices' onChange='alert( \"Selected index is \" + document.the_form.choices.selectedIndex );'>" +
" <option>red" +
" <option selected>blue" +
" </select>" +
"</form>" +
"<a href='#' onClick='selectOptionNum( document.the_form.choices, 0 )'>reset</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
final WebForm form = response.getFormWithName( "the_form" );
assertEquals( "Initial state", "blue", form.getParameterValue( "choices" ) );
assertEquals( "Alert message before change", null, wc.getNextAlert() );
form.setParameter( "choices", "red" );
assertEquals( "Alert after change", "Selected index is 0", wc.popNextAlert() );
form.setParameter( "choices", "blue" );
assertEquals( "Alert after change", "Selected index is 1", wc.popNextAlert() );
assertEquals( "Initial state", "blue", form.getParameterValue( "choices" ) );
response.getLinks()[ 0 ].click();
assertEquals( "Final state", "red", form.getParameterValue( "choices" ) );
assertEquals( "Alert message after JavaScript change", null, wc.getNextAlert() );
}
public void testFormSelectWriteableProperties() throws Exception {
defineResource( "OnCommand.html", "<html><head></head>" +
"<body>" +
"<form name='the_form'>" +
" <select name='choices'>" +
" <option value='1'>red" +
" <option value='3'>blue" +
" <option value='5'>green" +
" <option value='7'>azure" +
" </select>" +
"</form>" +
"<a href='#' onclick='alert( \"Selected index is \" + document.the_form.choices.selectedIndex );'>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "the_form" );
assertEquals( "initial selection", "1", form.getParameterValue( "choices" ) );
response.getLinks()[0].click();
assertEquals( "Notification", "Selected index is 0", wc.popNextAlert() );
}
public void testFormSelectDefaultProperties() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function selectOptionNum( the_select, index ) { \n" +
" for (var i = 0; i < the_select.length; i++) {\n" +
" if (i == index) the_select.options[i].selected = true;\n" +
" }\n" +
"}\n" +
"</script></head>" +
"<body>" +
"<form name='the_form'>" +
" <select name='choices'>" +
" <option value='1'>red" +
" <option value='3' selected>blue" +
" <option value='5'>green" +
" <option value='7'>azure" +
" </select>" +
"</form>" +
"<a href='#' onClick='selectOptionNum( document.the_form.choices, 2 )'>green</a>" +
"<a href='#' onClick='selectOptionNum( document.the_form.choices, 0 )'>red</a>" +
"<a href='#' onClick='document.the_form.choices.options[0].value=\"9\"'>red</a>" +
"<a href='#' onClick='document.the_form.choices.options[0].text=\"orange\"'>orange</a>" +
"<a href='#' onClick='document.the_form.choices.selectedIndex=3'>azure</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "the_form" );
assertEquals( "initial selection", "3", form.getParameterValue( "choices" ) );
response.getLinks()[0].click();
assertEquals( "2nd selection", "5", form.getParameterValue( "choices" ) );
response.getLinks()[1].click();
assertEquals( "3rd selection", "1", form.getParameterValue( "choices" ) );
response.getLinks()[2].click();
assertEquals( "4th selection", "9", form.getParameterValue( "choices" ) );
assertMatchingSet( "Displayed options", new String[] { "red", "blue", "green", "azure" }, form.getOptions( "choices" ) );
response.getLinks()[3].click();
assertMatchingSet( "Modified options", new String[] { "orange", "blue", "green", "azure" }, form.getOptions( "choices" ) );
response.getLinks()[4].click();
assertEquals( "5th selection", "7", form.getParameterValue( "choices" ) );
}
public void testFormSelectOverwriteOptions() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function rewriteSelect( the_select ) { \n" +
" the_select.options[0] = new Option( 'apache', 'a' );\n" +
" the_select.options[1] = new Option( 'comanche', 'c' );\n" +
" the_select.options[2] = new Option( 'sioux', 'x' );\n" +
" the_select.options[3] = new Option( 'iriquois', 'q' );\n" +
"}\n" +
"</script></head>" +
"<body>" +
"<form name='the_form'>" +
" <select name='choices'>" +
" <option value='1'>red" +
" <option value='2'>yellow" +
" <option value='3' selected>blue" +
" <option value='5'>green" +
" </select>" +
"</form>" +
"<a href='#' onMouseOver='document.the_form.choices.options.length=3;'>shorter</a>" +
"<a href='#' onMouseOver='document.the_form.choices.options[1]=null;'>weed</a>" +
"<a href='#' onMouseOver='rewriteSelect( document.the_form.choices );'>replace</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
WebForm form = response.getFormWithName( "the_form" );
assertMatchingSet( "initial values", new String[] { "1", "2", "3", "5" }, form.getOptionValues( "choices" ) );
assertMatchingSet( "initial text", new String[] { "red", "yellow", "blue", "green" }, form.getOptions( "choices" ) );
response.getLinks()[0].mouseOver();
assertMatchingSet( "modified values", new String[] { "1", "2", "3" }, form.getOptionValues( "choices" ) );
assertMatchingSet( "modified text", new String[] { "red", "yellow", "blue" }, form.getOptions( "choices" ) );
response.getLinks()[1].mouseOver();
assertMatchingSet( "weeded values", new String[] { "1", "3" }, form.getOptionValues( "choices" ) );
assertMatchingSet( "weeded text", new String[] { "red", "blue" }, form.getOptions( "choices" ) );
response.getLinks()[2].mouseOver();
assertMatchingSet( "replaced values", new String[] { "a", "c", "x", "q" }, form.getOptionValues( "choices" ) );
assertMatchingSet( "replaced text", new String[] { "apache", "comanche", "sioux", "iriquois" }, form.getOptions( "choices" ) );
}
public void testAccessAcrossFrames() throws Exception {
defineResource( "First.html",
"<html><head><script language='JavaScript'>" +
"function accessOtherFrame() {" +
" top.frame2.document.testform.param1.value = 'new1';" +
" window.alert('value: ' + top.frame2.document.testform.param1.value);" +
"}" +
"</script><body onload='accessOtherFrame();'>" +
"</body></html>" );
defineWebPage( "Second", "<form method=post name=testform action='http://trinity/dummy'>" +
" <input type=hidden name='param1' value='old1'></form>" );
defineResource( "Frames.html",
"<html><head><title>Initial</title></head>" +
"<frameset cols=\"20%,80%\">" +
" <frame src='First.html' name='frame1'>" +
" <frame src='Second.html' name='frame2'>" +
"</frameset></html>" );
WebConversation wc = new WebConversation();
wc.getResponse( getHostPath() + "/Frames.html" );
assertEquals( "Alert message", "value: new1", wc.popNextAlert() );
}
public void testSetFromEmbeddedScript() throws Exception {
defineWebPage( "OnCommand", "<form name=\"testform\">" +
"<input type=text name=\"testfield\" value=\"old\">" +
"</form>" +
"<script language=\"JavaScript\">" +
" document.testform.testfield.value=\"new\"" +
"</script>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
assertEquals( "Form parameter value", "new", response.getForms()[0].getParameterValue( "testfield") );
}
public void testSubmitFromJavaScriptLink() throws Exception {
defineResource( "test2.txt?Submit=Submit", "You made it!", "text/plain" );
defineWebPage( "OnCommand", "<form name='myform' action='test2.txt'>" +
" <input type='submit' id='btn' name='Submit' value='Submit'/>" +
" <a href='javascript:document.myform.btn.click();'>Link</a>" +
"</form>" );
WebConversation wc = new WebConversation();
WebResponse wr = wc.getResponse( getHostPath() + "/OnCommand.html" );
wr.getLinkWith( "Link" ).click();
}
public void testSubmitOnLoad() throws Exception {
defineResource( "test2.txt?Submit=Submit", "You made it!", "text/plain" );
defineResource( "OnCommand.html", "<html><body onload='document.myform.btn.click();'>" +
"<form name='myform' action='test2.txt'>" +
" <input type='submit' id='btn' name='Submit' value='Submit'/>" +
"</form></body></html>" );
WebConversation wc = new WebConversation();
WebResponse wr = wc.getResponse( getHostPath() + "/OnCommand.html" );
assertEquals( "current page URL", getHostPath() + "/test2.txt?Submit=Submit", wc.getCurrentPage().getURL().toExternalForm() );
assertEquals( "current page", "You made it!", wc.getCurrentPage().getText() );
assertEquals( "returned page URL", getHostPath() + "/test2.txt?Submit=Submit", wr.getURL().toExternalForm() );
assertEquals( "returned page", "You made it!", wr.getText() );
}
public void testSelectValueProperty() throws Exception {
defineResource( "OnCommand.html", "<html><head><script language='JavaScript'>" +
"function testProperty( form ) {\n" +
" elements = form.choices;\n" +
" alert( 'selected item is ' + elements.value );\n" +
"}" +
"</script></head>" +
"<body>" +
"<form name='the_form'>" +
" <select name='choices'>" +
" <option>red" +
" <option selected>blue" +
" </select>" +
"</form>" +
"<a href='#' onClick='testProperty( document.the_form )'>elements</a>" +
"</body></html>" );
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/OnCommand.html" );
response.getLinks()[0].click();
assertEquals( "Message 1", "selected item is blue", wc.popNextAlert() );
response.getScriptingHandler().doEventScript( "document.the_form.choices.value='red'" );
response.getLinks()[0].click();
assertEquals( "Message 2", "selected item is red", wc.popNextAlert() );
}
public void testElementsByIDProperty() throws Exception {
defineResource( "index.html", "<html>\n" +
"<head>\n" +
"<title>JavaScript Form Elements by ID String Test</title>\n" +
"<script language='JavaScript' type='text/javascript'><!--\n" +
"function foo() {\n" +
" if (document.forms['formName']) {\n" +
" var form = document.forms['formName'];\n" +
" if (form.elements['inputID']) {\n" +
" form.elements['inputID'].value = 'Hello World!';\n" +
" }\n" +
" }\n" +
"}\n" +
"// --></script>\n" +
"</head>\n" +
"<body onLoad='foo();'>\n" +
"<h1>JavaScript Form Elements by ID String Test</h1>\n" +
"<form name='formName'>\n" +
" <input type='text' name='inputName' value='' id='inputID'>\n" +
"</form>\n" +
"</body>\n" +
"</html>\n"
);
WebConversation wc = new WebConversation();
WebResponse response = wc.getResponse( getHostPath() + "/index.html" );
WebForm form = response.getFormWithName( "formName" );
assertEquals( "Changed value", "Hello World!", form.getParameterValue( "inputName" ) );
}
/**
* Test that JavaScript can correctly access the 'type' property for every kind of form control.
* @throws Exception
*/
public void testElementTypeAccess() throws Exception {
defineWebPage( "Default", "<script language=JavaScript>\n" +
"function CheckForm() {\n" +
" var len = document.myForm.elements.length;\n" +
" for (var index = 0; index < len; index++) {\n" +
" var control = document.myForm.elements[index];\n" +
" confirm(control.type);\n" +
" }\n" +
" return true;\n" +
"}\n" +
"</script>" +
"<form name=myForm method=POST>" +
" <input type=\"text\" name=\"textfield\">" +
" <textarea name=\"textarea\"></textarea>" +
" <input type=\"password\" name=\"password\">" +
" <input type=\"submit\" name=\"submit\" value=\"Submit\" onClick=\"return Check()\">" +
" <input type=\"reset\" name=\"reset\" value=\"Reset\">" +
" <input type=\"button\" name=\"button\" value=\"Button\">" +
" <input type=\"checkbox\" name=\"checkbox\" value=\"checkbox\">" +
" <input type=\"radio\" name=\"radiobutton\" value=\"radiobutton\">" +
" <select name=\"select\">" +
" <option value=\"1\">One</option>" +
" <option value=\"2\">Two</option>" +
" </select>" +
" <select name=\"select2\" size=\"2\" multiple>" +
" <option value=\"1\">One</option>" +
" <option value=\"2\">Two</option>" +
" </select>" +
" <input type=\"file\" name=\"fileField\">" +
" <input type=\"image\" name=\"imageField\" src=\"img.gif\">" +
" <input type=\"hidden\" name=\"hiddenField\">" +
" <button name=\"html4-button\" type=\"button\">html4-button</button>" +
" <button name=\"html4-submit\" type=\"submit\">html4-submit</button>" +
" <button name=\"html4-reset\" type=\"reset\">html4-reset</button>" +
" <button name=\"html4-default\">html4-default</button>" +
"</form>" +
"<script language=JavaScript>\n" +
" CheckForm();\n" +
"</script>\n");
String[] expectedTypes = new String[]{
"text", "textarea", "password", "submit", "reset", "button",
"checkbox", "radio", "select-one", "select-multiple", "file",
"image", "hidden", "button", "submit", "reset", "submit"
};
final PromptCollector collector = new PromptCollector();
WebConversation wc = new WebConversation();
wc.setDialogResponder(collector);
wc.getResponse( getHostPath() + "/Default.html" );
assertMatchingSet("Set of types on form", expectedTypes, collector.confirmPromptsSeen.toArray());
}
static class PromptCollector implements DialogResponder {
public List confirmPromptsSeen = new ArrayList();
public List responsePromptSeen = new ArrayList();
public boolean getConfirmation(String confirmationPrompt) {
confirmPromptsSeen.add(confirmationPrompt);
return true;
}
public String getUserResponse(String prompt, String defaultResponse) {
responsePromptSeen.add(prompt);
return null;
}
}
/**
* Test that the length (number of controls) of a form can be accessed from JavaScript.
* @throws Exception
*/
public void testFormLength () throws Exception {
defineWebPage("Default", "<script language=JavaScript>\n" +
"function CheckForm()\n"+
"{\n"+
"confirm (document.myForm.length);\n" +
"return true;\n" +
"}\n" +
"</script>" +
"<form name=myForm method=POST>" +
" <input type=\"text\" name=\"first_name\" value=\"Fred\">" +
" <input type=\"text\" name=\"last_name\" value=\"Bloggs\">" +
"</form>" +
"<script language=JavaScript>\n" +
" CheckForm();\n" +
"</script>\n");
String[] expectedPrompts = new String[]{"2"};
final PromptCollector collector = new PromptCollector();
WebConversation wc = new WebConversation();
wc.setDialogResponder(collector);
wc.getResponse( getHostPath() + "/Default.html" );
assertMatchingSet("Length of form", expectedPrompts, collector.confirmPromptsSeen.toArray());
}
/**
* Test that the JavaScript 'value' and 'defaultValue' properties of a text input are distinct.
* 'defaultValue' should represent the 'value' attribute of the input element.
* 'value' should initially match 'defaultValue', but setting it should not affect the 'defaultValue'.
* @throws Exception
*/
public void testElementDefaultValue () throws Exception {
defineWebPage("Default", "<script language=JavaScript>\n" +
"function CheckForm()\n"+
"{\n"+
"var i;\n" +
"var form_length=document.myForm.elements.length;\n" +
"for ( i=0 ; i< form_length; i++ )\n" +
"{\n"+
" confirm (document.myForm.elements[i].value);\n " +
"}\n"+
"document.myForm.elements[2].value = \"Charles\"\n" +
"for ( i=0 ; i< form_length; i++ )\n" +
"{\n"+
" confirm (document.myForm.elements[i].defaultValue);\n " +
"}\n"+
"confirm(document.myForm.elements[2].value);\n" +
"return true;\n" +
"}\n" +
"</script>" +
"<form name=myForm method=POST>" +
" <input type=\"text\" name=\"first_name\" value=\"Alpha\">" +
" <input type=\"text\" name=\"last_name\" value=\"Bravo\">" +
" <input type=\"text\" name=\"last_name\" value=\"Charlie\">" +
"</form>" +
"<script language=JavaScript>\n" +
" CheckForm();\n" +
"</script>\n");
String[] expectedValues = new String[]{"Alpha", "Bravo", "Charlie", "Alpha", "Bravo", "Charlie", "Charles"};
final PromptCollector collector = new PromptCollector();
WebConversation wc = new WebConversation();
wc.setDialogResponder(collector);
wc.getResponse( getHostPath() + "/Default.html" );
assertMatchingSet("Values seen by JavaScript", expectedValues, collector.confirmPromptsSeen.toArray());
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
b6bbd1afb609958f49208caa7b40dad942bdfa43 | db27e4af6fb3f7993b868e4d1ea007d3f343cc01 | /NettyDemo/src/main/java/com/baizhi/demo02/client/ClientChannelInitializer.java | daff1584cd4509c36fa1015302b768db5b68dfea | [] | no_license | 008aodi/testGit | 4448196ddf13ad1e0d2b1e4a606898f20f9ec2a3 | 047d0a90b9cbffb526b12ff461b75e2387f87c78 | refs/heads/master | 2022-12-21T23:15:44.045420 | 2019-04-12T07:21:56 | 2019-04-12T07:21:56 | 179,464,433 | 0 | 0 | null | 2022-12-16T08:18:07 | 2019-04-04T09:19:44 | CSS | UTF-8 | Java | false | false | 1,118 | java | package com.baizhi.demo02.client;
import com.baizhi.demo02.common.CustomMessageToMessageDecoder;
import com.baizhi.demo02.common.CustomMessageToMessageEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
//添加数据帧解码器
pipeline.addLast(new LengthFieldBasedFrameDecoder(65535,0,2,0,2));
//添加对象帧编码器
pipeline.addLast(new LengthFieldPrepender(2));
//添加对象解码器
pipeline.addLast(new CustomMessageToMessageDecoder());
//添加对象编码器
pipeline.addLast(new CustomMessageToMessageEncoder());
//添加最终处理者
pipeline.addLast(new ClientChannelHandlerAdapter());
}
}
| [
"008aodi@163.com"
] | 008aodi@163.com |
9949091243fde52595a1976edd7c3fc1a773e758 | f404f7198c91a0f91ed6d6dd0a1cda9adf3edbb1 | /com/planet_ink/coffee_mud/Abilities/Druid/Chant_GiveLife.java | 1d622baccb852d2b7d2dc35f348f6f06ebcbb1f8 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bbailey/ewok | 1f1d35b219a6ebd33fd3ad3d245383d075ef457d | b4fcf4ba90c7460b19d0af56a3ecabbc88470f6f | refs/heads/master | 2020-04-05T08:27:05.904034 | 2017-02-01T04:14:19 | 2017-02-01T04:14:19 | 656,100 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,757 | java | package com.planet_ink.coffee_mud.Abilities.Druid;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2014-2016 Bo Zimmerman
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.
*/
public class Chant_GiveLife extends Chant
{
@Override public String ID() { return "Chant_GiveLife"; }
private final static String localizedName = CMLib.lang().L("Give Life");
@Override public String name() { return localizedName; }
@Override public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_ANIMALAFFINITY;}
@Override protected int canAffectCode(){return 0;}
@Override protected int canTargetCode(){return Ability.CAN_MOBS;}
@Override public int abstractQuality(){ return Ability.QUALITY_OK_OTHERS;}
@Override public long flags(){return Ability.FLAG_NOORDERING;}
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
int amount=100;
if(!auto)
{
if((commands.size()==0)||(!CMath.isNumber(commands.get(commands.size()-1))))
{
mob.tell(L("Give how much life experience?"));
return false;
}
amount=CMath.s_int(commands.get(commands.size()-1));
if((amount<=0)||((amount>mob.getExperience())
&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.EXPERIENCE))
&&!mob.charStats().getCurrentClass().expless()
&&!mob.charStats().getMyRace().expless()))
{
mob.tell(L("You cannot give @x1 life experience.",""+amount));
return false;
}
commands.remove(commands.size()-1);
}
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if((!CMLib.flags().isAnimalIntelligence(target))||(!target.isMonster())||(!mob.getGroupMembers(new HashSet<MOB>()).contains(target)))
{
mob.tell(L("This chant only works on non-player animals in your group."));
return false;
}
if(mob.isMonster() && (!auto) && (givenTarget==null))
{
mob.tell(L("You cannot give your life."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),L(auto?"<T-NAME> gain(s) life experience!":"^S<S-NAME> chant(s) to <T-NAMESELF>, feeding <T-HIM-HER> <S-HIS-HER> life experience.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
CMLib.leveler().postExperience(mob,null,null,-amount,false);
if((mob.phyStats().level()>target.phyStats().level())&&(target.isMonster()))
amount+=(mob.phyStats().level()-target.phyStats().level())
*(mob.phyStats().level()/10);
CMLib.leveler().postExperience(target,null,null,amount,false);
if((CMLib.dice().rollPercentage() < amount)
&&(target.isMonster())
&&(target.fetchEffect("Loyalty")==null)
&&(target.fetchEffect("Chant_BestowName")!=null)
&&(target.amFollowing()==mob)
&&(mob.playerStats()!=null)
&&(!mob.isMonster())
&&(CMLib.flags().flaggedAnyAffects(target, Ability.FLAG_CHARMING).size()==0))
{
Ability A=CMClass.getAbility("Loyalty");
A.setMiscText("NAME="+mob.Name());
A.setSavable(true);
target.addNonUninvokableEffect(A);
mob.tell(mob,target,null,L("<T-NAME> is now loyal to you."));
}
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> chants for <T-NAMESELF>, but nothing happens."));
// return whether it worked
return success;
}
}
| [
"nosanity79@gmail.com"
] | nosanity79@gmail.com |
2346f63f6406ba12e55964795389f5c87a4af2b7 | 87e8a0e5be2df9057a03259b691f564721c25444 | /app/src/androidTest/java/com/whinc/test/recyclerviewcomponent/ApplicationTest.java | 7bc27cc160c3e9630c30d1cadd20ce99e2020783 | [
"Apache-2.0"
] | permissive | whinc/recyclerview-component | 3c23693995d1b259c95ffb41f45469da98560455 | ad41ff513578cfec99b516db3a3cf058601c44d8 | refs/heads/master | 2021-01-10T02:16:27.507752 | 2016-01-05T07:57:40 | 2016-01-05T07:57:40 | 48,363,248 | 0 | 0 | Apache-2.0 | 2020-02-26T17:34:27 | 2015-12-21T09:34:37 | Java | UTF-8 | Java | false | false | 367 | java | package com.whinc.test.recyclerviewcomponent;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"xiaohui_hubei@163.com"
] | xiaohui_hubei@163.com |
a58cdc4d5fe0eff91187a0de650a1237012200cd | f6bb93a3dc13563c0f68410388099066da229b77 | /src/test/java/com/example/demo/SpringBoot13ApplicationTests.java | 68146301f2141e19c78e5d126b1501360fb7b281 | [] | no_license | jcblefler/springboot13 | 0decfc132c6d84c375a300bd04a204735c430862 | 00e92f5676604ca2d0781acdb2a04d4484381151 | refs/heads/master | 2020-04-29T04:05:43.544835 | 2019-03-15T14:57:28 | 2019-03-15T14:57:28 | 175,835,578 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 339 | java | package com.example.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot13ApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"GBTC408005UR@MC.MONTGOMERYCOLLEGE.EDU"
] | GBTC408005UR@MC.MONTGOMERYCOLLEGE.EDU |
d93e98ef0b308d4c55c67e74379b674cc7c20a28 | 06c7d0ffb03af1ce5432300fa5c969592d657a99 | /orders/src/main/java/org/orders/config/RestTemplateFactory.java | 6e54aae2510e94b7bb1e8818bc4c5f2dcec04888 | [] | no_license | manifoldfinance/atlas-engine | abe10efc82a4c6c9890eca365cddc3a3b985fed4 | 058d158f21c048855fd36c2725e02aae8286318f | refs/heads/master | 2023-02-10T15:54:38.546191 | 2021-01-09T10:51:37 | 2021-01-09T10:51:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 426 | java | package org.atlas.engine.financialexchange.orders.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateFactory {
@Bean(name = "restTemplate")
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate;
}
}
| [
"sam@freighttrust.com"
] | sam@freighttrust.com |
f69866d6fdaf353f33783d0c96cb311eaf145bc0 | 2d5123318db65ab3f2794f97b03d10d1b08b0a41 | /Back-End-SpringBoot/src/main/java/com/wastedTimeStudiyng/pojos/Subject.java | c4a736cb37957f92e349751b0acc190864dc6446 | [] | no_license | SantDani/Wasted-Time-Studiying | 6a719b1a4a406a875790c47b2c24fe48cb624731 | dbc5d91dd4dab0ddbc5635a9aea164a4f5c89b06 | refs/heads/master | 2020-04-21T08:57:29.106917 | 2019-02-21T09:16:29 | 2019-02-21T09:16:29 | 169,434,399 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,275 | java | package com.wastedTimeStudiyng.pojos;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="subjects")
public class Subject {
public enum Difficulty{
EASY,
MEDIUM,
HARD,
RIP
}
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
@Enumerated(EnumType.STRING)
private Difficulty difficulty;
@ManyToOne
@JoinColumn(name="id_student")
private Student student;
public Subject() {
}
public Subject(int id, String name, Difficulty difficulty, Student student) {
super();
this.id = id;
this.name = name;
this.difficulty = difficulty;
this.student = student;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Difficulty getDifficulty() {
return difficulty;
}
public void setDifficulty(Difficulty difficulty) {
this.difficulty = difficulty;
}
}
| [
"s3rg10.martinez.roman@gmail.com"
] | s3rg10.martinez.roman@gmail.com |
3aceed182eff871b7a21ffb79b411281af2f9cf3 | b79a9ab661d8731dc86ba7565a806f7b8a66cc3e | /src/main/java/com/niche/ng/repository/CoverFillingDetailsRepository.java | 3745d31686cf31eb7f2bf73e2e4a91e775f1fd36 | [] | no_license | RRanjitha/projectgh | f08d962a917a9c92ca5a5cea23292110479c7f15 | a437a770b4fddb04e41b9e00cf7e0fa59f53ac13 | refs/heads/master | 2020-03-30T11:55:44.385866 | 2018-10-02T05:23:13 | 2018-10-02T05:23:13 | 150,845,304 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 538 | java | package com.niche.ng.repository;
import com.niche.ng.domain.CoverFillingDetails;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Spring Data repository for the CoverFillingDetails entity.
*/
@SuppressWarnings("unused")
@Repository
public interface CoverFillingDetailsRepository extends JpaRepository<CoverFillingDetails, Long>, JpaSpecificationExecutor<CoverFillingDetails> {
List<CoverFillingDetails> findByCoverFillingId(Long coverFillingId);
}
| [
"ranji.cs016@gmail.com"
] | ranji.cs016@gmail.com |
6dbde16a93c01e2f25227b8aac1712c57a1bf545 | fde1ae072046e6565b5238c37258109caba678fb | /lso.Android/obj/Debug/android/src/crc64ef8b66e166c17e87/MediaServiceConnection_1.java | 9b7f59446ecc7f063db01c7f1a5a994824860850 | [] | no_license | ahmidimohamed12/vlciptv | 46eb3fac3e9270d0af70415dc69612e365c1983f | 845e3481c698f6e33d7a356b0a897a81c42f709e | refs/heads/master | 2022-11-30T17:53:23.994670 | 2020-08-10T23:46:34 | 2020-08-10T23:46:34 | 286,601,031 | 0 | 0 | null | 2020-08-10T23:48:46 | 2020-08-10T23:42:43 | C++ | UTF-8 | Java | false | false | 1,900 | java | package crc64ef8b66e166c17e87;
public class MediaServiceConnection_1
extends java.lang.Object
implements
mono.android.IGCUserPeer,
android.content.ServiceConnection
{
/** @hide */
public static final String __md_methods;
static {
__md_methods =
"n_onServiceConnected:(Landroid/content/ComponentName;Landroid/os/IBinder;)V:GetOnServiceConnected_Landroid_content_ComponentName_Landroid_os_IBinder_Handler:Android.Content.IServiceConnectionInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" +
"n_onServiceDisconnected:(Landroid/content/ComponentName;)V:GetOnServiceDisconnected_Landroid_content_ComponentName_Handler:Android.Content.IServiceConnectionInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" +
"";
mono.android.Runtime.register ("Plugin.MediaManager.MediaServiceConnection`1, Plugin.MediaManager", MediaServiceConnection_1.class, __md_methods);
}
public MediaServiceConnection_1 ()
{
super ();
if (getClass () == MediaServiceConnection_1.class)
mono.android.TypeManager.Activate ("Plugin.MediaManager.MediaServiceConnection`1, Plugin.MediaManager", "", this, new java.lang.Object[] { });
}
public void onServiceConnected (android.content.ComponentName p0, android.os.IBinder p1)
{
n_onServiceConnected (p0, p1);
}
private native void n_onServiceConnected (android.content.ComponentName p0, android.os.IBinder p1);
public void onServiceDisconnected (android.content.ComponentName p0)
{
n_onServiceDisconnected (p0);
}
private native void n_onServiceDisconnected (android.content.ComponentName p0);
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
| [
"ahmidinador123@gmail.com"
] | ahmidinador123@gmail.com |
955394141253124f45d432bf6f28480f5e18e360 | 1c052d32fe190522679b597110bdc773d6a10c31 | /SleepingProblemCode/CustomerGenerator.java | 4f5dc88246b4dc9d99acfd17160f3c5e3949009a | [] | no_license | rohittoshniwal13/SleepingBarberJava | 24e8ad49372212edd8c4f1e90d0c485b5bbe3bb7 | 62077aabe2d2df0a0727385a45b86a66552172ea | refs/heads/master | 2022-07-24T20:35:19.528823 | 2020-05-17T10:18:19 | 2020-05-17T10:18:19 | 264,635,288 | 0 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,196 | java | package SleepingProblem;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;
class CustomerGenerator implements Runnable
{
Bshop shop;
int noOfCust;
public CustomerGenerator(Bshop shop, int noOfCust)
{
this.shop = shop;
this.noOfCust=noOfCust;
}
public void run()
{
double[] listCustomer = new double[noOfCust];
double mean = 15, std = 3;
Random ran = new Random();
Customer customer = new Customer(shop);
for(int i=0;i<noOfCust;i++)
{
customer.setInTime(new Date());
Thread thcustomer = new Thread(customer);
listCustomer[i] = Math.round((mean + std*ran.nextGaussian())*100.0/100.0);
customer.setName("Customer Thread "+thcustomer.getId());
thcustomer.start();
try
{
TimeUnit.SECONDS.sleep((long)listCustomer[i]);
}
catch(InterruptedException iex)
{
iex.printStackTrace();
}
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
2577827f5506acc024e9be6c4541dac357b69f5e | c6243efabe497f485e08aa0e0d0e29695657e41b | /Android/lib-asmack/org/jivesoftware/smackx/muc/MultiUserChat.java | 8277d8255883451df7cf7a1cc5d2e1e5725b596f | [] | no_license | sxj84877171/linknsync | f7cfc1bdd0ea84a9e053dd0458aa4a17d6a1379e | 112521f6f58804b42be0680701f85daeb12e330c | refs/heads/master | 2021-01-10T03:12:58.423559 | 2016-01-29T11:07:58 | 2016-01-29T11:07:58 | 50,657,537 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 125,424 | java | /**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright 2003-2007 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.muc;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.PacketInterceptor;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromMatchesFilter;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketExtensionFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.NodeInformationProvider;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.packet.DiscoverItems;
import org.jivesoftware.smackx.packet.MUCAdmin;
import org.jivesoftware.smackx.packet.MUCInitialPresence;
import org.jivesoftware.smackx.packet.MUCOwner;
import org.jivesoftware.smackx.packet.MUCUser;
import android.text.TextUtils;
/**
* A MultiUserChat is a conversation that takes place among many users in a virtual
* room. A room could have many occupants with different affiliation and roles.
* Possible affiliatons are "owner", "admin", "member", and "outcast". Possible roles
* are "moderator", "participant", and "visitor". Each role and affiliation guarantees
* different privileges (e.g. Send messages to all occupants, Kick participants and visitors,
* Grant voice, Edit member list, etc.).
*
* @author Gaston Dombiak, Larry Kirschner
*/
public class MultiUserChat {
private final static String discoNamespace = "http://jabber.org/protocol/muc";
private final static String discoNode = "http://jabber.org/protocol/muc#rooms";
private static Map<Connection, List<String>> joinedRooms =
new WeakHashMap<Connection, List<String>>();
private Connection connection;
private String room;
private String subject;
private String nickname = null;
private boolean joined = false;
private Map<String, Presence> occupantsMap = new ConcurrentHashMap<String, Presence>();
private Map<String, MUCUser.Item> mucUserItems = new ConcurrentHashMap<String, MUCUser.Item>();
private final List<InvitationRejectionListener> invitationRejectionListeners =
new ArrayList<InvitationRejectionListener>();
private final List<SubjectUpdatedListener> subjectUpdatedListeners =
new ArrayList<SubjectUpdatedListener>();
private final List<UserStatusListener> userStatusListeners =
new ArrayList<UserStatusListener>();
private final List<ParticipantStatusListener> participantStatusListeners =
new ArrayList<ParticipantStatusListener>();
private PacketFilter presenceFilter;
private List<PacketInterceptor> presenceInterceptors = new ArrayList<PacketInterceptor>();
private PacketFilter messageFilter;
private RoomListenerMultiplexor roomListenerMultiplexor;
private ConnectionDetachedPacketCollector messageCollector;
private List<PacketListener> connectionListeners = new ArrayList<PacketListener>();
static {
Connection.addConnectionCreationListener(new ConnectionCreationListener() {
public void connectionCreated(final Connection connection) {
try {
// Set on every established connection that this client supports the Multi-User
// Chat protocol. This information will be used when another client tries to
// discover whether this client supports MUC or not.
ServiceDiscoveryManager.getInstanceFor(connection).addFeature(discoNamespace);
// Set the NodeInformationProvider that will provide information about the
// joined rooms whenever a disco request is received
ServiceDiscoveryManager.getInstanceFor(connection).setNodeInformationProvider(
discoNode,
new NodeInformationProvider() {
public List<DiscoverItems.Item> getNodeItems() {
List<DiscoverItems.Item> answer = new ArrayList<DiscoverItems.Item>();
Iterator<String> rooms=MultiUserChat.getJoinedRooms(connection);
while (rooms.hasNext()) {
answer.add(new DiscoverItems.Item(rooms.next()));
}
return answer;
}
public List<String> getNodeFeatures() {
return null;
}
public List<DiscoverInfo.Identity> getNodeIdentities() {
return null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Creates a new multi user chat with the specified connection and room name. Note: no
* information is sent to or received from the server until you attempt to
* {@link #join(String) join} the chat room. On some server implementations,
* the room will not be created until the first person joins it.<p>
*
* Most XMPP servers use a sub-domain for the chat service (eg chat.example.com
* for the XMPP server example.com). You must ensure that the room address you're
* trying to connect to includes the proper chat sub-domain.
*
* @param connection the XMPP connection.
* @param room the name of the room in the form "roomName@service", where
* "service" is the hostname at which the multi-user chat
* service is running. Make sure to provide a valid JID.
*/
public MultiUserChat(Connection connection, String room) {
this.connection = connection;
this.room = room.toLowerCase();
init();
}
/**
* Returns true if the specified user supports the Multi-User Chat protocol.
*
* @param connection the connection to use to perform the service discovery.
* @param user the user to check. A fully qualified xmpp ID, e.g. jdoe@example.com.
* @return a boolean indicating whether the specified user supports the MUC protocol.
*/
public static boolean isServiceEnabled(Connection connection, String user) {
try {
DiscoverInfo result =
ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(user);
return result.containsFeature(discoNamespace);
}
catch (XMPPException e) {
e.printStackTrace();
return false;
}
}
/**
* Returns an Iterator on the rooms where the user has joined using a given connection.
* The Iterator will contain Strings where each String represents a room
* (e.g. room@muc.jabber.org).
*
* @param connection the connection used to join the rooms.
* @return an Iterator on the rooms where the user has joined using a given connection.
*/
private static Iterator<String> getJoinedRooms(Connection connection) {
List<String> rooms = joinedRooms.get(connection);
if (rooms != null) {
return rooms.iterator();
}
// Return an iterator on an empty collection (i.e. the user never joined a room)
return new ArrayList<String>().iterator();
}
/**
* Returns an Iterator on the rooms where the requested user has joined. The Iterator will
* contain Strings where each String represents a room (e.g. room@muc.jabber.org).
*
* @param connection the connection to use to perform the service discovery.
* @param user the user to check. A fully qualified xmpp ID, e.g. jdoe@example.com.
* @return an Iterator on the rooms where the requested user has joined.
*/
public static Iterator<String> getJoinedRooms(Connection connection, String user) {
try {
ArrayList<String> answer = new ArrayList<String>();
// Send the disco packet to the user
DiscoverItems result =
ServiceDiscoveryManager.getInstanceFor(connection).discoverItems(user, discoNode);
// Collect the entityID for each returned item
for (Iterator<DiscoverItems.Item> items=result.getItems(); items.hasNext();) {
answer.add(items.next().getEntityID());
}
return answer.iterator();
}
catch (XMPPException e) {
e.printStackTrace();
// Return an iterator on an empty collection
return new ArrayList<String>().iterator();
}
}
/**
* Returns the discovered information of a given room without actually having to join the room.
* The server will provide information only for rooms that are public.
*
* @param connection the XMPP connection to use for discovering information about the room.
* @param room the name of the room in the form "roomName@service" of which we want to discover
* its information.
* @return the discovered information of a given room without actually having to join the room.
* @throws XMPPException if an error occured while trying to discover information of a room.
*/
public static RoomInfo getRoomInfo(Connection connection, String room)
throws XMPPException {
DiscoverInfo info = ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(room);
return new RoomInfo(info);
}
/**
* Returns a collection with the XMPP addresses of the Multi-User Chat services.
*
* @param connection the XMPP connection to use for discovering Multi-User Chat services.
* @return a collection with the XMPP addresses of the Multi-User Chat services.
* @throws XMPPException if an error occured while trying to discover MUC services.
*/
public static Collection<String> getServiceNames(Connection connection) throws XMPPException {
final List<String> answer = new ArrayList<String>();
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
DiscoverItems items = discoManager.discoverItems(connection.getServiceName());
for (Iterator<DiscoverItems.Item> it = items.getItems(); it.hasNext();) {
DiscoverItems.Item item = it.next();
try {
DiscoverInfo info = discoManager.discoverInfo(item.getEntityID());
if (info.containsFeature("http://jabber.org/protocol/muc")) {
answer.add(item.getEntityID());
}
}
catch (XMPPException e) {
// Trouble finding info in some cases. This is a workaround for
// discovering info on remote servers.
}
}
return answer;
}
/**
* Returns a collection of HostedRooms where each HostedRoom has the XMPP address of the room
* and the room's name. Once discovered the rooms hosted by a chat service it is possible to
* discover more detailed room information or join the room.
*
* @param connection the XMPP connection to use for discovering hosted rooms by the MUC service.
* @param serviceName the service that is hosting the rooms to discover.
* @return a collection of HostedRooms.
* @throws XMPPException if an error occured while trying to discover the information.
*/
public static Collection<HostedRoom> getHostedRooms(Connection connection, String serviceName)
throws XMPPException {
List<HostedRoom> answer = new ArrayList<HostedRoom>();
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
DiscoverItems items = discoManager.discoverItems(serviceName);
for (Iterator<DiscoverItems.Item> it = items.getItems(); it.hasNext();) {
answer.add(new HostedRoom(it.next()));
}
return answer;
}
/**
* Returns the name of the room this MultiUserChat object represents.
*
* @return the multi user chat room name.
*/
public String getRoom() {
return room;
}
/**
* Creates the room according to some default configuration, assign the requesting user
* as the room owner, and add the owner to the room but not allow anyone else to enter
* the room (effectively "locking" the room). The requesting user will join the room
* under the specified nickname as soon as the room has been created.<p>
*
* To create an "Instant Room", that means a room with some default configuration that is
* available for immediate access, the room's owner should send an empty form after creating
* the room. {@link #sendConfigurationForm(Form)}<p>
*
* To create a "Reserved Room", that means a room manually configured by the room creator
* before anyone is allowed to enter, the room's owner should complete and send a form after
* creating the room. Once the completed configutation form is sent to the server, the server
* will unlock the room. {@link #sendConfigurationForm(Form)}
*
* @param nickname the nickname to use.
* @throws XMPPException if the room couldn't be created for some reason
* (e.g. room already exists; user already joined to an existant room or
* 405 error if the user is not allowed to create the room)
*/
public synchronized void create(String nickname) throws XMPPException {
if (nickname == null || nickname.equals("")) {
throw new IllegalArgumentException("Nickname must not be null or blank.");
}
// If we've already joined the room, leave it before joining under a new
// nickname.
if (joined) {
throw new IllegalStateException("Creation failed - User already joined the room.");
}
// We create a room by sending a presence packet to room@service/nick
// and signal support for MUC. The owner will be automatically logged into the room.
Presence joinPresence = new Presence(Presence.Type.available);
joinPresence.setTo(room + "/" + nickname);
// Indicate the the client supports MUC
joinPresence.addExtension(new MUCInitialPresence());
// Invoke presence interceptors so that extra information can be dynamically added
for (PacketInterceptor packetInterceptor : presenceInterceptors) {
packetInterceptor.interceptPacket(joinPresence);
}
// Wait for a presence packet back from the server.
PacketFilter responseFilter =
new AndFilter(
new FromMatchesFilter(room + "/" + nickname),
new PacketTypeFilter(Presence.class));
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send create & join packet.
System.out.println("req:"+joinPresence.toXML());
connection.sendPacket(joinPresence);
// Wait up to a certain number of seconds for a reply.
Presence presence =
(Presence) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (presence == null) {
throw new XMPPException("No response from server.");
}
else if (presence.getError() != null) {
throw new XMPPException(presence.getError());
}
// Whether the room existed before or was created, the user has joined the room
this.nickname = nickname;
joined = true;
userHasJoined();
// Look for confirmation of room creation from the server
MUCUser mucUser = getMUCUserExtension(presence);
if (mucUser != null && mucUser.getStatus() != null) {
if ("201".equals(mucUser.getStatus().getCode())) {
// Room was created and the user has joined the room
return;
}
}
// We need to leave the room since it seems that the room already existed
leave();
throw new XMPPException("Creation failed - Missing acknowledge of room creation.");
}
/**
* Joins the chat room using the specified nickname. If already joined
* using another nickname, this method will first leave the room and then
* re-join using the new nickname. The default timeout of Smack for a reply
* from the group chat server that the join succeeded will be used. After
* joining the room, the room will decide the amount of history to send.
*
* @param nickname the nickname to use.
* @throws XMPPException if an error occurs joining the room. In particular, a
* 401 error can occur if no password was provided and one is required; or a
* 403 error can occur if the user is banned; or a
* 404 error can occur if the room does not exist or is locked; or a
* 407 error can occur if user is not on the member list; or a
* 409 error can occur if someone is already in the group chat with the same nickname.
*/
public void join(String nickname) throws XMPPException {
join(nickname, null, null, SmackConfiguration.getPacketReplyTimeout());
}
/**
* Joins the chat room using the specified nickname and password. If already joined
* using another nickname, this method will first leave the room and then
* re-join using the new nickname. The default timeout of Smack for a reply
* from the group chat server that the join succeeded will be used. After
* joining the room, the room will decide the amount of history to send.<p>
*
* A password is required when joining password protected rooms. If the room does
* not require a password there is no need to provide one.
*
* @param nickname the nickname to use.
* @param password the password to use.
* @throws XMPPException if an error occurs joining the room. In particular, a
* 401 error can occur if no password was provided and one is required; or a
* 403 error can occur if the user is banned; or a
* 404 error can occur if the room does not exist or is locked; or a
* 407 error can occur if user is not on the member list; or a
* 409 error can occur if someone is already in the group chat with the same nickname.
*/
public void join(String nickname, String password) throws XMPPException {
join(nickname, password, null, SmackConfiguration.getPacketReplyTimeout());
}
/**
* Joins the chat room using the specified nickname and password. If already joined
* using another nickname, this method will first leave the room and then
* re-join using the new nickname.<p>
*
* To control the amount of history to receive while joining a room you will need to provide
* a configured DiscussionHistory object.<p>
*
* A password is required when joining password protected rooms. If the room does
* not require a password there is no need to provide one.<p>
*
* If the room does not already exist when the user seeks to enter it, the server will
* decide to create a new room or not.
*
* @param nickname the nickname to use.
* @param password the password to use.
* @param history the amount of discussion history to receive while joining a room.
* @param timeout the amount of time to wait for a reply from the MUC service(in milleseconds).
* @throws XMPPException if an error occurs joining the room. In particular, a
* 401 error can occur if no password was provided and one is required; or a
* 403 error can occur if the user is banned; or a
* 404 error can occur if the room does not exist or is locked; or a
* 407 error can occur if user is not on the member list; or a
* 409 error can occur if someone is already in the group chat with the same nickname.
*/
public synchronized void join(
String nickname,
String password,
DiscussionHistory history,
long timeout)
throws XMPPException {
if (nickname == null || nickname.equals("")) {
throw new IllegalArgumentException("Nickname must not be null or blank.");
}
// If we've already joined the room, leave it before joining under a new
// nickname.
if (joined) {
leave();
}
// We join a room by sending a presence packet where the "to"
// field is in the form "roomName@service/nickname"
Presence joinPresence = new Presence(Presence.Type.available);
joinPresence.setTo(room + "/" + nickname);
// Indicate the the client supports MUC
MUCInitialPresence mucInitialPresence = new MUCInitialPresence();
if (password != null) {
mucInitialPresence.setPassword(password);
}
if (history != null) {
mucInitialPresence.setHistory(history.getMUCHistory());
}
joinPresence.addExtension(mucInitialPresence);
// Invoke presence interceptors so that extra information can be dynamically added
for (PacketInterceptor packetInterceptor : presenceInterceptors) {
packetInterceptor.interceptPacket(joinPresence);
}
// Wait for a presence packet back from the server.
PacketFilter responseFilter =
new AndFilter(
new FromMatchesFilter(room + "/" + nickname),
new PacketTypeFilter(Presence.class));
PacketCollector response = null;
Presence presence;
try {
response = connection.createPacketCollector(responseFilter);
// Send join packet.
connection.sendPacket(joinPresence);
// Wait up to a certain number of seconds for a reply.
presence = (Presence) response.nextResult(timeout);
}
finally {
// Stop queuing results
if (response != null) {
response.cancel();
}
}
if (presence == null) {
throw new XMPPException("No response from server.");
}
else if (presence.getError() != null) {
throw new XMPPException(presence.getError());
}
this.nickname = nickname;
joined = true;
userHasJoined();
}
/**
* Returns true if currently in the multi user chat (after calling the {@link
* #join(String)} method).
*
* @return true if currently in the multi user chat room.
*/
public boolean isJoined() {
return joined;
}
/**
* Leave the chat room.
*/
public synchronized void leave() {
// If not joined already, do nothing.
if (!joined) {
return;
}
// We leave a room by sending a presence packet where the "to"
// field is in the form "roomName@service/nickname"
Presence leavePresence = new Presence(Presence.Type.unavailable);
leavePresence.setTo(room + "/" + nickname);
// Invoke presence interceptors so that extra information can be dynamically added
for (PacketInterceptor packetInterceptor : presenceInterceptors) {
packetInterceptor.interceptPacket(leavePresence);
}
connection.sendPacket(leavePresence);
// Reset occupant information.
occupantsMap.clear();
nickname = null;
joined = false;
userHasLeft();
}
/**
* Returns the room's configuration form that the room's owner can use or <tt>null</tt> if
* no configuration is possible. The configuration form allows to set the room's language,
* enable logging, specify room's type, etc..
*
* @return the Form that contains the fields to complete together with the instrucions or
* <tt>null</tt> if no configuration is possible.
* @throws XMPPException if an error occurs asking the configuration form for the room.
*/
public Form getConfigurationForm() throws XMPPException {
MUCOwner iq = new MUCOwner();
iq.setTo(room);
iq.setType(IQ.Type.GET);
// Filter packets looking for an answer from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Request the configuration form to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
return Form.getFormFrom(answer);
}
/**
* Sends the completed configuration form to the server. The room will be configured
* with the new settings defined in the form. If the form is empty then the server
* will create an instant room (will use default configuration).
*
* @param form the form with the new settings.
* @throws XMPPException if an error occurs setting the new rooms' configuration.
*/
public void sendConfigurationForm(Form form) throws XMPPException {
MUCOwner iq = new MUCOwner();
iq.setTo(room);
iq.setType(IQ.Type.SET);
iq.addExtension(form.getDataFormToSend());
// Filter packets looking for an answer from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the completed configuration form to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
}
/**
* Returns the room's registration form that an unaffiliated user, can use to become a member
* of the room or <tt>null</tt> if no registration is possible. Some rooms may restrict the
* privilege to register members and allow only room admins to add new members.<p>
*
* If the user requesting registration requirements is not allowed to register with the room
* (e.g. because that privilege has been restricted), the room will return a "Not Allowed"
* error to the user (error code 405).
*
* @return the registration Form that contains the fields to complete together with the
* instrucions or <tt>null</tt> if no registration is possible.
* @throws XMPPException if an error occurs asking the registration form for the room or a
* 405 error if the user is not allowed to register with the room.
*/
public Form getRegistrationForm() throws XMPPException {
Registration reg = new Registration();
reg.setType(IQ.Type.GET);
reg.setTo(room);
PacketFilter filter =
new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
PacketCollector collector = connection.createPacketCollector(filter);
connection.sendPacket(reg);
IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
collector.cancel();
if (result == null) {
throw new XMPPException("No response from server.");
}
else if (result.getType() == IQ.Type.ERROR) {
throw new XMPPException(result.getError());
}
return Form.getFormFrom(result);
}
/**
* Sends the completed registration form to the server. After the user successfully submits
* the form, the room may queue the request for review by the room admins or may immediately
* add the user to the member list by changing the user's affiliation from "none" to "member.<p>
*
* If the desired room nickname is already reserved for that room, the room will return a
* "Conflict" error to the user (error code 409). If the room does not support registration,
* it will return a "Service Unavailable" error to the user (error code 503).
*
* @param form the completed registration form.
* @throws XMPPException if an error occurs submitting the registration form. In particular, a
* 409 error can occur if the desired room nickname is already reserved for that room;
* or a 503 error can occur if the room does not support registration.
*/
public void sendRegistrationForm(Form form) throws XMPPException {
Registration reg = new Registration();
reg.setType(IQ.Type.SET);
reg.setTo(room);
reg.addExtension(form.getDataFormToSend());
PacketFilter filter =
new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
PacketCollector collector = connection.createPacketCollector(filter);
connection.sendPacket(reg);
IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
collector.cancel();
if (result == null) {
throw new XMPPException("No response from server.");
}
else if (result.getType() == IQ.Type.ERROR) {
throw new XMPPException(result.getError());
}
}
/**
* Sends a request to the server to destroy the room. The sender of the request
* should be the room's owner. If the sender of the destroy request is not the room's owner
* then the server will answer a "Forbidden" error (403).
*
* @param reason the reason for the room destruction.
* @param alternateJID the JID of an alternate location.
* @throws XMPPException if an error occurs while trying to destroy the room.
* An error can occur which will be wrapped by an XMPPException --
* XMPP error code 403. The error code can be used to present more
* appropiate error messages to end-users.
*/
public void destroy(String reason, String alternateJID) throws XMPPException {
MUCOwner iq = new MUCOwner();
iq.setTo(room);
iq.setType(IQ.Type.SET);
// Create the reason for the room destruction
MUCOwner.Destroy destroy = new MUCOwner.Destroy();
destroy.setReason(reason);
destroy.setJid(alternateJID);
iq.setDestroy(destroy);
// Wait for a presence packet back from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the room destruction request.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
// Reset occupant information.
occupantsMap.clear();
nickname = null;
joined = false;
userHasLeft();
}
/**
* Invites another user to the room in which one is an occupant. The invitation
* will be sent to the room which in turn will forward the invitation to the invitee.<p>
*
* If the room is password-protected, the invitee will receive a password to use to join
* the room. If the room is members-only, the the invitee may be added to the member list.
*
* @param user the user to invite to the room.(e.g. hecate@shakespeare.lit)
* @param reason the reason why the user is being invited.
*/
public void invite(String user, String reason) {
invite(new Message(), user, reason);
}
/**
* Invites another user to the room in which one is an occupant using a given Message. The invitation
* will be sent to the room which in turn will forward the invitation to the invitee.<p>
*
* If the room is password-protected, the invitee will receive a password to use to join
* the room. If the room is members-only, the the invitee may be added to the member list.
*
* @param message the message to use for sending the invitation.
* @param user the user to invite to the room.(e.g. hecate@shakespeare.lit)
* @param reason the reason why the user is being invited.
*/
public void invite(Message message, String user, String reason) {
// TODO listen for 404 error code when inviter supplies a non-existent JID
message.setTo(room);
// Create the MUCUser packet that will include the invitation
MUCUser mucUser = new MUCUser();
MUCUser.Invite invite = new MUCUser.Invite();
invite.setTo(user);
invite.setReason(reason);
mucUser.setInvite(invite);
// Add the MUCUser packet that includes the invitation to the message
message.addExtension(mucUser);
connection.sendPacket(message);
}
/**
* Informs the sender of an invitation that the invitee declines the invitation. The rejection
* will be sent to the room which in turn will forward the rejection to the inviter.
*
* @param conn the connection to use for sending the rejection.
* @param room the room that sent the original invitation.
* @param inviter the inviter of the declined invitation.
* @param reason the reason why the invitee is declining the invitation.
*/
public static void decline(Connection conn, String room, String inviter, String reason) {
Message message = new Message(room);
// Create the MUCUser packet that will include the rejection
MUCUser mucUser = new MUCUser();
MUCUser.Decline decline = new MUCUser.Decline();
decline.setTo(inviter);
decline.setReason(reason);
mucUser.setDecline(decline);
// Add the MUCUser packet that includes the rejection
message.addExtension(mucUser);
conn.sendPacket(message);
}
/**
* Adds a listener to invitation notifications. The listener will be fired anytime
* an invitation is received.
*
* @param conn the connection where the listener will be applied.
* @param listener an invitation listener.
*/
public static void addInvitationListener(Connection conn, InvitationListener listener) {
InvitationsMonitor.getInvitationsMonitor(conn).addInvitationListener(listener);
}
/**
* Removes a listener to invitation notifications. The listener will be fired anytime
* an invitation is received.
*
* @param conn the connection where the listener was applied.
* @param listener an invitation listener.
*/
public static void removeInvitationListener(Connection conn, InvitationListener listener) {
InvitationsMonitor.getInvitationsMonitor(conn).removeInvitationListener(listener);
}
/**
* Adds a listener to invitation rejections notifications. The listener will be fired anytime
* an invitation is declined.
*
* @param listener an invitation rejection listener.
*/
public void addInvitationRejectionListener(InvitationRejectionListener listener) {
synchronized (invitationRejectionListeners) {
if (!invitationRejectionListeners.contains(listener)) {
invitationRejectionListeners.add(listener);
}
}
}
/**
* Removes a listener from invitation rejections notifications. The listener will be fired
* anytime an invitation is declined.
*
* @param listener an invitation rejection listener.
*/
public void removeInvitationRejectionListener(InvitationRejectionListener listener) {
synchronized (invitationRejectionListeners) {
invitationRejectionListeners.remove(listener);
}
}
/**
* Fires invitation rejection listeners.
*
* @param invitee the user being invited.
* @param reason the reason for the rejection
*/
private void fireInvitationRejectionListeners(String invitee, String reason) {
InvitationRejectionListener[] listeners;
synchronized (invitationRejectionListeners) {
listeners = new InvitationRejectionListener[invitationRejectionListeners.size()];
invitationRejectionListeners.toArray(listeners);
}
for (InvitationRejectionListener listener : listeners) {
listener.invitationDeclined(invitee, reason);
}
}
/**
* Adds a listener to subject change notifications. The listener will be fired anytime
* the room's subject changes.
*
* @param listener a subject updated listener.
*/
public void addSubjectUpdatedListener(SubjectUpdatedListener listener) {
synchronized (subjectUpdatedListeners) {
if (!subjectUpdatedListeners.contains(listener)) {
subjectUpdatedListeners.add(listener);
}
}
}
/**
* Removes a listener from subject change notifications. The listener will be fired
* anytime the room's subject changes.
*
* @param listener a subject updated listener.
*/
public void removeSubjectUpdatedListener(SubjectUpdatedListener listener) {
synchronized (subjectUpdatedListeners) {
subjectUpdatedListeners.remove(listener);
}
}
/**
* Fires subject updated listeners.
*/
private void fireSubjectUpdatedListeners(String subject, String from) {
SubjectUpdatedListener[] listeners;
synchronized (subjectUpdatedListeners) {
listeners = new SubjectUpdatedListener[subjectUpdatedListeners.size()];
subjectUpdatedListeners.toArray(listeners);
}
for (SubjectUpdatedListener listener : listeners) {
listener.subjectUpdated(subject, from);
}
}
/**
* Adds a new {@link PacketInterceptor} that will be invoked every time a new presence
* is going to be sent by this MultiUserChat to the server. Packet interceptors may
* add new extensions to the presence that is going to be sent to the MUC service.
*
* @param presenceInterceptor the new packet interceptor that will intercept presence packets.
*/
public void addPresenceInterceptor(PacketInterceptor presenceInterceptor) {
presenceInterceptors.add(presenceInterceptor);
}
/**
* Removes a {@link PacketInterceptor} that was being invoked every time a new presence
* was being sent by this MultiUserChat to the server. Packet interceptors may
* add new extensions to the presence that is going to be sent to the MUC service.
*
* @param presenceInterceptor the packet interceptor to remove.
*/
public void removePresenceInterceptor(PacketInterceptor presenceInterceptor) {
presenceInterceptors.remove(presenceInterceptor);
}
/**
* Returns the last known room's subject or <tt>null</tt> if the user hasn't joined the room
* or the room does not have a subject yet. In case the room has a subject, as soon as the
* user joins the room a message with the current room's subject will be received.<p>
*
* To be notified every time the room's subject change you should add a listener
* to this room. {@link #addSubjectUpdatedListener(SubjectUpdatedListener)}<p>
*
* To change the room's subject use {@link #changeSubject(String)}.
*
* @return the room's subject or <tt>null</tt> if the user hasn't joined the room or the
* room does not have a subject yet.
*/
public String getSubject() {
return subject;
}
/**
* Returns the reserved room nickname for the user in the room. A user may have a reserved
* nickname, for example through explicit room registration or database integration. In such
* cases it may be desirable for the user to discover the reserved nickname before attempting
* to enter the room.
*
* @return the reserved room nickname or <tt>null</tt> if none.
*/
public String getReservedNickname() {
try {
DiscoverInfo result =
ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(
room,
"x-roomuser-item");
// Look for an Identity that holds the reserved nickname and return its name
for (Iterator<DiscoverInfo.Identity> identities = result.getIdentities();
identities.hasNext();) {
DiscoverInfo.Identity identity = identities.next();
return identity.getName();
}
// If no Identity was found then the user does not have a reserved room nickname
return null;
}
catch (XMPPException e) {
e.printStackTrace();
return null;
}
}
/**
* Returns the nickname that was used to join the room, or <tt>null</tt> if not
* currently joined.
*
* @return the nickname currently being used.
*/
public String getNickname() {
return nickname;
}
/**
* Changes the occupant's nickname to a new nickname within the room. Each room occupant
* will receive two presence packets. One of type "unavailable" for the old nickname and one
* indicating availability for the new nickname. The unavailable presence will contain the new
* nickname and an appropriate status code (namely 303) as extended presence information. The
* status code 303 indicates that the occupant is changing his/her nickname.
*
* @param nickname the new nickname within the room.
* @throws XMPPException if the new nickname is already in use by another occupant.
*/
public void changeNickname(String nickname) throws XMPPException {
if (nickname == null || nickname.equals("")) {
throw new IllegalArgumentException("Nickname must not be null or blank.");
}
// Check that we already have joined the room before attempting to change the
// nickname.
if (!joined) {
throw new IllegalStateException("Must be logged into the room to change nickname.");
}
// We change the nickname by sending a presence packet where the "to"
// field is in the form "roomName@service/nickname"
// We don't have to signal the MUC support again
Presence joinPresence = new Presence(Presence.Type.available);
joinPresence.setTo(room + "/" + nickname);
// Invoke presence interceptors so that extra information can be dynamically added
for (PacketInterceptor packetInterceptor : presenceInterceptors) {
packetInterceptor.interceptPacket(joinPresence);
}
// Wait for a presence packet back from the server.
PacketFilter responseFilter =
new AndFilter(
new FromMatchesFilter(room + "/" + nickname),
new PacketTypeFilter(Presence.class));
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send join packet.
connection.sendPacket(joinPresence);
// Wait up to a certain number of seconds for a reply.
Presence presence =
(Presence) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (presence == null) {
throw new XMPPException("No response from server.");
}
else if (presence.getError() != null) {
throw new XMPPException(presence.getError());
}
this.nickname = nickname;
}
/**
* Changes the occupant's availability status within the room. The presence type
* will remain available but with a new status that describes the presence update and
* a new presence mode (e.g. Extended away).
*
* @param status a text message describing the presence update.
* @param mode the mode type for the presence update.
*/
public void changeAvailabilityStatus(String status, Presence.Mode mode) {
if (nickname == null || nickname.equals("")) {
throw new IllegalArgumentException("Nickname must not be null or blank.");
}
// Check that we already have joined the room before attempting to change the
// availability status.
if (!joined) {
throw new IllegalStateException(
"Must be logged into the room to change the " + "availability status.");
}
// We change the availability status by sending a presence packet to the room with the
// new presence status and mode
Presence joinPresence = new Presence(Presence.Type.available);
joinPresence.setStatus(status);
joinPresence.setMode(mode);
joinPresence.setTo(room + "/" + nickname);
// Invoke presence interceptors so that extra information can be dynamically added
for (PacketInterceptor packetInterceptor : presenceInterceptors) {
packetInterceptor.interceptPacket(joinPresence);
}
// Send join packet.
connection.sendPacket(joinPresence);
}
/**
* Kicks a visitor or participant from the room. The kicked occupant will receive a presence
* of type "unavailable" including a status code 307 and optionally along with the reason
* (if provided) and the bare JID of the user who initiated the kick. After the occupant
* was kicked from the room, the rest of the occupants will receive a presence of type
* "unavailable". The presence will include a status code 307 which means that the occupant
* was kicked from the room.
*
* @param nickname the nickname of the participant or visitor to kick from the room
* (e.g. "john").
* @param reason the reason why the participant or visitor is being kicked from the room.
* @throws XMPPException if an error occurs kicking the occupant. In particular, a
* 405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
* was intended to be kicked (i.e. Not Allowed error); or a
* 403 error can occur if the occupant that intended to kick another occupant does
* not have kicking privileges (i.e. Forbidden error); or a
* 400 error can occur if the provided nickname is not present in the room.
*/
public void kickParticipant(String nickname, String reason) throws XMPPException {
changeRole(nickname, "none", reason);
}
/**
* Grants voice to visitors in the room. In a moderated room, a moderator may want to manage
* who does and does not have "voice" in the room. To have voice means that a room occupant
* is able to send messages to the room occupants.
*
* @param nicknames the nicknames of the visitors to grant voice in the room (e.g. "john").
* @throws XMPPException if an error occurs granting voice to a visitor. In particular, a
* 403 error can occur if the occupant that intended to grant voice is not
* a moderator in this room (i.e. Forbidden error); or a
* 400 error can occur if the provided nickname is not present in the room.
*/
public void grantVoice(Collection<String> nicknames) throws XMPPException {
changeRole(nicknames, "participant");
}
/**
* Grants voice to a visitor in the room. In a moderated room, a moderator may want to manage
* who does and does not have "voice" in the room. To have voice means that a room occupant
* is able to send messages to the room occupants.
*
* @param nickname the nickname of the visitor to grant voice in the room (e.g. "john").
* @throws XMPPException if an error occurs granting voice to a visitor. In particular, a
* 403 error can occur if the occupant that intended to grant voice is not
* a moderator in this room (i.e. Forbidden error); or a
* 400 error can occur if the provided nickname is not present in the room.
*/
public void grantVoice(String nickname) throws XMPPException {
changeRole(nickname, "participant", null);
}
/**
* Revokes voice from participants in the room. In a moderated room, a moderator may want to
* revoke an occupant's privileges to speak. To have voice means that a room occupant
* is able to send messages to the room occupants.
*
* @param nicknames the nicknames of the participants to revoke voice (e.g. "john").
* @throws XMPPException if an error occurs revoking voice from a participant. In particular, a
* 405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
* was tried to revoke his voice (i.e. Not Allowed error); or a
* 400 error can occur if the provided nickname is not present in the room.
*/
public void revokeVoice(Collection<String> nicknames) throws XMPPException {
changeRole(nicknames, "visitor");
}
/**
* Revokes voice from a participant in the room. In a moderated room, a moderator may want to
* revoke an occupant's privileges to speak. To have voice means that a room occupant
* is able to send messages to the room occupants.
*
* @param nickname the nickname of the participant to revoke voice (e.g. "john").
* @throws XMPPException if an error occurs revoking voice from a participant. In particular, a
* 405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
* was tried to revoke his voice (i.e. Not Allowed error); or a
* 400 error can occur if the provided nickname is not present in the room.
*/
public void revokeVoice(String nickname) throws XMPPException {
changeRole(nickname, "visitor", null);
}
/**
* Bans users from the room. An admin or owner of the room can ban users from a room. This
* means that the banned user will no longer be able to join the room unless the ban has been
* removed. If the banned user was present in the room then he/she will be removed from the
* room and notified that he/she was banned along with the reason (if provided) and the bare
* XMPP user ID of the user who initiated the ban.
*
* @param jids the bare XMPP user IDs of the users to ban.
* @throws XMPPException if an error occurs banning a user. In particular, a
* 405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
* was tried to be banned (i.e. Not Allowed error).
*/
public void banUsers(Collection<String> jids) throws XMPPException {
changeAffiliationByAdmin(jids, "outcast");
}
/**
* Bans a user from the room. An admin or owner of the room can ban users from a room. This
* means that the banned user will no longer be able to join the room unless the ban has been
* removed. If the banned user was present in the room then he/she will be removed from the
* room and notified that he/she was banned along with the reason (if provided) and the bare
* XMPP user ID of the user who initiated the ban.
*
* @param jid the bare XMPP user ID of the user to ban (e.g. "user@host.org").
* @param reason the reason why the user was banned.
* @throws XMPPException if an error occurs banning a user. In particular, a
* 405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
* was tried to be banned (i.e. Not Allowed error).
*/
public void banUser(String jid, String reason) throws XMPPException {
changeAffiliationByAdmin(jid, "outcast", reason);
}
/**
* Grants membership to other users. Only administrators are able to grant membership. A user
* that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
* that a user cannot enter without being on the member list).
*
* @param jids the XMPP user IDs of the users to grant membership.
* @throws XMPPException if an error occurs granting membership to a user.
*/
public void grantMembership(Collection<String> jids) throws XMPPException {
changeAffiliationByAdmin(jids, "member");
}
/**
* Grants membership to a user. Only administrators are able to grant membership. A user
* that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
* that a user cannot enter without being on the member list).
*
* @param jid the XMPP user ID of the user to grant membership (e.g. "user@host.org").
* @throws XMPPException if an error occurs granting membership to a user.
*/
public void grantMembership(String jid) throws XMPPException {
changeAffiliationByAdmin(jid, "member", null);
}
/**
* Revokes users' membership. Only administrators are able to revoke membership. A user
* that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
* that a user cannot enter without being on the member list). If the user is in the room and
* the room is of type members-only then the user will be removed from the room.
*
* @param jids the bare XMPP user IDs of the users to revoke membership.
* @throws XMPPException if an error occurs revoking membership to a user.
*/
public void revokeMembership(Collection<String> jids) throws XMPPException {
changeAffiliationByAdmin(jids, "none");
}
/**
* Revokes a user's membership. Only administrators are able to revoke membership. A user
* that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
* that a user cannot enter without being on the member list). If the user is in the room and
* the room is of type members-only then the user will be removed from the room.
*
* @param jid the bare XMPP user ID of the user to revoke membership (e.g. "user@host.org").
* @throws XMPPException if an error occurs revoking membership to a user.
*/
public void revokeMembership(String jid) throws XMPPException {
changeAffiliationByAdmin(jid, "none", null);
}
/**
* Grants moderator privileges to participants or visitors. Room administrators may grant
* moderator privileges. A moderator is allowed to kick users, grant and revoke voice, invite
* other users, modify room's subject plus all the partcipants privileges.
*
* @param nicknames the nicknames of the occupants to grant moderator privileges.
* @throws XMPPException if an error occurs granting moderator privileges to a user.
*/
public void grantModerator(Collection<String> nicknames) throws XMPPException {
changeRole(nicknames, "moderator");
}
/**
* Grants moderator privileges to a participant or visitor. Room administrators may grant
* moderator privileges. A moderator is allowed to kick users, grant and revoke voice, invite
* other users, modify room's subject plus all the partcipants privileges.
*
* @param nickname the nickname of the occupant to grant moderator privileges.
* @throws XMPPException if an error occurs granting moderator privileges to a user.
*/
public void grantModerator(String nickname) throws XMPPException {
changeRole(nickname, "moderator", null);
}
/**
* Revokes moderator privileges from other users. The occupant that loses moderator
* privileges will become a participant. Room administrators may revoke moderator privileges
* only to occupants whose affiliation is member or none. This means that an administrator is
* not allowed to revoke moderator privileges from other room administrators or owners.
*
* @param nicknames the nicknames of the occupants to revoke moderator privileges.
* @throws XMPPException if an error occurs revoking moderator privileges from a user.
*/
public void revokeModerator(Collection<String> nicknames) throws XMPPException {
changeRole(nicknames, "participant");
}
/**
* Revokes moderator privileges from another user. The occupant that loses moderator
* privileges will become a participant. Room administrators may revoke moderator privileges
* only to occupants whose affiliation is member or none. This means that an administrator is
* not allowed to revoke moderator privileges from other room administrators or owners.
*
* @param nickname the nickname of the occupant to revoke moderator privileges.
* @throws XMPPException if an error occurs revoking moderator privileges from a user.
*/
public void revokeModerator(String nickname) throws XMPPException {
changeRole(nickname, "participant", null);
}
/**
* Grants ownership privileges to other users. Room owners may grant ownership privileges.
* Some room implementations will not allow to grant ownership privileges to other users.
* An owner is allowed to change defining room features as well as perform all administrative
* functions.
*
* @param jids the collection of bare XMPP user IDs of the users to grant ownership.
* @throws XMPPException if an error occurs granting ownership privileges to a user.
*/
public void grantOwnership(Collection<String> jids) throws XMPPException {
changeAffiliationByOwner(jids, "owner");
}
/**
* Grants ownership privileges to another user. Room owners may grant ownership privileges.
* Some room implementations will not allow to grant ownership privileges to other users.
* An owner is allowed to change defining room features as well as perform all administrative
* functions.
*
* @param jid the bare XMPP user ID of the user to grant ownership (e.g. "user@host.org").
* @throws XMPPException if an error occurs granting ownership privileges to a user.
*/
public void grantOwnership(String jid) throws XMPPException {
changeAffiliationByOwner(jid, "owner");
}
/**
* Revokes ownership privileges from other users. The occupant that loses ownership
* privileges will become an administrator. Room owners may revoke ownership privileges.
* Some room implementations will not allow to grant ownership privileges to other users.
*
* @param jids the bare XMPP user IDs of the users to revoke ownership.
* @throws XMPPException if an error occurs revoking ownership privileges from a user.
*/
public void revokeOwnership(Collection<String> jids) throws XMPPException {
changeAffiliationByOwner(jids, "admin");
}
/**
* Revokes ownership privileges from another user. The occupant that loses ownership
* privileges will become an administrator. Room owners may revoke ownership privileges.
* Some room implementations will not allow to grant ownership privileges to other users.
*
* @param jid the bare XMPP user ID of the user to revoke ownership (e.g. "user@host.org").
* @throws XMPPException if an error occurs revoking ownership privileges from a user.
*/
public void revokeOwnership(String jid) throws XMPPException {
changeAffiliationByOwner(jid, "admin");
}
/**
* Grants administrator privileges to other users. Room owners may grant administrator
* privileges to a member or unaffiliated user. An administrator is allowed to perform
* administrative functions such as banning users and edit moderator list.
*
* @param jids the bare XMPP user IDs of the users to grant administrator privileges.
* @throws XMPPException if an error occurs granting administrator privileges to a user.
*/
public void grantSubchief(Collection<String> jids) throws XMPPException {
changeAffiliationByOwner(jids, "admin",true);
}
/**
* Grants administrator privileges to other users. Room owners may grant administrator
* privileges to a member or unaffiliated user. An administrator is allowed to perform
* administrative functions such as banning users and edit moderator list.
*
* @param jids the bare XMPP user IDs of the users to grant administrator privileges.
* @throws XMPPException if an error occurs granting administrator privileges to a user.
*/
public void grantAdmin(Collection<String> jids) throws XMPPException {
changeAffiliationByOwner(jids, "admin");
}
/**
* Grants administrator privileges to another user. Room owners may grant administrator
* privileges to a member or unaffiliated user. An administrator is allowed to perform
* administrative functions such as banning users and edit moderator list.
*
* @param jid the bare XMPP user ID of the user to grant administrator privileges
* (e.g. "user@host.org").
* @throws XMPPException if an error occurs granting administrator privileges to a user.
*/
public void grantAdmin(String jid) throws XMPPException {
changeAffiliationByOwner(jid, "admin");
}
public void grantSubchief(String jid) throws XMPPException {
changeAffiliationByOwner(jid, "owner",true);
}
/**
* Revokes administrator privileges from users. The occupant that loses administrator
* privileges will become a member. Room owners may revoke administrator privileges from
* a member or unaffiliated user.
*
* @param jids the bare XMPP user IDs of the user to revoke administrator privileges.
* @throws XMPPException if an error occurs revoking administrator privileges from a user.
*/
public void revokeAdmin(Collection<String> jids) throws XMPPException {
changeAffiliationByOwner(jids, "member");
}
public void revokeSubchief(Collection<String> jids) throws XMPPException {
changeAffiliationByOwner(jids, "member",true);
}
public void revokeSubchief(String jid) throws XMPPException {
changeAffiliationByOwner(jid, "member",true);
}
/**
* Revokes administrator privileges from a user. The occupant that loses administrator
* privileges will become a member. Room owners may revoke administrator privileges from
* a member or unaffiliated user.
*
* @param jid the bare XMPP user ID of the user to revoke administrator privileges
* (e.g. "user@host.org").
* @throws XMPPException if an error occurs revoking administrator privileges from a user.
*/
public void revokeAdmin(String jid) throws XMPPException {
changeAffiliationByOwner(jid, "member");
}
private void changeAffiliationByOwner(String jid, String affiliation) throws XMPPException {
changeAffiliationByOwner(jid, affiliation, false);
}
private void changeAffiliationByOwner(String jid, String affiliation,boolean isSubchief) throws XMPPException {
MUCOwner iq = new MUCOwner();
iq.setTo(room);
iq.setType(IQ.Type.SET);
// Set the new affiliation.
MUCOwner.Item item = new MUCOwner.Item(affiliation);
item.setJid(jid);
item.setSubchief(isSubchief);
iq.addItem(item);
// Wait for a response packet back from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the change request to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
}
private void changeAffiliationByOwner(Collection<String> jids, String affiliation)
throws XMPPException {
changeAffiliationByOwner(jids, affiliation, false);
}
private void changeAffiliationByOwner(Collection<String> jids, String affiliation,boolean isSubchief)
throws XMPPException {
MUCOwner iq = new MUCOwner();
iq.setTo(room);
iq.setType(IQ.Type.SET);
for (String jid : jids) {
// Set the new affiliation.
MUCOwner.Item item = new MUCOwner.Item(affiliation);
item.setSubchief(isSubchief);
item.setJid(jid);
iq.addItem(item);
}
// Wait for a response packet back from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the change request to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
}
private void changeAffiliationByAdmin(String jid, String affiliation, String reason)
throws XMPPException {
MUCAdmin iq = new MUCAdmin();
iq.setTo(room);
iq.setType(IQ.Type.SET);
// Set the new affiliation.
MUCAdmin.Item item = new MUCAdmin.Item(affiliation, null);
item.setJid(jid);
item.setReason(reason);
iq.addItem(item);
// Wait for a response packet back from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the change request to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
}
private void changeAffiliationByAdmin(Collection<String> jids, String affiliation)
throws XMPPException {
MUCAdmin iq = new MUCAdmin();
iq.setTo(room);
iq.setType(IQ.Type.SET);
for (String jid : jids) {
// Set the new affiliation.
MUCAdmin.Item item = new MUCAdmin.Item(affiliation, null);
item.setJid(jid);
iq.addItem(item);
}
// Wait for a response packet back from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the change request to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
}
private void changeRole(String nickname, String role, String reason) throws XMPPException {
MUCAdmin iq = new MUCAdmin();
iq.setTo(room);
iq.setType(IQ.Type.SET);
// Set the new role.
MUCAdmin.Item item = new MUCAdmin.Item(null, role);
item.setNick(nickname);
item.setReason(reason);
iq.addItem(item);
// Wait for a response packet back from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the change request to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
}
private void changeRole(Collection<String> nicknames, String role) throws XMPPException {
MUCAdmin iq = new MUCAdmin();
iq.setTo(room);
iq.setType(IQ.Type.SET);
for (String nickname : nicknames) {
// Set the new role.
MUCAdmin.Item item = new MUCAdmin.Item(null, role);
item.setNick(nickname);
iq.addItem(item);
}
// Wait for a response packet back from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the change request to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
}
/**
* Returns the number of occupants in the group chat.<p>
*
* Note: this value will only be accurate after joining the group chat, and
* may fluctuate over time. If you query this value directly after joining the
* group chat it may not be accurate, as it takes a certain amount of time for
* the server to send all presence packets to this client.
*
* @return the number of occupants in the group chat.
*/
public int getOccupantsCount() {
return occupantsMap.size();
}
/**
* Returns an Iterator (of Strings) for the list of fully qualified occupants
* in the group chat. For example, "conference@chat.jivesoftware.com/SomeUser".
* Typically, a client would only display the nickname of the occupant. To
* get the nickname from the fully qualified name, use the
* {@link org.jivesoftware.smack.util.StringUtils#parseResource(String)} method.
* Note: this value will only be accurate after joining the group chat, and may
* fluctuate over time.
*
* @return an Iterator for the occupants in the group chat.
*/
public Iterator<String> getOccupants() {
return Collections.unmodifiableList(new ArrayList<String>(occupantsMap.keySet()))
.iterator();
}
/**
* Returns the presence info for a particular user, or <tt>null</tt> if the user
* is not in the room.<p>
*
* @param user the room occupant to search for his presence. The format of user must
* be: roomName@service/nickname (e.g. darkcave@macbeth.shakespeare.lit/thirdwitch).
* @return the occupant's current presence, or <tt>null</tt> if the user is unavailable
* or if no presence information is available.
*/
public Presence getOccupantPresence(String user) {
return occupantsMap.get(user);
}
/**
* Returns the Occupant information for a particular occupant, or <tt>null</tt> if the
* user is not in the room. The Occupant object may include information such as full
* JID of the user as well as the role and affiliation of the user in the room.<p>
*
* @param user the room occupant to search for his presence. The format of user must
* be: roomName@service/nickname (e.g. darkcave@macbeth.shakespeare.lit/thirdwitch).
* @return the Occupant or <tt>null</tt> if the user is unavailable (i.e. not in the room).
*/
public Occupant getOccupant(String user) {
Presence presence = occupantsMap.get(user);
if (presence != null) {
return new Occupant(presence);
}
return null;
}
/**
* Adds a packet listener that will be notified of any new Presence packets
* sent to the group chat. Using a listener is a suitable way to know when the list
* of occupants should be re-loaded due to any changes.
*
* @param listener a packet listener that will be notified of any presence packets
* sent to the group chat.
*/
public void addParticipantListener(PacketListener listener) {
connection.addPacketListener(listener, presenceFilter);
connectionListeners.add(listener);
}
/**
* Remoces a packet listener that was being notified of any new Presence packets
* sent to the group chat.
*
* @param listener a packet listener that was being notified of any presence packets
* sent to the group chat.
*/
public void removeParticipantListener(PacketListener listener) {
connection.removePacketListener(listener);
connectionListeners.remove(listener);
}
/**
* Returns a collection of <code>Affiliate</code> with the room owners.
*
* @return a collection of <code>Affiliate</code> with the room owners.
* @throws XMPPException if an error occured while performing the request to the server or you
* don't have enough privileges to get this information.
*/
public Collection<Affiliate> getOwners() throws XMPPException {
return getAffiliatesByOwner("owner");
}
/**
* Returns a collection of <code>Affiliate</code> with the room administrators.
*
* @return a collection of <code>Affiliate</code> with the room administrators.
* @throws XMPPException if an error occured while performing the request to the server or you
* don't have enough privileges to get this information.
*/
public Collection<Affiliate> getAdmins() throws XMPPException {
return getAffiliatesByOwner("admin");
}
/**
* Returns a collection of <code>Affiliate</code> with the room members.
*
* @return a collection of <code>Affiliate</code> with the room members.
* @throws XMPPException if an error occured while performing the request to the server or you
* don't have enough privileges to get this information.
*/
public Collection<Affiliate> getMembers() throws XMPPException {
return getAffiliatesByAdmin("member");
}
/**
* Returns a collection of <code>Affiliate</code> with the room outcasts.
*
* @return a collection of <code>Affiliate</code> with the room outcasts.
* @throws XMPPException if an error occured while performing the request to the server or you
* don't have enough privileges to get this information.
*/
public Collection<Affiliate> getOutcasts() throws XMPPException {
return getAffiliatesByAdmin("outcast");
}
/**
* Returns a collection of <code>Affiliate</code> that have the specified room affiliation
* sending a request in the owner namespace.
*
* @param affiliation the affiliation of the users in the room.
* @return a collection of <code>Affiliate</code> that have the specified room affiliation.
* @throws XMPPException if an error occured while performing the request to the server or you
* don't have enough privileges to get this information.
*/
private Collection<Affiliate> getAffiliatesByOwner(String affiliation) throws XMPPException {
MUCOwner iq = new MUCOwner();
iq.setTo(room);
iq.setType(IQ.Type.GET);
// Set the specified affiliation. This may request the list of owners/admins/members/outcasts.
MUCOwner.Item item = new MUCOwner.Item(affiliation);
iq.addItem(item);
// Wait for a response packet back from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the request to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
MUCOwner answer = (MUCOwner) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
// Get the list of affiliates from the server's answer
List<Affiliate> affiliates = new ArrayList<Affiliate>();
for (Iterator it = answer.getItems(); it.hasNext();) {
affiliates.add(new Affiliate((MUCOwner.Item) it.next()));
}
return affiliates;
}
/**
* Returns a collection of <code>Affiliate</code> that have the specified room affiliation
* sending a request in the admin namespace.
*
* @param affiliation the affiliation of the users in the room.
* @return a collection of <code>Affiliate</code> that have the specified room affiliation.
* @throws XMPPException if an error occured while performing the request to the server or you
* don't have enough privileges to get this information.
*/
private Collection<Affiliate> getAffiliatesByAdmin(String affiliation) throws XMPPException {
MUCAdmin iq = new MUCAdmin();
iq.setTo(room);
iq.setType(IQ.Type.GET);
// Set the specified affiliation. This may request the list of owners/admins/members/outcasts.
MUCAdmin.Item item = new MUCAdmin.Item(affiliation, null);
iq.addItem(item);
// Wait for a response packet back from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the request to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
MUCAdmin answer = (MUCAdmin) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
// Get the list of affiliates from the server's answer
List<Affiliate> affiliates = new ArrayList<Affiliate>();
for (Iterator it = answer.getItems(); it.hasNext();) {
affiliates.add(new Affiliate((MUCAdmin.Item) it.next()));
}
return affiliates;
}
/**
* Returns a collection of <code>Occupant</code> with the room moderators.
*
* @return a collection of <code>Occupant</code> with the room moderators.
* @throws XMPPException if an error occured while performing the request to the server or you
* don't have enough privileges to get this information.
*/
public Collection<Occupant> getModerators() throws XMPPException {
return getOccupants("moderator");
}
/**
* Returns a collection of <code>Occupant</code> with the room participants.
*
* @return a collection of <code>Occupant</code> with the room participants.
* @throws XMPPException if an error occured while performing the request to the server or you
* don't have enough privileges to get this information.
*/
public Collection<Occupant> getParticipants() throws XMPPException {
return getOccupants("participant");
}
/**
* Returns a collection of <code>Occupant</code> that have the specified room role.
*
* @param role the role of the occupant in the room.
* @return a collection of <code>Occupant</code> that have the specified room role.
* @throws XMPPException if an error occured while performing the request to the server or you
* don't have enough privileges to get this information.
*/
private Collection<Occupant> getOccupants(String role) throws XMPPException {
MUCAdmin iq = new MUCAdmin();
iq.setTo(room);
iq.setType(IQ.Type.GET);
// Set the specified role. This may request the list of moderators/participants.
MUCAdmin.Item item = new MUCAdmin.Item(null, role);
iq.addItem(item);
// Wait for a response packet back from the server.
PacketFilter responseFilter = new PacketIDFilter(iq.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send the request to the server.
connection.sendPacket(iq);
// Wait up to a certain number of seconds for a reply.
MUCAdmin answer = (MUCAdmin) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
// Get the list of participants from the server's answer
List<Occupant> participants = new ArrayList<Occupant>();
for (Iterator it = answer.getItems(); it.hasNext();) {
participants.add(new Occupant((MUCAdmin.Item) it.next()));
}
return participants;
}
/**
* Sends a message to the chat room.
*
* @param text the text of the message to send.
* @throws XMPPException if sending the message fails.
*/
public void sendMessage(String text) throws XMPPException {
Message message = new Message(room, Message.Type.groupchat);
message.setBody(text);
connection.sendPacket(message);
}
/**
* Returns a new Chat for sending private messages to a given room occupant.
* The Chat's occupant address is the room's JID (i.e. roomName@service/nick). The server
* service will change the 'from' address to the sender's room JID and delivering the message
* to the intended recipient's full JID.
*
* @param occupant occupant unique room JID (e.g. 'darkcave@macbeth.shakespeare.lit/Paul').
* @param listener the listener is a message listener that will handle messages for the newly
* created chat.
* @return new Chat for sending private messages to a given room occupant.
*/
public Chat createPrivateChat(String occupant, MessageListener listener) {
return connection.getChatManager().createChat(occupant, listener);
}
/**
* Creates a new Message to send to the chat room.
*
* @return a new Message addressed to the chat room.
*/
public Message createMessage() {
return new Message(room, Message.Type.groupchat);
}
/**
* Sends a Message to the chat room.
*
* @param message the message.
* @throws XMPPException if sending the message fails.
*/
public void sendMessage(Message message) throws XMPPException {
connection.sendPacket(message);
}
/**
* Polls for and returns the next message, or <tt>null</tt> if there isn't
* a message immediately available. This method provides significantly different
* functionalty than the {@link #nextMessage()} method since it's non-blocking.
* In other words, the method call will always return immediately, whereas the
* nextMessage method will return only when a message is available (or after
* a specific timeout).
*
* @return the next message if one is immediately available and
* <tt>null</tt> otherwise.
*/
public Message pollMessage() {
return (Message) messageCollector.pollResult();
}
/**
* Returns the next available message in the chat. The method call will block
* (not return) until a message is available.
*
* @return the next message.
*/
public Message nextMessage() {
return (Message) messageCollector.nextResult();
}
/**
* Returns the next available message in the chat. The method call will block
* (not return) until a packet is available or the <tt>timeout</tt> has elapased.
* If the timeout elapses without a result, <tt>null</tt> will be returned.
*
* @param timeout the maximum amount of time to wait for the next message.
* @return the next message, or <tt>null</tt> if the timeout elapses without a
* message becoming available.
*/
public Message nextMessage(long timeout) {
return (Message) messageCollector.nextResult(timeout);
}
/**
* Adds a packet listener that will be notified of any new messages in the
* group chat. Only "group chat" messages addressed to this group chat will
* be delivered to the listener. If you wish to listen for other packets
* that may be associated with this group chat, you should register a
* PacketListener directly with the Connection with the appropriate
* PacketListener.
*
* @param listener a packet listener.
*/
public void addMessageListener(PacketListener listener) {
connection.addPacketListener(listener, messageFilter);
connectionListeners.add(listener);
}
/**
* Removes a packet listener that was being notified of any new messages in the
* multi user chat. Only "group chat" messages addressed to this multi user chat were
* being delivered to the listener.
*
* @param listener a packet listener.
*/
public void removeMessageListener(PacketListener listener) {
connection.removePacketListener(listener);
connectionListeners.remove(listener);
}
/**
* Changes the subject within the room. As a default, only users with a role of "moderator"
* are allowed to change the subject in a room. Although some rooms may be configured to
* allow a mere participant or even a visitor to change the subject.
*
* @param subject the new room's subject to set.
* @throws XMPPException if someone without appropriate privileges attempts to change the
* room subject will throw an error with code 403 (i.e. Forbidden)
*/
public void changeSubject(final String subject) throws XMPPException {
Message message = new Message(room, Message.Type.groupchat);
message.setSubject(subject);
// Wait for an error or confirmation message back from the server.
PacketFilter responseFilter =
new AndFilter(
new FromMatchesFilter(room),
new PacketTypeFilter(Message.class));
responseFilter = new AndFilter(responseFilter, new PacketFilter() {
public boolean accept(Packet packet) {
Message msg = (Message) packet;
return subject.equals(msg.getSubject());
}
});
PacketCollector response = connection.createPacketCollector(responseFilter);
// Send change subject packet.
connection.sendPacket(message);
// Wait up to a certain number of seconds for a reply.
Message answer =
(Message) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
}
else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
}
/**
* Notification message that the user has joined the room.
*/
private synchronized void userHasJoined() {
// Update the list of joined rooms through this connection
List<String> rooms = joinedRooms.get(connection);
if (rooms == null) {
rooms = new ArrayList<String>();
joinedRooms.put(connection, rooms);
}
rooms.add(room);
}
/**
* Notification message that the user has left the room.
*/
private synchronized void userHasLeft() {
// Update the list of joined rooms through this connection
List<String> rooms = joinedRooms.get(connection);
if (rooms == null) {
return;
}
rooms.remove(room);
}
/**
* Returns the MUCUser packet extension included in the packet or <tt>null</tt> if none.
*
* @param packet the packet that may include the MUCUser extension.
* @return the MUCUser found in the packet.
*/
private MUCUser getMUCUserExtension(Packet packet) {
if (packet != null) {
// Get the MUC User extension
return (MUCUser) packet.getExtension("x", "http://jabber.org/protocol/muc#user");
}
return null;
}
/**
* Adds a listener that will be notified of changes in your status in the room
* such as the user being kicked, banned, or granted admin permissions.
*
* @param listener a user status listener.
*/
public void addUserStatusListener(UserStatusListener listener) {
synchronized (userStatusListeners) {
if (!userStatusListeners.contains(listener)) {
userStatusListeners.add(listener);
}
}
}
/**
* Removes a listener that was being notified of changes in your status in the room
* such as the user being kicked, banned, or granted admin permissions.
*
* @param listener a user status listener.
*/
public void removeUserStatusListener(UserStatusListener listener) {
synchronized (userStatusListeners) {
userStatusListeners.remove(listener);
}
}
private void fireUserStatusListeners(String methodName, Object[] params) {
UserStatusListener[] listeners;
synchronized (userStatusListeners) {
listeners = new UserStatusListener[userStatusListeners.size()];
userStatusListeners.toArray(listeners);
}
// Get the classes of the method parameters
Class[] paramClasses = new Class[params.length];
for (int i = 0; i < params.length; i++) {
paramClasses[i] = params[i].getClass();
}
try {
// Get the method to execute based on the requested methodName and parameters classes
Method method = UserStatusListener.class.getDeclaredMethod(methodName, paramClasses);
for (UserStatusListener listener : listeners) {
method.invoke(listener, params);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* Adds a listener that will be notified of changes in occupants status in the room
* such as the user being kicked, banned, or granted admin permissions.
*
* @param listener a participant status listener.
*/
public void addParticipantStatusListener(ParticipantStatusListener listener) {
synchronized (participantStatusListeners) {
if (!participantStatusListeners.contains(listener)) {
participantStatusListeners.add(listener);
}
}
}
/**
* Removes a listener that was being notified of changes in occupants status in the room
* such as the user being kicked, banned, or granted admin permissions.
*
* @param listener a participant status listener.
*/
public void removeParticipantStatusListener(ParticipantStatusListener listener) {
synchronized (participantStatusListeners) {
participantStatusListeners.remove(listener);
}
}
private void fireParticipantStatusListeners(String methodName, List<String> params) {
ParticipantStatusListener[] listeners;
synchronized (participantStatusListeners) {
listeners = new ParticipantStatusListener[participantStatusListeners.size()];
participantStatusListeners.toArray(listeners);
}
try {
// Get the method to execute based on the requested methodName and parameter
Class[] classes = new Class[params.size()];
for (int i=0;i<params.size(); i++) {
classes[i] = String.class;
}
Method method = ParticipantStatusListener.class.getDeclaredMethod(methodName, classes);
for (ParticipantStatusListener listener : listeners) {
method.invoke(listener, params.toArray());
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private void init() {
// Create filters
messageFilter =
new AndFilter(
new FromMatchesFilter(room),
new MessageTypeFilter(Message.Type.groupchat));
messageFilter = new AndFilter(messageFilter, new PacketFilter() {
public boolean accept(Packet packet) {
Message msg = (Message) packet;
return msg.getBody() != null;
}
});
presenceFilter =
new AndFilter(new FromMatchesFilter(room), new PacketTypeFilter(Presence.class));
// Create a collector for incoming messages.
messageCollector = new ConnectionDetachedPacketCollector();
// Create a listener for subject updates.
PacketListener subjectListener = new PacketListener() {
public void processPacket(Packet packet) {
Message msg = (Message) packet;
// Update the room subject
subject = msg.getSubject();
// Fire event for subject updated listeners
fireSubjectUpdatedListeners(
msg.getSubject(),
msg.getFrom());
}
};
// Create a listener for all presence updates.
PacketListener presenceListener = new PacketListener() {
public void processPacket(Packet packet) {
Presence presence = (Presence) packet;
String from = presence.getFrom();
String myRoomJID = room + "/" + nickname;
System.out.println("presence received...");
boolean isUserStatusModification = presence.getFrom().equals(myRoomJID);
if (presence.getType() == Presence.Type.available) {
Presence oldPresence = occupantsMap.put(from, presence);
if (oldPresence != null) {
// Get the previous occupant's affiliation & role
MUCUser mucExtension = getMUCUserExtension(presence);
if(mucExtension==null)
return;
MUCUser.Item mucItem=mucExtension.getItem();
if(mucItem==null)
return;
MUCUser.Item oldItem=mucUserItems.put(mucItem.getJid(),mucItem);
String oldAffiliation = null;
String oldRole = null;
if(oldItem!=null){
oldAffiliation= oldItem.getAffiliation();
if(oldItem.isSubchief()){
oldAffiliation="subchief";
}
oldRole=oldItem.getRole();
}
// Get the new occupant's affiliation & role
// mucExtension = getMUCUserExtension(presence);
String newAffiliation = mucExtension.getItem().getAffiliation();
if(mucExtension.getItem().isSubchief()){
newAffiliation="subchief";
}
String newRole = mucExtension.getItem().getRole();
////Logger.i("newRole: "+newRole+", newAffiliation:"+newAffiliation);
// Fire role modification events
checkRoleModifications(oldRole, newRole, isUserStatusModification, mucExtension.getItem().getNick());
// Fire affiliation modification events
checkAffiliationModifications(
oldAffiliation,
newAffiliation,
isUserStatusModification,
mucExtension.getItem().getNick());
}
else {
MUCUser mucExtension = getMUCUserExtension(presence);
if(mucExtension!=null){
MUCUser.Item item= mucExtension.getItem();
if(item!=null){
String jid=item.getJid();
mucUserItems.put(jid, item);
}
}
// A new occupant has joined the room
if (!isUserStatusModification) {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("joined", params);
}
}
}
else if (presence.getType() == Presence.Type.unavailable) {
occupantsMap.remove(from);
MUCUser mucUser = getMUCUserExtension(presence);
if (mucUser != null && mucUser.getStatus() != null) {
// Fire events according to the received presence code
checkPresenceCode(
mucUser.getStatus().getCode(),
presence.getFrom().equals(myRoomJID),
mucUser,
from);
} else {
// An occupant has left the room
if (!isUserStatusModification) {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("left", params);
}
}
}
}
};
// Listens for all messages that include a MUCUser extension and fire the invitation
// rejection listeners if the message includes an invitation rejection.
PacketListener declinesListener = new PacketListener() {
public void processPacket(Packet packet) {
// Get the MUC User extension
MUCUser mucUser = getMUCUserExtension(packet);
// Check if the MUCUser informs that the invitee has declined the invitation
if (mucUser.getDecline() != null &&
((Message) packet).getType() != Message.Type.error) {
// Fire event for invitation rejection listeners
fireInvitationRejectionListeners(
mucUser.getDecline().getFrom(),
mucUser.getDecline().getReason());
}
}
};
PacketMultiplexListener packetMultiplexor = new PacketMultiplexListener(
messageCollector, presenceListener, subjectListener,
declinesListener);
roomListenerMultiplexor = RoomListenerMultiplexor.getRoomMultiplexor(connection);
roomListenerMultiplexor.addRoom(room, packetMultiplexor);
}
/**
* Fires notification events if the role of a room occupant has changed. If the occupant that
* changed his role is your occupant then the <code>UserStatusListeners</code> added to this
* <code>MultiUserChat</code> will be fired. On the other hand, if the occupant that changed
* his role is not yours then the <code>ParticipantStatusListeners</code> added to this
* <code>MultiUserChat</code> will be fired. The following table shows the events that will
* be fired depending on the previous and new role of the occupant.
*
* <pre>
* <table border="1">
* <tr><td><b>Old</b></td><td><b>New</b></td><td><b>Events</b></td></tr>
*
* <tr><td>None</td><td>Visitor</td><td>--</td></tr>
* <tr><td>Visitor</td><td>Participant</td><td>voiceGranted</td></tr>
* <tr><td>Participant</td><td>Moderator</td><td>moderatorGranted</td></tr>
*
* <tr><td>None</td><td>Participant</td><td>voiceGranted</td></tr>
* <tr><td>None</td><td>Moderator</td><td>voiceGranted + moderatorGranted</td></tr>
* <tr><td>Visitor</td><td>Moderator</td><td>voiceGranted + moderatorGranted</td></tr>
*
* <tr><td>Moderator</td><td>Participant</td><td>moderatorRevoked</td></tr>
* <tr><td>Participant</td><td>Visitor</td><td>voiceRevoked</td></tr>
* <tr><td>Visitor</td><td>None</td><td>kicked</td></tr>
*
* <tr><td>Moderator</td><td>Visitor</td><td>voiceRevoked + moderatorRevoked</td></tr>
* <tr><td>Moderator</td><td>None</td><td>kicked</td></tr>
* <tr><td>Participant</td><td>None</td><td>kicked</td></tr>
* </table>
* </pre>
*
* @param oldRole the previous role of the user in the room before receiving the new presence
* @param newRole the new role of the user in the room after receiving the new presence
* @param isUserModification whether the received presence is about your user in the room or not
* @param from the occupant whose role in the room has changed
* (e.g. room@conference.jabber.org/nick).
*/
private void checkRoleModifications(
String oldRole,
String newRole,
boolean isUserModification,
String from) {
// Voice was granted to a visitor
if (("visitor".equals(oldRole) || "none".equals(oldRole))
&& "participant".equals(newRole)) {
if (isUserModification) {
fireUserStatusListeners("voiceGranted", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("voiceGranted", params);
}
}
// The participant's voice was revoked from the room
else if (
"participant".equals(oldRole)
&& ("visitor".equals(newRole) || "none".equals(newRole))) {
if (isUserModification) {
fireUserStatusListeners("voiceRevoked", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("voiceRevoked", params);
}
}
// Moderator privileges were granted to a participant
if (!"moderator".equals(oldRole) && "moderator".equals(newRole)) {
if ("visitor".equals(oldRole) || "none".equals(oldRole)) {
if (isUserModification) {
fireUserStatusListeners("voiceGranted", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("voiceGranted", params);
}
}
if (isUserModification) {
fireUserStatusListeners("moderatorGranted", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("moderatorGranted", params);
}
}
// Moderator privileges were revoked from a participant
else if ("moderator".equals(oldRole) && !"moderator".equals(newRole)) {
if ("visitor".equals(newRole) || "none".equals(newRole)) {
if (isUserModification) {
fireUserStatusListeners("voiceRevoked", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("voiceRevoked", params);
}
}
if (isUserModification) {
fireUserStatusListeners("moderatorRevoked", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("moderatorRevoked", params);
}
}
}
/**
* Fires notification events if the affiliation of a room occupant has changed. If the
* occupant that changed his affiliation is your occupant then the
* <code>UserStatusListeners</code> added to this <code>MultiUserChat</code> will be fired.
* On the other hand, if the occupant that changed his affiliation is not yours then the
* <code>ParticipantStatusListeners</code> added to this <code>MultiUserChat</code> will be
* fired. The following table shows the events that will be fired depending on the previous
* and new affiliation of the occupant.
*
* <pre>
* <table border="1">
* <tr><td><b>Old</b></td><td><b>New</b></td><td><b>Events</b></td></tr>
*
* <tr><td>None</td><td>Member</td><td>membershipGranted</td></tr>
* <tr><td>Member</td><td>Admin</td><td>membershipRevoked + adminGranted</td></tr>
* <tr><td>Admin</td><td>Owner</td><td>adminRevoked + ownershipGranted</td></tr>
*
* <tr><td>None</td><td>Admin</td><td>adminGranted</td></tr>
* <tr><td>None</td><td>Owner</td><td>ownershipGranted</td></tr>
* <tr><td>Member</td><td>Owner</td><td>membershipRevoked + ownershipGranted</td></tr>
*
* <tr><td>Owner</td><td>Admin</td><td>ownershipRevoked + adminGranted</td></tr>
* <tr><td>Admin</td><td>Member</td><td>adminRevoked + membershipGranted</td></tr>
* <tr><td>Member</td><td>None</td><td>membershipRevoked</td></tr>
*
* <tr><td>Owner</td><td>Member</td><td>ownershipRevoked + membershipGranted</td></tr>
* <tr><td>Owner</td><td>None</td><td>ownershipRevoked</td></tr>
* <tr><td>Admin</td><td>None</td><td>adminRevoked</td></tr>
* <tr><td><i>Anyone</i></td><td>Outcast</td><td>banned</td></tr>
* </table>
* </pre>
*
* @param oldAffiliation the previous affiliation of the user in the room before receiving the
* new presence
* @param newAffiliation the new affiliation of the user in the room after receiving the new
* presence
* @param isUserModification whether the received presence is about your user in the room or not
* @param from the occupant whose role in the room has changed
* (e.g. room@conference.jabber.org/nick).
*/
private void checkAffiliationModifications(
String oldAffiliation,
String newAffiliation,
boolean isUserModification,
String from) {
// First check for revoked affiliation and then for granted affiliations. The idea is to
// first fire the "revoke" events and then fire the "grant" events.
// The user's ownership to the room was revoked
if ("owner".equals(oldAffiliation) && !"owner".equals(newAffiliation)) {
if (isUserModification) {
fireUserStatusListeners("ownershipRevoked", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("ownershipRevoked", params);
}
}
// The user's administrative privileges to the room were revoked
else if ("subchief".equals(oldAffiliation) && !"subchief".equals(newAffiliation)) {
if (isUserModification) {
fireUserStatusListeners("subchiefRevoked", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("subchiefRevoked", params);
}
}
else if ("admin".equals(oldAffiliation) && !"admin".equals(newAffiliation)) {
if (isUserModification) {
fireUserStatusListeners("adminRevoked", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("adminRevoked", params);
}
}
// The user's membership to the room was revoked
else if ("member".equals(oldAffiliation) && !"member".equals(newAffiliation)) {
if (isUserModification) {
fireUserStatusListeners("membershipRevoked", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("membershipRevoked", params);
}
}
// The user was granted ownership to the room
if (!"owner".equals(oldAffiliation) && "owner".equals(newAffiliation)) {
if (isUserModification) {
fireUserStatusListeners("ownershipGranted", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("ownershipGranted", params);
}
}
else if (!"subchief".equals(oldAffiliation) && "subchief".equals(newAffiliation)) {
if (isUserModification) {
fireUserStatusListeners("subchiefGranted", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("subchiefGranted", params);
}
}
// The user was granted administrative privileges to the room
else if (!"admin".equals(oldAffiliation) && "admin".equals(newAffiliation)) {
if (isUserModification) {
fireUserStatusListeners("adminGranted", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("adminGranted", params);
}
}
// The user was granted membership to the room
else if (!"member".equals(oldAffiliation) && "member".equals(newAffiliation)) {
if (isUserModification) {
fireUserStatusListeners("membershipGranted", new Object[] {});
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("membershipGranted", params);
}
}
}
/**
* Fires events according to the received presence code.
*
* @param code
* @param isUserModification
* @param mucUser
* @param from
*/
private void checkPresenceCode(
String code,
boolean isUserModification,
MUCUser mucUser,
String from) {
// Check if an occupant was kicked from the room
if ("307".equals(code)) {
// Check if this occupant was kicked
if (isUserModification) {
joined = false;
fireUserStatusListeners(
"kicked",
new Object[] { mucUser.getItem().getActor(), mucUser.getItem().getReason()});
// Reset occupant information.
occupantsMap.clear();
nickname = null;
userHasLeft();
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
params.add(mucUser.getItem().getActor());
params.add(mucUser.getItem().getReason());
fireParticipantStatusListeners("kicked", params);
}
}
// A user was banned from the room
else if ("301".equals(code)) {
// Check if this occupant was banned
if (isUserModification) {
joined = false;
fireUserStatusListeners(
"banned",
new Object[] { mucUser.getItem().getActor(), mucUser.getItem().getReason()});
// Reset occupant information.
occupantsMap.clear();
nickname = null;
userHasLeft();
}
else {
List<String> params = new ArrayList<String>();
params.add(from);
params.add(mucUser.getItem().getActor());
params.add(mucUser.getItem().getReason());
fireParticipantStatusListeners("banned", params);
}
}
// A user's membership was revoked from the room
else if ("321".equals(code)) {
// Check if this occupant's membership was revoked
if (isUserModification) {
joined = false;
fireUserStatusListeners("membershipRevoked", new Object[] {});
// Reset occupant information.
occupantsMap.clear();
nickname = null;
userHasLeft();
}
}
// A occupant has changed his nickname in the room
else if ("303".equals(code)) {
List<String> params = new ArrayList<String>();
params.add(from);
params.add(mucUser.getItem().getNick());
fireParticipantStatusListeners("nicknameChanged", params);
}
}
protected void finalize() throws Throwable {
try {
if (connection != null) {
roomListenerMultiplexor.removeRoom(room);
// Remove all the PacketListeners added to the connection by this chat
for (PacketListener connectionListener : connectionListeners) {
connection.removePacketListener(connectionListener);
}
}
}
catch (Exception e) {
// Do nothing
}
super.finalize();
}
/**
* An InvitationsMonitor monitors a given connection to detect room invitations. Every
* time the InvitationsMonitor detects a new invitation it will fire the invitation listeners.
*
* @author Gaston Dombiak
*/
private static class InvitationsMonitor implements ConnectionListener {
// We use a WeakHashMap so that the GC can collect the monitor when the
// connection is no longer referenced by any object.
private final static Map<Connection, WeakReference<InvitationsMonitor>> monitors =
new WeakHashMap<Connection, WeakReference<InvitationsMonitor>>();
private final List<InvitationListener> invitationsListeners =
new ArrayList<InvitationListener>();
private Connection connection;
private PacketFilter invitationFilter;
private PacketListener invitationPacketListener;
/**
* Returns a new or existing InvitationsMonitor for a given connection.
*
* @param conn the connection to monitor for room invitations.
* @return a new or existing InvitationsMonitor for a given connection.
*/
public static InvitationsMonitor getInvitationsMonitor(Connection conn) {
synchronized (monitors) {
if (!monitors.containsKey(conn)) {
// We need to use a WeakReference because the monitor references the
// connection and this could prevent the GC from collecting the monitor
// when no other object references the monitor
monitors.put(conn, new WeakReference<InvitationsMonitor>(new InvitationsMonitor(conn)));
}
// Return the InvitationsMonitor that monitors the connection
return monitors.get(conn).get();
}
}
/**
* Creates a new InvitationsMonitor that will monitor invitations received
* on a given connection.
*
* @param connection the connection to monitor for possible room invitations
*/
private InvitationsMonitor(Connection connection) {
this.connection = connection;
}
/**
* Adds a listener to invitation notifications. The listener will be fired anytime
* an invitation is received.<p>
*
* If this is the first monitor's listener then the monitor will be initialized in
* order to start listening to room invitations.
*
* @param listener an invitation listener.
*/
public void addInvitationListener(InvitationListener listener) {
synchronized (invitationsListeners) {
// If this is the first monitor's listener then initialize the listeners
// on the connection to detect room invitations
if (invitationsListeners.size() == 0) {
init();
}
if (!invitationsListeners.contains(listener)) {
invitationsListeners.add(listener);
}
}
}
/**
* Removes a listener to invitation notifications. The listener will be fired anytime
* an invitation is received.<p>
*
* If there are no more listeners to notifiy for room invitations then the monitor will
* be stopped. As soon as a new listener is added to the monitor, the monitor will resume
* monitoring the connection for new room invitations.
*
* @param listener an invitation listener.
*/
public void removeInvitationListener(InvitationListener listener) {
synchronized (invitationsListeners) {
if (invitationsListeners.contains(listener)) {
invitationsListeners.remove(listener);
}
// If there are no more listeners to notifiy for room invitations
// then proceed to cancel/release this monitor
if (invitationsListeners.size() == 0) {
cancel();
}
}
}
/**
* Fires invitation listeners.
*/
private void fireInvitationListeners(String room, String inviter, String reason, String password,
Message message) {
InvitationListener[] listeners;
synchronized (invitationsListeners) {
listeners = new InvitationListener[invitationsListeners.size()];
invitationsListeners.toArray(listeners);
}
for (InvitationListener listener : listeners) {
listener.invitationReceived(connection, room, inviter, reason, password, message);
}
}
public void connectionClosed() {
cancel();
}
public void connectionClosedOnError(Exception e) {
// ignore
}
public void reconnectingIn(int seconds) {
// ignore
}
public void reconnectionSuccessful() {
// ignore
}
public void reconnectionFailed(Exception e) {
// ignore
}
/**
* Initializes the listeners to detect received room invitations and to detect when the
* connection gets closed. As soon as a room invitation is received the invitations
* listeners will be fired. When the connection gets closed the monitor will remove
* his listeners on the connection.
*/
private void init() {
// Listens for all messages that include a MUCUser extension and fire the invitation
// listeners if the message includes an invitation.
invitationFilter =
new PacketExtensionFilter("x", "http://jabber.org/protocol/muc#user");
invitationPacketListener = new PacketListener() {
public void processPacket(Packet packet) {
// Get the MUCUser extension
MUCUser mucUser =
(MUCUser) packet.getExtension("x", "http://jabber.org/protocol/muc#user");
// Check if the MUCUser extension includes an invitation
if (mucUser.getInvite() != null &&
((Message) packet).getType() != Message.Type.error) {
// Fire event for invitation listeners
fireInvitationListeners(packet.getFrom(), mucUser.getInvite().getFrom(),
mucUser.getInvite().getReason(), mucUser.getPassword(), (Message) packet);
}
}
};
connection.addPacketListener(invitationPacketListener, invitationFilter);
// Add a listener to detect when the connection gets closed in order to
// cancel/release this monitor
connection.addConnectionListener(this);
}
/**
* Cancels all the listeners that this InvitationsMonitor has added to the connection.
*/
private void cancel() {
connection.removePacketListener(invitationPacketListener);
connection.removeConnectionListener(this);
}
@Override
public void onAccountConflicted() {
// TODO Auto-generated method stub
}
}
}
| [
"sunxiangjin1261@163.com"
] | sunxiangjin1261@163.com |
48b820fd73e60bbcae6e01ed1e746b66a8598313 | ff404f9f2eed7703a0ae9fda498b781efd6100b2 | /XEClipse/BallAnimationTemp2/src/Animation/MoveableShape.java | 8bf6cafa0037b7021c7c9c956cab0276ca6f7ccb | [] | no_license | gersonlobos2/X_WorkCode | a3788a3dd326b5741f12a6de1d12ad14491a2682 | a39ac8571672e37425e73e639f669924607f9218 | refs/heads/master | 2021-01-19T05:08:28.125569 | 2014-03-08T02:15:47 | 2014-03-08T02:15:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 182 | java | package Animation;
import java.awt.*;
public interface MoveableShape
{
void draw(Graphics2D g2);
void translate(int dx, int dy);
void moveShape(int x, int y);
}
| [
"gerson.lobos@whitestratus.com"
] | gerson.lobos@whitestratus.com |
b49ea60cfd282a69dea6395d92379cf770f0c076 | 0fecf9760e434824e64e894a63b05ca10a0d1e44 | /src/cn/appsys/controller/DevUserControll.java | fefa77948dd84627bc0f758f61597abd0ffc0aba | [] | no_license | luohongbiao/AppInfoSystem | 2391d5b3143b77a7e6c52b15c1425685b97dc0b0 | 5fbc28c2926499b1151fd9ca285849767d761bb9 | refs/heads/master | 2020-09-10T20:50:08.600623 | 2019-11-15T02:58:29 | 2019-11-15T02:58:29 | 221,697,741 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 24,148 | java | package cn.appsys.controller;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Null;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.tomcat.util.descriptor.web.LoginConfig;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.sun.java.swing.plaf.motif.resources.motif;
import com.sun.org.apache.bcel.internal.generic.NEW;
import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.AppCategoryService;
import cn.appsys.service.AppInfoService;
import cn.appsys.service.AppVersionService;
import cn.appsys.service.DataDictionaryService;
import cn.appsys.service.DevUserService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;
@Controller
@RequestMapping("/dev")
public class DevUserControll {
//注入app版本信息service
@Resource(name="appVersionService")
private AppVersionService appVersionService;
// 注入前台service对象
@Resource(name = "devUserService")
private DevUserService devUserService;
// 注入app信息service对象
@Resource(name = "appInfoService")
private AppInfoService appInfoService;
// 注入分类service对象
@Resource(name = "appCategoryService")
private AppCategoryService appCategoryService;
// 获取平台service对象
@Resource(name = "dataDictionaryService")
private DataDictionaryService dataDictionaryService;
@RequestMapping(value = "/login")
public String login() {
return "devlogin";
}
// 开发者登录
@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
public String doLogin(@RequestParam String devCode, @RequestParam String devPassword, HttpSession session,
HttpServletRequest request) {
DevUser devUser = devUserService.login(devCode);
if (devUser != null) {
if (devUser.getDevPassword().equals(devPassword)) {
session.setAttribute(Constants.DEV_USER_SESSION, devUser);
return "developer/main";
} else {
request.setAttribute("error", "账号或密码错误!");
return "devlogin";
}
} else {
request.setAttribute("error", "账号不存在!");
return "devlogin";
}
}
@RequestMapping("logout")
public Object logout() {
return "../../index";
}
// 去main主页面
@RequestMapping(value = "/flatform/main")
public String main() {
return "developer/main";
}
// 所有的app
@RequestMapping(value = "/flatform/getAppList.do")
public Object appList(Model model,
@RequestParam(value = "querySoftwareName", required = false) String querySoftwareName,
@RequestParam(value = "queryStatus", required = false) String queryStatus,
@RequestParam(value = "queryFlatformId", required = false) String queryFlatformId,
@RequestParam(value = "queryCategoryLevel1", required = false) String queryCategoryLevel1,
@RequestParam(value = "queryCategoryLevel2", required = false) String queryCategoryLevel2,
@RequestParam(value = "queryCategoryLevel3", required = false) String queryCategoryLevel3,
@RequestParam(value = "devId", required = false) Integer devId,
@RequestParam(value = "pageIndex", required = false) Integer pageIndex) {
List<AppInfo> appInfoList = null;// app信息集合
List<AppCategory> categoryLevel1List = null;// 一级分类集合
List<DataDictionary> flatFormList = null;// 平台集合
List<DataDictionary> statusList = null;
String _querySoftwareName = null;// 软件名称
Integer _queryStatus = 0;// 状态
Integer _queryFlatformId = 0;// 所属平台
Integer _queryCategoryLevel1 = 0;// 一级分类
Integer _queryCategoryLevel2 = 0;// 二级分类
Integer _queryCategoryLevel3 = 0;// 三级分类
Integer _devId = 0;// 作者id
Integer _pageIndex = 1;// 当前页码
int _pageSize = 5;// 设置页面大小
if (querySoftwareName != null) {
_querySoftwareName = querySoftwareName;
model.addAttribute("querySoftwareName", querySoftwareName);
}
if (queryStatus != null&&queryStatus!="") {
_queryStatus = Integer.valueOf(queryStatus);
model.addAttribute("queryStatus", queryStatus);
}
if (queryFlatformId != null&&queryFlatformId!="") {
_queryFlatformId = Integer.valueOf(queryFlatformId);
model.addAttribute("queryFlatformId", queryFlatformId);
}
if (queryCategoryLevel1 != null&&queryCategoryLevel1!="") {
_queryCategoryLevel1 = Integer.valueOf(queryCategoryLevel1);
model.addAttribute("queryCategoryLevel1", queryCategoryLevel1);
}
if (queryCategoryLevel2 != null&&queryCategoryLevel2!="") {
_queryCategoryLevel2 = Integer.valueOf(queryCategoryLevel2);
model.addAttribute("queryCategoryLevel2", queryCategoryLevel2);
}
if (queryCategoryLevel3 != null&&queryCategoryLevel3!="") {
_queryCategoryLevel3 = Integer.valueOf(queryCategoryLevel3);
model.addAttribute("queryCategoryLevel3", queryCategoryLevel3);
}
if (devId != null) {
_devId = Integer.valueOf(devId);
model.addAttribute("devId", devId);
}
if (pageIndex != null) {
_pageIndex = Integer.valueOf(pageIndex);
}
int total = appInfoService.getAllAppInfo(_querySoftwareName, _queryStatus, _queryCategoryLevel1,
_queryCategoryLevel2, _queryCategoryLevel3, _queryFlatformId, _devId, _pageIndex, _pageSize);
System.err.println("软件名称" + _querySoftwareName + "状态" + _queryStatus + "一级分类" + _queryCategoryLevel1 + "二级分类"
+ _queryCategoryLevel2 + "三级分类" + _queryCategoryLevel3 + _queryFlatformId + "所属平台id" + _devId + "开发者id"
+ _pageIndex + "当前页码" + _pageIndex + "显示几条" + _pageSize + "总数量" + total);
PageSupport pages = new PageSupport();// 实例化page对象
pages.setPageSize(_pageSize);// 设置页面大小
pages.setTotalCount(total);// 设置总数量
pages.setCurrentPageNo(_pageIndex);// 设置当前页码
int pageCount = pages.getTotalPageCount();// 总页数
if (_pageIndex < 1) {
_pageIndex = 1;
} else if (_pageIndex > pageCount) {
_pageIndex = pageCount;
}
appInfoList = appInfoService.getAppInfoList(_querySoftwareName, _queryStatus, _queryCategoryLevel1,
_queryCategoryLevel2, _queryCategoryLevel3, _queryFlatformId, _devId, _pageIndex, _pageSize);
for(AppInfo info:appInfoList) {
System.err.println("getVersionNo"+info.getVersionNo());
}
categoryLevel1List = appCategoryService.getAppCategoryByParentId(null);
flatFormList = dataDictionaryService.getAllDataDictionary();
statusList = dataDictionaryService.getAllStatus();
model.addAttribute("statusList", statusList);
model.addAttribute("flatFormList", flatFormList);
model.addAttribute("categoryLevel1List", categoryLevel1List);
model.addAttribute("appInfoList", appInfoList);
model.addAttribute("pages", pages);
return "developer/appinfolist";
}
// ajax加载平台
@RequestMapping("/flatform/datadictionarylist.json")
@ResponseBody
public Object loadFlatform() {
List<DataDictionary> flatFormList = null;// 平台集合
flatFormList = dataDictionaryService.getAllDataDictionary();
return flatFormList;
}
// ajax加载二三级分类
@RequestMapping("/flatform/categorylevellist.json")
@ResponseBody
public Object loadLevel(@RequestParam(value = "pid") String pid) {
List<AppCategory> appCategories = appCategoryService.getAppCategoryByParentId(pid);
return appCategories;
}
//带着Appinfo对象去新增APP页面
@RequestMapping(value = "/flatform/add",method=RequestMethod.GET)
public Object addAccount(@ModelAttribute("appInfo") AppInfo appInfo) {
return "developer/appinfoadd";
}
// ajax验证apkname是否重复
@RequestMapping("/flatform/apkexist.json")
@ResponseBody
public Object checkApk(@RequestParam(value = "APKName") String APKName) {
HashMap<String, Object> map = new HashMap<String, Object>();
if (APKName == null || APKName == "") {
map.put("APKName", "empty");
return map;
} else if (appInfoService.queryApkName(APKName)) {
map.put("APKName", "noexist");
return map;
} else {
map.put("APKName", "exist");
return map;
}
}
// 单文件上传绑定数据执行新增操作
@RequestMapping(value = "/flatform/appinfoaddsave", method = RequestMethod.POST)
public Object appInfoAddSave(AppInfo appinfo,
HttpSession session,
HttpServletRequest request,
@RequestParam(value = "a_logoPicPath", required = false) MultipartFile attach) {
String logoPicPath = null;
String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
if (!attach.isEmpty()) {// 自带的验证是否为空的方法
String oldFileName = attach.getOriginalFilename();// 原文件名
String prefix = FilenameUtils.getExtension(oldFileName);// 源文件后缀
int filesize = 500000;
if (attach.getSize() > filesize) {
// 上传大小不能超出500kb
request.setAttribute("fileUploadError", "* 上传大小不得超过500KB");
return "developer/appinfoadd";
} else if (prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpg")
|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
File targeFile = new File(path, fileName);
if (!targeFile.exists()) {
targeFile.mkdirs();// 不存在就创建
}
// 保存
try {
attach.transferTo(targeFile);
// 将这张图片写入磁盘
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("fileUploadError", "* 上传失败!");
return "useradd";
}
logoPicPath = path + File.separator + fileName;
logoPicPath=logoPicPath.substring(logoPicPath.length()-61);
} else {
request.setAttribute("fileUploadError", "* 上传图片格式不正确");
return "useradd";
}
}
appinfo.setCreatedBy(((DevUser)session.getAttribute(Constants.DEV_USER_SESSION)).getId());//用户id
appinfo.setDevId(((DevUser)session.getAttribute(Constants.DEV_USER_SESSION)).getId());//开发者id
appinfo.setDevId(((DevUser)session.getAttribute(Constants.DEV_USER_SESSION)).getId());
appinfo.setCreationDate(new Date());//创建时间
appinfo.setLogoLocPath(path);
appinfo.setLogoPicPath(logoPicPath);
if(appInfoService.addAppinfo(appinfo)) {
return "redirect:/dev/flatform/getAppList.do";
}
return "developer/appinfoadd";
}
//去新增版本页面
@RequestMapping("/flatform/appversionadd")
public Object appVersionAdd(Model model
,@RequestParam(value="id")String id){
List<AppVersion> appVersionList=appVersionService.getAppVersionById(Integer.valueOf(id));
model.addAttribute("appVersionList", appVersionList);
model.addAttribute("appId", id);
return "developer/appversionadd";
}
//新增版本操作
@RequestMapping(value="/flatform/addversionsave")
public Object addVersionSave(HttpServletRequest request,HttpSession session,
@RequestParam(value="appId")String appId,
@RequestParam(value="versionNo")String versionNo,
@RequestParam(value="versionSize")String versionSize,
@RequestParam(value="publishStatus")String publishStatus,
@RequestParam(value="versionInfo")String versionInfo,
@RequestParam(value="a_downloadLink")MultipartFile attach) {
String logoPicPath = null;
String fileName=null;
String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
if (!attach.isEmpty()) {// 自带的验证是否为空的方法
String oldFileName = attach.getOriginalFilename();// 原文件名
String prefix = FilenameUtils.getExtension(oldFileName);// 源文件后缀
int filesize = 10000000;
if (attach.getSize() > filesize) {
// 上传大小不能超出500kb
request.setAttribute("fileUploadError", "* 上传大小不得超出10000000KB");
return "developer/appversionadd";
} else if (prefix.equalsIgnoreCase("apk")) {
fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000)+"_Personal.apk";
File targeFile = new File(path, fileName);
if (!targeFile.exists()) {
targeFile.mkdirs();// 不存在就创建
}
// 保存
try {
attach.transferTo(targeFile);
// 将这张图片写入磁盘
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("fileUploadError", "* 上传失败!");
return "developer/appinfoadd";
}
logoPicPath = path + File.separator + fileName;
} else {
request.setAttribute("fileUploadError", "* 上传文件格式不正确");
return "developer/appversionadd";
}
}
AppVersion appVersion=new AppVersion();
appVersion.setAppId(Integer.valueOf(appId));//appid
appVersion.setVersionNo(versionNo);//版本号
appVersion.setVersionInfo(versionInfo);//版本信息
appVersion.setPublishStatus(Integer.valueOf(publishStatus));//版本状态
appVersion.setDownloadLink(path);//apk下载地址
BigDecimal size=new BigDecimal(versionSize);
appVersion.setVersionSize(size);//版本大小
appVersion.setCreatedBy(((DevUser)session.getAttribute(Constants.DEV_USER_SESSION)).getId());
//创建者
appVersion.setModifyBy(((DevUser)session.getAttribute(Constants.DEV_USER_SESSION)).getId());
//更新者
appVersion.setModifyDate(new Date());//更新时间
appVersion.setCreationDate(new Date());//创建时间
appVersion.setApkLocPath(path);//服务器存储路径
appVersion.setApkFileName(fileName);//上传的apk文件名称
if (appVersionService.addAppVersion(appVersion)) {
Integer id=appVersionService.newId(Integer.valueOf(appId));//查询这个app的最新版本id
if(id!=null) {
if(appInfoService.modifyVersId(id,Integer.valueOf(appId))) {
return "redirect:/dev/flatform/getAppList.do";
}
}
}
return "developer/appversionadd";
}
//接受用户的请求将此app的版本信息查询出来让用用户修改
@RequestMapping("/flatform/appversionmodify")
public Object appVersionmoDify(Model model,
@RequestParam("vid")String vid,
@RequestParam("aid")String aid) {
AppVersion appVersion=appVersionService.getAppVersion(Integer.valueOf(vid), Integer.valueOf(aid));
List<AppVersion>appVersionList=appVersionService.getAppVersionById(Integer.valueOf(aid));
model.addAttribute("appVersionList", appVersionList);
model.addAttribute("appVersion", appVersion);
return "developer/appversionmodify";
}
//使用ajax删除该app的apk文件
@RequestMapping("/flatform/delfile.json")
@ResponseBody
public Object delFile(@RequestParam("id")String id){
HashMap<Object, String>map=new HashMap<Object, String>();
if(appVersionService.delAppVersionById(Integer.valueOf(id))) {
map.put("result", "success");
}else {
map.put("result", "failed");
}
return map;
}
//修改版本信息
@RequestMapping(value="/flatform/appversionmodifysave",method=RequestMethod.POST)
public Object appversionmodifysave(HttpServletRequest request,
HttpSession session,
@RequestParam("attach")MultipartFile attach,
@RequestParam("id")String id,
@RequestParam("appId")String appId,
@RequestParam("versionNo")String versionNo,
@RequestParam("versionSize")String versionSize,
@RequestParam("publishStatus")String publishStatus,
@RequestParam("versionInfo")String versionInfo) {
String logoPicPath = null;
String fileName=null;
String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
if (!attach.isEmpty()) {// 自带的验证是否为空的方法
String oldFileName = attach.getOriginalFilename();// 原文件名
String prefix = FilenameUtils.getExtension(oldFileName);// 源文件后缀
int filesize = 10000000;
if (attach.getSize() > filesize) {
// 上传大小不能超出500kb
request.setAttribute("fileUploadError", "* 上传大小不得超出10000000KB");
return "developer/appversionadd";
} else if (prefix.equalsIgnoreCase("apk")) {
fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.apk";
File targeFile = new File(path, fileName);
if (!targeFile.exists()) {
targeFile.mkdirs();// 不存在就创建
}
// 保存
try {
attach.transferTo(targeFile);
// 将这张图片写入磁盘
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("fileUploadError", "* 上传失败!");
return "developer/appinfoadd";
}
logoPicPath = path + File.separator + fileName;
}else{
request.setAttribute("fileUploadError","* 上传文件格式不正确");
return "developer/appversionadd";
}
}
AppVersion appVersion=new AppVersion();
appVersion.setId(Integer.valueOf(id));//版本id
appVersion.setAppId(Integer.valueOf(appId));//appId
appVersion.setVersionNo(versionNo);//版本号
appVersion.setVersionInfo(versionInfo);//版本信息
BigDecimal bigDecimal=new BigDecimal(versionSize);
appVersion.setVersionSize(bigDecimal);//版本大小
appVersion.setPublishStatus(Integer.valueOf(publishStatus));//版本状态
appVersion.setDownloadLink(path);//下载地址
appVersion.setModifyBy(((DevUser)session.getAttribute(Constants.DEV_USER_SESSION)).getId());
appVersion.setModifyDate(new Date());//更新时间
appVersion.setApkLocPath(path);////服务器存储地址
appVersion.setApkFileName(fileName);//文件名字
if(appVersionService.modifyAppVersion(appVersion)) {
return "redirect:/dev/flatform/getAppList.do";
}
return "developer/appversionmodify";
}
//按照id吧信息都查出来去到修改页面
@RequestMapping("/flatform/appinfomodify")
public Object appinfoModify(Model model,@RequestParam("id")String id) {
AppInfo appInfo=appInfoService.getAppinfoById(Integer.valueOf(id), null);
System.err.println(appInfo.getAppInfo());
model.addAttribute("appInfo", appInfo);
return "developer/appinfomodify";
}
//修改app信息
@RequestMapping(value="/flatform/appinfomodifysave",method=RequestMethod.POST)
public Object modifyAppInfo(
HttpServletRequest request,
HttpSession session,
@Param("id")String id,
@Param("softwareName")String softwareName,
@Param("APKName")String APKName,
@Param("supportROM")String supportROM,
@Param("interfaceLanguage")String interfaceLanguage,
@Param("softwareSize")String softwareSize,
@Param("downloads")String downloads,
@Param("flatformId")String flatformId,
@Param("categoryLevel1")String categoryLevel1,
@Param("categoryLevel2")String categoryLevel2,
@Param("categoryLevel3")String categoryLevel3,
@Param("statusName")String statusName,
@Param("appInfo")String appInfo,
@Param("attach")MultipartFile attach) {
String logoPicPath = null;
String fileName=null;
String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
if (!attach.isEmpty()) {// 自带的验证是否为空的方法
String oldFileName = attach.getOriginalFilename();// 原文件名
String prefix = FilenameUtils.getExtension(oldFileName);// 源文件后缀
int filesize = 10000000;
if (attach.getSize() > filesize) {
// 上传大小不能超出500kb
request.setAttribute("fileUploadError", "* 上传大小不得超出10000000KB");
return "developer/appinfomodify";
} else if (prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpg")
|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){
fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
File targeFile = new File(path, fileName);
if (!targeFile.exists()) {
targeFile.mkdirs();// 不存在就创建
}
// 保存
try {
attach.transferTo(targeFile);
// 将这张图片写入磁盘
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("fileUploadError", "* 上传失败!");
return "developer/appinfomodify";
}
logoPicPath=path + File.separator + fileName;
} else {
request.setAttribute("fileUploadError", "* 上传文件格式不正确");
return "developer/appinfomodify";
}
}
AppInfo apInfo=new AppInfo();
apInfo.setId(Integer.valueOf(id));
apInfo.setSoftwareName(softwareName);
apInfo.setAPKName(APKName);
apInfo.setSupportROM(supportROM);
apInfo.setInterfaceLanguage(interfaceLanguage);
BigDecimal bigDecimal=new BigDecimal(softwareSize);
apInfo.setSoftwareSize(bigDecimal);
apInfo.setDownloads(Integer.valueOf(downloads));
apInfo.setFlatformId(Integer.valueOf(flatformId));
apInfo.setCategoryLevel1(Integer.valueOf(categoryLevel1));
apInfo.setCategoryLevel2(Integer.valueOf(categoryLevel2));
apInfo.setCategoryLevel3(Integer.valueOf(categoryLevel3));
apInfo.setStatusName(statusName);
apInfo.setAppInfo(appInfo);
apInfo.setModifyBy(((DevUser)session.getAttribute(Constants.DEV_USER_SESSION)).getId());
apInfo.setModifyDate(new Date());
apInfo.setLogoPicPath(path);
apInfo.setLogoLocPath(logoPicPath);
if(apInfo.getStatusName().equals("待审核")) {
apInfo.setStatus(1);
}else if(apInfo.getStatusName().equals("审核通过")) {
apInfo.setStatus(2);
}else if(apInfo.getStatusName().equals("审核未通过")) {
apInfo.setStatus(3);
}else if(apInfo.getStatusName().equals("已上架")) {
apInfo.setStatus(4);
}else if(apInfo.getStatusName().equals("已下架")) {
apInfo.setStatus(5);
}
if(appInfoService.modifyAppInfo(apInfo)) {
return "redirect:/dev/flatform/getAppList.do";
}
return "developer/appinfomodify";
}
//使用rest风格查看app信息
@RequestMapping(value="/flatform/appview/{id}")
public Object appView(Model model,@PathVariable("id")String id) {
List<AppVersion>appVersionList=appVersionService.getAppVersionById(Integer.valueOf(id));
AppInfo appInfo=appInfoService.getAppinfoById(Integer.valueOf(id), null);
model.addAttribute("appInfo", appInfo);
model.addAttribute("appVersionList", appVersionList);
System.err.println(appInfo.getLogoPicPath());
return "developer/appinfoview";
}
//删除app信息
@RequestMapping("/flatform/delapp.json")
@ResponseBody
public Object delApp(@RequestParam("id")String id) {
HashMap<String, String>map=new HashMap<String, String>();
if(appInfoService.delApp(Integer.valueOf(id))) {
map.put("delResult", "true");
}else {
map.put("delResult", "false");
}
return map;
}
//使用rest风格的ajax方式来操作
@RequestMapping(value="/flatform/{appId}/sale.json",method=RequestMethod.PUT)
@ResponseBody
public Object sale(@PathVariable("appId")String id,HttpSession session) {
HashMap<String, String>map=new HashMap<String, String>();
Integer idInteger=0;
try {
idInteger=Integer.parseInt(id);
} catch (Exception e) {
idInteger=0;
}
map.put("errorCode", "0");
if (idInteger>0) {
try {
DevUser devUser=(DevUser)session.getAttribute(Constants.DEV_USER_SESSION);
AppInfo appInfo=new AppInfo();
appInfo.setId(idInteger);
appInfo.setModifyBy(idInteger);
if(appInfoService.appsysUpdateSaleStatusById(appInfo)) {
map.put("resultMsg", "success");
}else {
map.put("resultMsg", "failed");
}
} catch (Exception e) {
map.put("errorCode", "exeception000001");
}
}else {
map.put("errorCode", "exception000001");
}
System.err.println(map.toString());
return map;
}
}
| [
"1325420188@qq.com"
] | 1325420188@qq.com |
6fd03cca1de11f1ab31fc1b68db8fa962e4c7df1 | 4a8013ffc2f166506fc709698f2242db6b8dde41 | /src/main/java/org/elissa/web/preprocessing/impl/PreprocessingServiceImpl.java | 87731ad3f4f54eaebf3acc91d80996f693f5b03f | [] | no_license | tsurdilo/elissa | a7a255c436420b2cbd75b2f7aac6f49aab6c0b1d | d44604bd6b3ef188563bb4dabd25aae4b3f7a69f | refs/heads/master | 2021-01-01T05:39:53.149047 | 2012-02-05T22:18:20 | 2012-02-05T22:18:20 | 3,308,767 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,210 | java | /**
* Copyright 2010 JBoss 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 org.elissa.web.preprocessing.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.elissa.web.preprocessing.IDiagramPreprocessingService;
import org.elissa.web.preprocessing.IDiagramPreprocessingUnit;
import org.elissa.web.profile.IDiagramProfile;
/**
*
* @author Tihomir Surdilovic
*/
public class PreprocessingServiceImpl implements IDiagramPreprocessingService {
public static PreprocessingServiceImpl INSTANCE = new PreprocessingServiceImpl();
private Map<String, IDiagramPreprocessingUnit> _registry = new HashMap<String, IDiagramPreprocessingUnit>();
public Collection<IDiagramPreprocessingUnit> getRegisteredPreprocessingUnits(
HttpServletRequest request) {
Map<String, IDiagramPreprocessingUnit> preprocessingUnits = new HashMap<String, IDiagramPreprocessingUnit>(_registry);
return new ArrayList<IDiagramPreprocessingUnit>(preprocessingUnits.values());
}
public IDiagramPreprocessingUnit findPreprocessingUnit(
HttpServletRequest request, IDiagramProfile profile) {
Map<String, IDiagramPreprocessingUnit> preprocessingUnits = new HashMap<String, IDiagramPreprocessingUnit>(_registry);
return preprocessingUnits.get(profile.getName());
}
public void init(ServletContext context) {
_registry.put("default", new DefaultPreprocessingUnit(context));
_registry.put("jbpm", new JbpmPreprocessingUnit(context));
}
}
| [
"tsurdilo@redhat.com"
] | tsurdilo@redhat.com |
a8a912934afa3850bda3e0688985660b82e25d85 | 411b0a3216d3a74505d375bf48229ff6c7839600 | /main/animals/Bird.java | fb27ff02aa272d3d42e355e408101e4dd7b2c36e | [] | no_license | Khadijatng/projet_zoo_khadija | f9d54396e54352ccebdd2f61b6079a6b9899ddaf | d62349c2b58e65aaeddca5f25d4c894e27f48a68 | refs/heads/master | 2020-04-02T11:09:04.108550 | 2018-10-23T17:50:19 | 2018-10-23T17:50:19 | 154,373,465 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,438 | java | package main.animals;
public abstract class Bird implements Animals {
private String name;
private double poids;
private int eatCount;
private int drinkCount;
//Add other attributes
private String HairColor;
// constructor
public Bird(String name, double poids, String HairColor){
this.name = name;
this.poids = poids;
this.HairColor = HairColor;
this.eatCount = 0;
this.drinkCount = 0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPoids() {
return poids;
}
public void setPoids(double poids) {
this.poids = poids;
}
public int getEatCount() {
return eatCount;
}
public void setEatCount(int eatCount) {
this.eatCount = eatCount;
}
public int getDrinkCount() {
return drinkCount;
}
public void setDrinkCount(int drinkCount) {
this.drinkCount = drinkCount;
}
public String getHairColor() {
return HairColor;
}
public void setHairColor(String hairColor) {
HairColor = hairColor;
}
public String toString() {
return getName();
}
public void eat(String food) {
this.eatCount++;
}
public void drink(){
this.drinkCount++;
}
public abstract String scream();
}
| [
"khadija.azibou@gmail.com"
] | khadija.azibou@gmail.com |
c4470a5fbfa315444140b0d78a9a7ea3e2dd568d | 32b72e1dc8b6ee1be2e80bb70a03a021c83db550 | /ast_results/geometer_FBReaderJ/fbreader/app/src/main/java/org/geometerplus/fbreader/network/IPredefinedNetworkLink.java | 3bf54e1a809cef0b319216e280fe74893d8dffda | [] | no_license | cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning | d90c41a17e88fcd99d543124eeb6e93f9133cb4a | 0564143d92f8024ff5fa6b659c2baebf827582b1 | refs/heads/master | 2020-07-13T13:53:40.297493 | 2019-01-11T11:51:18 | 2019-01-11T11:51:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 187 | java | // isComment
package org.geometerplus.fbreader.network;
public interface isClassOrIsInterface extends INetworkLink {
String isMethod();
boolean isMethod(String isParameter);
}
| [
"matheus@melsolucoes.net"
] | matheus@melsolucoes.net |
7445e0a784771397c19743a476ff9f1e26c3f1da | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/19/19_0c654d36f0c2d05a4777bd037f3ee50c8c375adf/ReviewPage/19_0c654d36f0c2d05a4777bd037f3ee50c8c375adf_ReviewPage_s.java | 5e8cc1011fd3daf9a19c9ca8f201fa563d5dfe63 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 27,963 | java | /*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.update.internal.ui.wizards;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.*;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.operation.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.*;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.dialogs.*;
import org.eclipse.ui.help.*;
import org.eclipse.update.core.*;
import org.eclipse.update.internal.operations.*;
import org.eclipse.update.internal.ui.*;
import org.eclipse.update.internal.ui.model.*;
import org.eclipse.update.internal.ui.parts.*;
import org.eclipse.update.operations.*;
import org.eclipse.update.search.*;
public class ReviewPage
extends BannerPage
implements IUpdateSearchResultCollector {
private ArrayList jobs;
private Label counterLabel;
private CheckboxTableViewer tableViewer;
private IStatus validationStatus;
private Collection problematicFeatures = new HashSet();
// feature that was recently selected or null
private IFeature newlySelectedFeature;
//
private FeatureStatus lastDisplayedStatus;
private PropertyDialogAction propertiesAction;
private Text descLabel;
private Button statusButton;
private Button moreInfoButton;
private Button propertiesButton;
private Button filterCheck;
private ContainmentFilter filter = new ContainmentFilter();
private SearchRunner searchRunner;
private int LABEL_ORDER = 1;
private int VERSION_ORDER = 1;
private int PROVIDER_ORDER = 1;
class JobsContentProvider
extends DefaultContentProvider
implements IStructuredContentProvider {
public Object[] getElements(Object inputElement) {
return jobs.toArray();
}
}
class JobsLabelProvider
extends SharedLabelProvider
implements ITableLabelProvider {
public String getColumnText(Object obj, int column) {
IInstallFeatureOperation job = (IInstallFeatureOperation) obj;
IFeature feature = job.getFeature();
switch (column) {
case 0 :
return feature.getLabel();
case 1 :
return feature
.getVersionedIdentifier()
.getVersion()
.toString();
case 2 :
return feature.getProvider();
}
return ""; //$NON-NLS-1$
}
public Image getColumnImage(Object obj, int column) {
if (column == 0) {
IFeature feature = ((IInstallFeatureOperation) obj).getFeature();
boolean patch = feature.isPatch();
boolean problematic=problematicFeatures.contains(feature);
if (patch) {
return get(UpdateUIImages.DESC_EFIX_OBJ, problematic? F_ERROR : 0);
} else {
return get(UpdateUIImages.DESC_FEATURE_OBJ, problematic? F_ERROR : 0);
}
}
return null;
}
}
class ContainmentFilter extends ViewerFilter {
public boolean select(Viewer v, Object parent, Object child) {
return !isContained((IInstallFeatureOperation) child);
}
private boolean isContained(IInstallFeatureOperation job) {
VersionedIdentifier vid = job.getFeature().getVersionedIdentifier();
for (int i = 0; i < jobs.size(); i++) {
IInstallFeatureOperation candidate = (IInstallFeatureOperation) jobs.get(i);
if (candidate.equals(job))
continue;
IFeature feature = candidate.getFeature();
if (includes(feature, vid,null))
return true;
}
return false;
}
private boolean includes(IFeature feature, VersionedIdentifier vid, ArrayList cycleCandidates) {
try {
if (cycleCandidates == null)
cycleCandidates = new ArrayList();
if (cycleCandidates.contains(feature))
throw Utilities.newCoreException(UpdateUI.getFormattedMessage("InstallWizard.ReviewPage.cycle", feature.getVersionedIdentifier().toString()), null); //$NON-NLS-1$
else
cycleCandidates.add(feature);
IFeatureReference[] irefs =
feature.getIncludedFeatureReferences();
for (int i = 0; i < irefs.length; i++) {
IFeatureReference iref = irefs[i];
IFeature ifeature = iref.getFeature(null);
VersionedIdentifier ivid =
ifeature.getVersionedIdentifier();
if (ivid.equals(vid))
return true;
if (includes(ifeature, vid, cycleCandidates))
return true;
}
return false;
} catch (CoreException e) {
return false;
} finally {
// after this feature has been DFS-ed, it is no longer a cycle candidate
cycleCandidates.remove(feature);
}
}
}
class FeaturePropertyDialogAction extends PropertyDialogAction {
private IStructuredSelection selection;
public FeaturePropertyDialogAction(
Shell shell,
ISelectionProvider provider) {
super(shell, provider);
}
public IStructuredSelection getStructuredSelection() {
return selection;
}
public void selectionChanged(IStructuredSelection selection) {
this.selection = selection;
}
}
/**
* Constructor for ReviewPage2
*/
public ReviewPage(SearchRunner searchRunner, ArrayList jobs) {
super("Review"); //$NON-NLS-1$
setTitle(UpdateUI.getString("InstallWizard.ReviewPage.title")); //$NON-NLS-1$
setDescription(UpdateUI.getString("InstallWizard.ReviewPage.desc")); //$NON-NLS-1$
UpdateUI.getDefault().getLabelProvider().connect(this);
this.searchRunner = searchRunner;
setBannerVisible(false);
this.jobs = jobs;
if (this.jobs==null) this.jobs = new ArrayList();
}
public void dispose() {
UpdateUI.getDefault().getLabelProvider().disconnect(this);
super.dispose();
}
public void setVisible(boolean visible) {
super.setVisible(visible);
// when searching for updates, only nested patches can be shown.
// when searching for features, features and patches can be shown
String filterText = filterCheck.getText();
String filterFeatures = UpdateUI.getString("InstallWizard.ReviewPage.filterFeatures"); //$NON-NLS-1$
String filterPatches = UpdateUI.getString("InstallWizard.ReviewPage.filterPatches"); //$NON-NLS-1$
boolean isUpdateSearch = searchRunner.getSearchProvider() instanceof ModeSelectionPage;
if (isUpdateSearch && filterText.equals(filterFeatures))
filterCheck.setText(filterPatches);
else if ( !isUpdateSearch && filterText.equals(filterPatches))
filterCheck.setText(filterFeatures);
if (visible && searchRunner.isNewSearchNeeded()) {
jobs.clear();
tableViewer.refresh();
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
searchRunner.runSearch();
performPostSearchProcessing();
}
});
}
}
private void performPostSearchProcessing() {
BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
public void run() {
if (tableViewer != null) {
tableViewer.refresh();
tableViewer.getTable().layout(true);
if (searchRunner.getSearchProvider() instanceof ModeSelectionPage) {
selectTrueUpdates();
}
}
pageChanged();
}
});
}
private void selectTrueUpdates() {
ArrayList trueUpdates = new ArrayList();
for (int i=0; i<jobs.size(); i++) {
IInstallFeatureOperation job = (IInstallFeatureOperation)jobs.get(i);
if (!UpdateUtils.isPatch(job.getFeature()))
trueUpdates.add(job);
}
tableViewer.setCheckedElements(trueUpdates.toArray());
}
/**
* @see DialogPage#createControl(Composite)
*/
public Control createContents(Composite parent) {
Composite client = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginWidth = layout.marginHeight = 0;
client.setLayout(layout);
Label label = new Label(client, SWT.NULL);
label.setText(UpdateUI.getString("InstallWizard.ReviewPage.label")); //$NON-NLS-1$
GridData gd = new GridData();
gd.horizontalSpan = 2;
label.setLayoutData(gd);
createTable(client);
Composite buttonContainer = new Composite(client, SWT.NULL);
gd = new GridData(GridData.FILL_VERTICAL);
buttonContainer.setLayoutData(gd);
layout = new GridLayout();
layout.marginWidth = 0;
layout.marginHeight = 0;
buttonContainer.setLayout(layout);
Button button = new Button(buttonContainer, SWT.PUSH);
button.setText(UpdateUI.getString("InstallWizard.ReviewPage.selectAll")); //$NON-NLS-1$
gd =
new GridData(
GridData.HORIZONTAL_ALIGN_FILL
| GridData.VERTICAL_ALIGN_BEGINNING);
button.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(button);
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleSelectAll(true);
}
});
button = new Button(buttonContainer, SWT.PUSH);
button.setText(UpdateUI.getString("InstallWizard.ReviewPage.deselectAll")); //$NON-NLS-1$
gd =
new GridData(
GridData.HORIZONTAL_ALIGN_FILL
| GridData.VERTICAL_ALIGN_BEGINNING);
button.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(button);
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleSelectAll(false);
}
});
moreInfoButton = new Button(buttonContainer, SWT.PUSH);
moreInfoButton.setText(UpdateUI.getString("InstallWizard.ReviewPage.moreInfo")); //$NON-NLS-1$
gd =
new GridData(
GridData.HORIZONTAL_ALIGN_FILL
| GridData.VERTICAL_ALIGN_BEGINNING);
moreInfoButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(moreInfoButton);
moreInfoButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleMoreInfo();
}
});
moreInfoButton.setEnabled(false);
propertiesButton = new Button(buttonContainer, SWT.PUSH);
propertiesButton.setText(UpdateUI.getString("InstallWizard.ReviewPage.properties")); //$NON-NLS-1$
gd =
new GridData(
GridData.HORIZONTAL_ALIGN_FILL
| GridData.VERTICAL_ALIGN_BEGINNING);
propertiesButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(propertiesButton);
propertiesButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleProperties();
}
});
propertiesButton.setEnabled(false);
statusButton = new Button(buttonContainer, SWT.PUSH);
statusButton.setText(UpdateUI.getString("InstallWizard.ReviewPage.showStatus")); //$NON-NLS-1$
gd =
new GridData(
GridData.HORIZONTAL_ALIGN_FILL
| GridData.VERTICAL_ALIGN_BEGINNING);
statusButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(statusButton);
statusButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
showStatus();
}
});
//new Label(client, SWT.NULL);
counterLabel = new Label(client, SWT.NULL);
gd = new GridData();
gd.horizontalSpan = 2;
counterLabel.setLayoutData(gd);
filterCheck = new Button(client, SWT.CHECK);
filterCheck.setText(UpdateUI.getString("InstallWizard.ReviewPage.filterFeatures")); //$NON-NLS-1$
filterCheck.setSelection(false);
//tableViewer.addFilter(filter);
filterCheck.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (filterCheck.getSelection()) {
// make sure model is local
if (downloadIncludedFeatures()) {
tableViewer.addFilter(filter);
} else {
filterCheck.setSelection(false);
}
} else {
tableViewer.removeFilter(filter);
}
pageChanged();
}
});
gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan = 2;
filterCheck.setLayoutData(gd);
pageChanged();
WorkbenchHelp.setHelp(client, "org.eclipse.update.ui.MultiReviewPage2"); //$NON-NLS-1$
Dialog.applyDialogFont(parent);
return client;
}
private void createTable(Composite parent) {
SashForm sform = new SashForm(parent, SWT.VERTICAL);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.widthHint = 250;
gd.heightHint =100;
sform.setLayoutData(gd);
TableLayoutComposite composite= new TableLayoutComposite(sform, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
tableViewer =
CheckboxTableViewer.newCheckList(
composite,
SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
Table table = tableViewer.getTable();
table.setHeaderVisible(true);
TableColumn column = new TableColumn(table, SWT.NULL);
column.setText(UpdateUI.getString("InstallWizard.ReviewPage.feature")); //$NON-NLS-1$
column.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
LABEL_ORDER *= -1;
tableViewer.setSorter(
new FeatureSorter(
FeatureSorter.FEATURE_LABEL,
LABEL_ORDER,
VERSION_ORDER,
PROVIDER_ORDER));
}
});
column = new TableColumn(table, SWT.NULL);
column.setText(UpdateUI.getString("InstallWizard.ReviewPage.version")); //$NON-NLS-1$
column.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
VERSION_ORDER *= -1;
tableViewer.setSorter(
new FeatureSorter(
FeatureSorter.FEATURE_VERSION,
LABEL_ORDER,
VERSION_ORDER,
PROVIDER_ORDER));
}
});
column = new TableColumn(table, SWT.NULL);
column.setText(UpdateUI.getString("InstallWizard.ReviewPage.provider")); //$NON-NLS-1$
column.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PROVIDER_ORDER *= -1;
tableViewer.setSorter(
new FeatureSorter(
FeatureSorter.FEATURE_PROVIDER,
LABEL_ORDER,
VERSION_ORDER,
PROVIDER_ORDER));
}
});
//TableLayout layout = new TableLayout();
composite.addColumnData(new ColumnWeightData(5, 275, true));
composite.addColumnData(new ColumnWeightData(1, 80, true));
composite.addColumnData(new ColumnWeightData(5, 90, true));
//layout.addColumnData(new ColumnPixelData(225, true));
//layout.addColumnData(new ColumnPixelData(80, true));
//layout.addColumnData(new ColumnPixelData(140, true));
//table.setLayout(layout);
tableViewer.setContentProvider(new JobsContentProvider());
tableViewer.setLabelProvider(new JobsLabelProvider());
tableViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
newlySelectedFeature = null;
if(event.getChecked()){
// save checked feeature, so its error can be shown if any
Object checked = event.getElement();
if(checked instanceof IInstallFeatureOperation){
newlySelectedFeature= ((IInstallFeatureOperation)checked).getFeature();
}
}
tableViewer
.getControl()
.getDisplay()
.asyncExec(new Runnable() {
public void run() {
pageChanged();
}
});
}
});
tableViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent e) {
jobSelected((IStructuredSelection) e.getSelection());
}
});
tableViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
handleProperties();
}
});
tableViewer.setSorter(new FeatureSorter());
MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
fillContextMenu(manager);
}
});
table.setMenu(menuMgr.createContextMenu(table));
tableViewer.setInput(UpdateUI.getDefault().getUpdateModel());
tableViewer.setAllChecked(true);
descLabel = new Text(sform, SWT.BORDER|SWT.WRAP|SWT.MULTI|SWT.V_SCROLL);
descLabel.setEditable(false);
sform.setWeights(new int[] {10, 2});
}
private void fillContextMenu(IMenuManager manager) {
if (tableViewer.getSelection().isEmpty()) return;
Action action = new Action(UpdateUI.getString("InstallWizard.ReviewPage.prop")) { //$NON-NLS-1$
public void run() {
handleProperties();
}
};
manager.add(action);
}
public void accept(final IFeature feature) {
getShell().getDisplay().syncExec(new Runnable() {
public void run() {
IInstallFeatureOperation job = OperationsManager.getOperationFactory().createInstallOperation( null, feature,null, null, null);
ViewerFilter[] filters = tableViewer.getFilters();
boolean visible = true;
for (int i = 0; i < filters.length; i++) {
ViewerFilter filter = filters[i];
if (!filter.select(tableViewer, null, job)) {
visible = false;
break;
}
}
if (visible) {
tableViewer.add(job);
updateItemCount(0, -1);
}
jobs.add(job);
}
});
}
private void jobSelected(IStructuredSelection selection) {
IInstallFeatureOperation job = (IInstallFeatureOperation) selection.getFirstElement();
IFeature feature = job != null ? job.getFeature() : null;
IURLEntry descEntry = feature != null ? feature.getDescription() : null;
String desc = null;
if (descEntry != null)
desc = descEntry.getAnnotation();
if (desc == null)
desc = ""; //$NON-NLS-1$
descLabel.setText(desc);
propertiesButton.setEnabled(feature != null);
moreInfoButton.setEnabled(job != null && getMoreInfoURL(job) != null);
}
private void pageChanged() {
Object[] checked = tableViewer.getCheckedElements();
int totalCount = tableViewer.getTable().getItemCount();
updateItemCount(checked.length, totalCount);
if (checked.length > 0) {
validateSelection();
} else {
lastDisplayedStatus = null;
setErrorMessage(null);
setPageComplete(false);
validationStatus = null;
problematicFeatures.clear();
}
tableViewer.update(jobs.toArray(), null);
statusButton.setEnabled(validationStatus != null);
}
private void updateItemCount(int checkedCount, int totalCount) {
if (checkedCount == -1) {
Object[] checkedElements = tableViewer.getCheckedElements();
checkedCount = checkedElements.length;
}
if (totalCount == -1) {
totalCount = tableViewer.getTable().getItemCount();
}
String total = "" + totalCount; //$NON-NLS-1$
String selected = "" + checkedCount; //$NON-NLS-1$
counterLabel.setText(
UpdateUI.getFormattedMessage(
"InstallWizard.ReviewPage.counter", //$NON-NLS-1$
new String[] { selected, total }));
counterLabel.getParent().layout();
}
private void handleSelectAll(boolean select) {
tableViewer.setAllChecked(select);
tableViewer.getControl().getDisplay().asyncExec(new Runnable() {
public void run() {
pageChanged();
}
});
}
private void handleProperties() {
final IStructuredSelection selection =
(IStructuredSelection) tableViewer.getSelection();
final IInstallFeatureOperation job =
(IInstallFeatureOperation) selection.getFirstElement();
if (propertiesAction == null) {
propertiesAction =
new FeaturePropertyDialogAction(getShell(), tableViewer);
}
BusyIndicator
.showWhile(tableViewer.getControl().getDisplay(), new Runnable() {
public void run() {
SimpleFeatureAdapter adapter =
new SimpleFeatureAdapter(job.getFeature());
propertiesAction.selectionChanged(
new StructuredSelection(adapter));
propertiesAction.run();
}
});
}
private String getMoreInfoURL(IInstallFeatureOperation job) {
IURLEntry desc = job.getFeature().getDescription();
if (desc != null) {
URL url = desc.getURL();
return (url == null) ? null : url.toString();
}
return null;
}
private void handleMoreInfo() {
IStructuredSelection selection =
(IStructuredSelection) tableViewer.getSelection();
final IInstallFeatureOperation selectedJob =
(IInstallFeatureOperation) selection.getFirstElement();
BusyIndicator
.showWhile(tableViewer.getControl().getDisplay(), new Runnable() {
public void run() {
String urlName = getMoreInfoURL(selectedJob);
UpdateUI.showURL(urlName);
}
});
}
public IInstallFeatureOperation[] getSelectedJobs() {
Object[] selected = tableViewer.getCheckedElements();
IInstallFeatureOperation[] result = new IInstallFeatureOperation[selected.length];
System.arraycopy(selected, 0, result, 0, selected.length);
return result;
}
public void validateSelection() {
IInstallFeatureOperation[] jobs = getSelectedJobs();
validationStatus =
OperationsManager.getValidator().validatePendingChanges(jobs);
problematicFeatures.clear();
if (validationStatus != null) {
IStatus[] status = validationStatus.getChildren();
for (int i = 0; i < status.length; i++) {
IStatus singleStatus = status[i];
if(isSpecificStatus(singleStatus)){
IFeature f = ((FeatureStatus) singleStatus).getFeature();
problematicFeatures.add(f);
}
}
}
setPageComplete(validationStatus == null || validationStatus.getCode() == IStatus.WARNING);
updateWizardMessage();
}
private void showStatus() {
if (validationStatus != null) {
new StatusDialog().open();
}
}
/**
* Check whether status is relevant to show for
* a specific feature or is a other problem
* @param status
* @return true if status is FeatureStatus with
* specified feature and certain error codes
*/
private boolean isSpecificStatus(IStatus status){
if(!(status instanceof FeatureStatus)){
return false;
}
if(status.getSeverity()!=IStatus.ERROR){
return false;
}
FeatureStatus featureStatus = (FeatureStatus) status;
if(featureStatus.getFeature()==null){
return false;
}
return 0!= (featureStatus.getCode()
& FeatureStatus.CODE_CYCLE
+ FeatureStatus.CODE_ENVIRONMENT
+ FeatureStatus.CODE_EXCLUSIVE
+ FeatureStatus.CODE_OPTIONAL_CHILD
+ FeatureStatus.CODE_PREREQ_FEATURE
+ FeatureStatus.CODE_PREREQ_PLUGIN);
}
/**
* Update status in the wizard status area
*/
private void updateWizardMessage() {
if (validationStatus == null) {
lastDisplayedStatus=null;
setErrorMessage(null);
} else if (validationStatus.getCode() == IStatus.WARNING) {
lastDisplayedStatus=null;
setErrorMessage(null);
setMessage(validationStatus.getMessage(), IMessageProvider.WARNING);
} else {
// 1. Feature selected, creating a problem for it, show status for it
if(newlySelectedFeature !=null){
IStatus[] status = validationStatus.getChildren();
for(int s =0; s< status.length; s++){
if(isSpecificStatus(status[s])){
FeatureStatus featureStatus = (FeatureStatus)status[s];
if(newlySelectedFeature.equals(featureStatus.getFeature())){
lastDisplayedStatus=featureStatus;
setErrorMessage(featureStatus.getMessage());
return;
}
}
}
}
// 2. show old status if possible (it is still valid)
if(lastDisplayedStatus !=null){
IStatus[] status = validationStatus.getChildren();
for(int i=0; i<status.length; i++){
if(lastDisplayedStatus.equals(status[i])){
//lastDisplayedStatus=lastDisplayedStatus;
//setErrorMessage(status[i].getMessage());
return;
}
}
lastDisplayedStatus = null;
}
// 3. pick the first problem that is specific to some feature
IStatus[] status = validationStatus.getChildren();
for(int s =0; s< status.length; s++){
if(isSpecificStatus(status[s])){
lastDisplayedStatus = (FeatureStatus)status[s];
setErrorMessage(status[s].getMessage());
return;
}
}
// 4. display the first problem (no problems specify a feature)
if(status.length>0){
IStatus singleStatus=status[0];
setErrorMessage(singleStatus.getMessage());
}else{
// 5. not multi or empty multi status
setErrorMessage(UpdateUI.getString("InstallWizard.ReviewPage.invalid.long")); //$NON-NLS-1$
}
}
}
class StatusDialog extends ErrorDialog {
// Button detailsButton;
public StatusDialog() {
super(UpdateUI.getActiveWorkbenchShell(), UpdateUI
.getString("InstallWizard.ReviewPage.invalid.short"), null, //$NON-NLS-1$
validationStatus, IStatus.OK | IStatus.INFO
| IStatus.WARNING | IStatus.ERROR);
}
// protected Button createButton(
// Composite parent,
// int id,
// String label,
// boolean defaultButton) {
// Button b = super.createButton(parent, id, label, defaultButton);
// if(IDialogConstants.DETAILS_ID == id){
// detailsButton = b;
// }
// return b;
// }
public void create() {
super.create();
buttonPressed(IDialogConstants.DETAILS_ID);
// if(detailsButton!=null){
// detailsButton.dispose();
// }
}
}
/**
* @return true, if completed, false if canceled by the user
*/
private boolean downloadIncludedFeatures() {
try {
Downloader downloader = new Downloader(jobs);
getContainer().run(true, true, downloader);
return !downloader.isCanceled();
} catch (InvocationTargetException ite) {
} catch (InterruptedException ie) {
}
return true;
}
/**
* Runnable to resolve included feature references.
*/
class Downloader implements IRunnableWithProgress {
boolean canceled = false;
/**
* List of IInstallFeatureOperation
*/
ArrayList operations;
public Downloader(ArrayList installOperations) {
operations = installOperations;
}
public boolean isCanceled() {
return canceled;
}
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
for (int i = 0; i < operations.size(); i++) {
IInstallFeatureOperation candidate = (IInstallFeatureOperation) operations
.get(i);
IFeature feature = candidate.getFeature();
try {
IFeatureReference[] irefs = feature
.getRawIncludedFeatureReferences();
for (int f = 0; f < irefs.length; f++) {
if (monitor.isCanceled()) {
canceled = true;
return;
}
IFeatureReference iref = irefs[f];
IFeature ifeature = iref.getFeature(monitor);
}
} catch (CoreException e) {
}
}
if (monitor.isCanceled()) {
canceled = true;
}
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
e09d37de95eb61ad69c138c6c01db7b2ed268118 | f228f99b2ed749dd0e13191f8273241e8a2487b8 | /commerceue-app/src/main/java/com/ibm/commerce/search/ue/rest/ProductViewResource.java | 7603334739708e952fcfa707a6e16450bdee9661 | [] | no_license | wcsv9/wcs-product-dev-rep | 1afe60b36b510c54e44f448e65164d2fc8ed626e | 106339fcea500e410715a658827520211a7aa0c7 | refs/heads/master | 2021-08-17T23:55:28.955186 | 2020-04-02T19:27:10 | 2020-04-02T19:27:10 | 150,336,193 | 0 | 2 | null | 2020-03-10T18:20:48 | 2018-09-25T22:22:17 | JavaScript | UTF-8 | Java | false | false | 17,469 | java | package com.ibm.commerce.search.ue.rest;
/*
*-----------------------------------------------------------------
* IBM Confidential
*
* OCO Source Materials
*
* WebSphere Commerce
*
* (C) Copyright IBM Corp. 2016
*
* The source code for this program is not published or otherwise
* divested of its trade secrets, irrespective of what has
* been deposited with the U.S. Copyright Office.
*-----------------------------------------------------------------
*/
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.JSONObject;
import com.ibm.commerce.search.ue.pojo.SearchUERequest;
import com.ibm.commerce.search.ue.pojo.SearchUEResponse;
@Path("/search/productview")
@SwaggerDefinition(tags = { @Tag(name = "search - product view", description = "This resource handler contains customization extensions for the ProductView search service which is hosted on the Search server. The ProductView service is used for browsing product by category and performing keyword searches from the storefront, as well as displaying product level information such as associated attributes and the product's underlying items.") })
@Api(value = "/search/productview", tags = "search - product view")
public class ProductViewResource extends AbstractSearchResource {
private static final Logger LOGGER = Logger
.getLogger(ProductViewResource.class.getName());
private static final String CLASSNAME = ProductViewResource.class.getName();
private static final String SHORT_DESCRIPTION = "shortDescription";
private static final String FIELD5 = "field5";
private static final String NAME = "name";
private static final String USER_DATA = "UserData";
@POST
@Path("/postBySearchTerm")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search response after getting product details based on a search term. For example, update the short description of the given product.", response = SearchUEResponse.class)
public Response postFindProductsBySearchTerm(
@ApiParam(name = "ProductViewPost UE input", value = "The UE Request String", required = true) SearchUERequest uePostRequest) {
final String METHODNAME = "postFindProductsBySearchTerm(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePostRequest);
Response response = null;
try {
// Convert request into a map
List<JSONObject> arrayContentView = uePostRequest
.getContent();
Iterator<JSONObject> iterator = arrayContentView.iterator();
// Loop through each catentry_id
while (iterator.hasNext()) {
JSONObject jsonObject = iterator.next();
// get the user data object
if (jsonObject.get(USER_DATA) != null) {
JSONArray userDataArray = jsonObject.getJSONArray(USER_DATA);
if (!userDataArray.isEmpty()) {
JSONObject userDataJsonObject = (JSONObject) userDataArray.get(0);
Object field5Obj = userDataJsonObject.containsKey(FIELD5)
? userDataJsonObject.get(FIELD5) : null;
if (field5Obj != null && field5Obj instanceof String) {
String field5 = (String) field5Obj;
String prepend = "";
prepend = "(" + field5 + ") ";
String shortDescription = (String) jsonObject.get(SHORT_DESCRIPTION);
jsonObject.put(SHORT_DESCRIPTION, prepend + shortDescription);
String name = (String) jsonObject.get(NAME);
jsonObject.put(NAME, prepend + name);
}
}
}
}
// Return back to search server
SearchUEResponse uePostResponse = new SearchUEResponse();
uePostResponse.setContent(arrayContentView);
response = Response.ok(uePostResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/preBySearchTerm")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search expression before getting product details based on a search term.")
public Response preFindProductsBySearchTerm(
@ApiParam(name = "ProductViewPre UE input", value = "The UE Request String", required = true) SearchUERequest uePreRequest) {
final String METHODNAME = "preFindProductsBySearchTerm(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePreRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePreRequest
.getContent();
// Updating the sort criteria to use non-tokenized name column
setControlParameterValue(contentView, "_wcf.search.internal.sort", "name_ntk asc");
// Return back to search server
SearchUEResponse uePreResponse = new SearchUEResponse();
uePreResponse.setContent(contentView);
response = Response.ok(uePreResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/postById")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search response after getting product details based on the product ID.", response = SearchUEResponse.class)
public Response postFindProductsById(
@ApiParam(name = "ProductViewPost UE input", value = "The UE Request String", required = true) SearchUERequest uePostRequest) {
final String METHODNAME = "postFindProductsById(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePostRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePostRequest
.getContent();
// Put your customization logic here ....
// Return back to search server
SearchUEResponse uePostResponse = new SearchUEResponse();
uePostResponse.setContent(contentView);
response = Response.ok(uePostResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/preById")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search expression before getting product details based on the product ID.")
public Response preFindProductsById(
@ApiParam(name = "ProductViewPre UE input", value = "The UE Request String", required = true) SearchUERequest uePreRequest) {
final String METHODNAME = "preFindProductsById(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePreRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePreRequest
.getContent();
// Put your customization logic here ....
// Return back to search server
SearchUEResponse uePreResponse = new SearchUEResponse();
uePreResponse.setContent(contentView);
response = Response.ok(uePreResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/postByIds")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search response after getting product details based on the product IDs.", response = SearchUEResponse.class)
public Response postFindProductsByIds(
@ApiParam(name = "ProductViewPost UE input", value = "The UE Request String", required = true) SearchUERequest uePostRequest) {
final String METHODNAME = "postFindProductsByIds(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePostRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePostRequest
.getContent();
// Put your customization logic here ....
// Return back to search server
SearchUEResponse uePostResponse = new SearchUEResponse();
uePostResponse.setContent(contentView);
response = Response.ok(uePostResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/preByIds")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search expression before getting product details based on the product IDs.")
public Response preFindProductsByIds(
@ApiParam(name = "ProductViewPre UE input", value = "The UE Request String", required = true) SearchUERequest uePreRequest) {
final String METHODNAME = "preFindProductsByIds(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePreRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePreRequest
.getContent();
// Put your customization logic here ....
// Return back to search server
SearchUEResponse uePreResponse = new SearchUEResponse();
uePreResponse.setContent(contentView);
response = Response.ok(uePreResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/postByPartNumber")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search response after getting product details based on the part number.", response = SearchUEResponse.class)
public Response postFindProductsByPartNumber(
@ApiParam(name = "ProductViewPost UE input", value = "The UE Request String", required = true) SearchUERequest uePostRequest) {
final String METHODNAME = "postFindProductsByPartNumber(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePostRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePostRequest
.getContent();
// Put your customization logic here ....
// Return back to search server
SearchUEResponse uePostResponse = new SearchUEResponse();
uePostResponse.setContent(contentView);
response = Response.ok(uePostResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/preByPartNumber")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search expression before getting product details based on the part number.")
public Response preFindProductsByPartNumber(
@ApiParam(name = "ProductViewPre UE input", value = "The UE Request String", required = true) SearchUERequest uePreRequest) {
final String METHODNAME = "preFindProductsByPartNumber(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePreRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePreRequest
.getContent();
// Put your customization logic here ....
// Return back to search server
SearchUEResponse uePreResponse = new SearchUEResponse();
uePreResponse.setContent(contentView);
response = Response.ok(uePreResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/postByPartNumbers")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search response after getting product details based on the part numbers.", response = SearchUEResponse.class)
public Response postFindProductsByPartNumbers(
@ApiParam(name = "ProductViewPost UE input", value = "The UE Request String", required = true) SearchUERequest uePostRequest) {
final String METHODNAME = "postFindProductsByPartNumbers(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePostRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePostRequest
.getContent();
// Put your customization logic here ....
// Return back to search server
SearchUEResponse uePostResponse = new SearchUEResponse();
uePostResponse.setContent(contentView);
response = Response.ok(uePostResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/preByPartNumbers")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search expression before getting product details based on the part numbers.")
public Response preFindProductsByPartNumbers(
@ApiParam(name = "ProductViewPre UE input", value = "The UE Request String", required = true) SearchUERequest uePreRequest) {
final String METHODNAME = "preFindProductsByPartNumbers(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePreRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePreRequest
.getContent();
// Put your customization logic here ....
// Return back to search server
SearchUEResponse uePreResponse = new SearchUEResponse();
uePreResponse.setContent(contentView);
response = Response.ok(uePreResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/postByCategory")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search response after getting product details based on the category.", response = SearchUEResponse.class)
public Response postFindProductsByCategory(
@ApiParam(name = "ProductViewPost UE input", value = "The UE Request String", required = true) SearchUERequest uePostRequest) {
final String METHODNAME = "postFindProductsByCategory(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePostRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePostRequest
.getContent();
// Put your customization logic here ....
// Return back to search server
SearchUEResponse uePostResponse = new SearchUEResponse();
uePostResponse.setContent(contentView);
response = Response.ok(uePostResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
@POST
@Path("/preByCategory")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Customize the search expression before getting product details based on the category.")
public Response preFindProductsByCategory(
@ApiParam(name = "ProductViewPre UE input", value = "The UE Request String", required = true) SearchUERequest uePreRequest) {
final String METHODNAME = "preFindProductsByCategory(SearchUERequest)";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, METHODNAME);
}
logRequest(uePreRequest);
Response response = null;
try {
// Convert request into a map of JSONObject of JSONArray
List<JSONObject> contentView = uePreRequest
.getContent();
// Put your customization logic here ....
// Return back to search server
SearchUEResponse uePreResponse = new SearchUEResponse();
uePreResponse.setContent(contentView);
response = Response.ok(uePreResponse).build();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
logResponse(response);
}
LOGGER.exiting(CLASSNAME, METHODNAME);
return response;
}
}
| [
"vikram.aditya@royalcyber.com"
] | vikram.aditya@royalcyber.com |
5643c9f9dca602bc00ad77e03a250ac548cd2750 | c8b153eff93b948fbe6f65830236284e31784c28 | /web/src/test/java/com/avp/geoservice/web/BaseIntegrationTest.java | 6dddf45895edf8cce39bee10fc60c7878d53d449 | [] | no_license | B1zDelNickus/geo-service | 370018de77ecb66b9462cd5bb87964a8c00299d1 | 093b68cc5d734a4b85fc697c26574208b678eef7 | refs/heads/main | 2023-09-03T01:26:50.734257 | 2021-10-26T15:39:50 | 2021-10-26T15:39:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,048 | java | package com.avp.geoservice.web;
import com.avp.geoservice.config.ServiceConfiguration;
import com.avp.geoservice.config.WebConfiguration;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
@ActiveProfiles("test")
@SpringBootTest(
classes = {
WebConfiguration.class,
ServiceConfiguration.class,
BaseIntegrationTest.MongoConfig.class
},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
@ExtendWith(SpringExtension.class)
@Testcontainers
@AutoConfigureWebClient(registerRestTemplate = true)
public abstract class BaseIntegrationTest {
@Container
protected static final GeoMongoDBContainer mongoDBContainer = GeoMongoDBContainer.getInstance();
@Autowired
protected RestTemplate restTemplate;
protected MockMvc mockMvc;
@LocalServerPort
private int randomServerPort;
@Autowired
private WebApplicationContext context;
@BeforeEach
public void beforeEach() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
protected String getEndpointUrl(String endpoint) {
return String.format("http://localhost:%d%s", randomServerPort, endpoint);
}
@Configuration
@EnableMongoRepositories({"com.avp.geoservice.repository.mongo"})
@ComponentScan({"com.avp.geoservice.repository.mongo"})
@EnableTransactionManagement
public static class MongoConfig extends AbstractMongoClientConfiguration {
@Bean
@Primary
public MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
@Override
protected String getDatabaseName() {
return "testdb";
}
@Bean
@Primary
public MongoClient mongoClient() {
String connectionString = String.format("mongodb://%s:%s", mongoDBContainer.getContainerIp(),
mongoDBContainer.getMongoDBPort());
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(connectionString)).build();
return MongoClients.create(settings);
}
@Bean
@Primary
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), "test");
}
}
}
| [
"andrei.vasilevich@drsmile-group.com"
] | andrei.vasilevich@drsmile-group.com |
1b5bcd29987f95ab53b444dfd48c59b31259affd | 753c9025f958215b5def759ead138013eb3f5ab1 | /src/src/armstrongnumber.java | 381370ec145c185e5e68ce2dd4660b6e5b5cb8b6 | [] | no_license | GodLikeHuman/javava | a05ca3d8af6792cbd7cf289afa178ad6af95a0e2 | 9a273d9a50ebecfa57594d4e6038bc59e07c9a6d | refs/heads/master | 2021-01-02T03:31:10.369443 | 2020-02-11T03:22:26 | 2020-02-11T03:22:26 | 239,471,573 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 660 | java | package src;
import java.util.Scanner;
public class armstrongnumber {
public static void main(String[] args) {
int num, number, temp, total = 0;
System.out.println("Ënter 3 Digit Number");
Scanner scanner = new Scanner(System.in);
num = scanner.nextInt();
scanner.close();
number = num;
for( ;number!=0;number /= 10)
{
temp = number % 10;
total = total + temp*temp*temp;
}
if(total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
| [
"60730907+GodLikeHuman@users.noreply.github.com"
] | 60730907+GodLikeHuman@users.noreply.github.com |
e422ea29730b66163f2bfb2e6694041d076b2204 | 0daaa543cebef5fabddfe897439f943408b849fb | /TOOL/Learning/Learning.java | 412a96f009a4fa5a39cc17fceb8715d7cd223203 | [] | no_license | alawrenc/tool | bf26488b566ca2247780d923507b73320e362648 | 2f21b45263681ba584536aa6c463f383fc54532b | refs/heads/master | 2021-01-17T23:15:49.237764 | 2010-03-25T22:06:23 | 2010-03-25T22:06:23 | 104,763 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 47,966 | java | package TOOL.Learning;
import java.lang.Math;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.image.*;
import java.awt.Cursor;
import java.awt.geom.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GradientPaint;
import java.awt.AlphaComposite;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.Toolkit;
import java.awt.Point;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import TOOL.Data.DataListener;
import TOOL.Data.DataSet;
import TOOL.Data.Frame;
import TOOL.Data.ColorTableListener;
import TOOL.Data.File.FileSource;
//import TOOL.Misc.Pair;
import TOOL.Misc.Estimate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
// Image stuff
import TOOL.Image.ColorTable;
import TOOL.Image.ImageSwatch;
import TOOL.Image.ImagePanel;
import TOOL.Image.TOOLImage;
import TOOL.Image.ThresholdedImage;
import TOOL.Image.ProcessedImage;
import TOOL.Image.PixelSelectionPanel;
import TOOL.Image.ImageMarkerPanel;
import TOOL.Image.CalibrationDrawingPanel;
import TOOL.Image.DrawingPanel;
import TOOL.Image.ImageOverlay;
import TOOL.Image.ImageOverlayAction;
import TOOL.Vision.Vision;
import TOOL.Data.Classification.Keys.Builder;
import TOOL.Data.Classification.KeyFrame.GoalType;
import TOOL.Data.Classification.KeyFrame.CrossType;
import TOOL.Data.Classification.Keys;
import TOOL.Data.Classification.KeyFrame;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import TOOL.GUI.IncrementalSliderParent;
import TOOL.TOOL;
import TOOL.TOOLException;
/**
* This is the learning class. It is responsible for managing and running
* our classification system so we can machine learn vision.
* Right now it checks for a given KEY.KEY file in the current data directory.
* If it finds one it reads it and displays the data along with the current
* frame. If it doesn't then it creates one and uses the vision system to
* guess at what the contents of the file should be. Then a human can
* go through and modify them as necessary or simply approve of the contents.
* Hitting the "human approved" button is a signal to save the new contents.
* However, the file is only written when the "Write" button is hit.
* This file is the main entry point and contains the big overall panel.
* It contains three subpanels - 1) an image viewing panel, 2) a panel for
* editting the contents of a single frame, and 3) a panel for moving
* through the frames.
* @author modified Eric Chown, plus whoever wrote all the code I borrow from
* other parts of the tool
*/
public class Learning implements DataListener, MouseListener,
MouseMotionListener,
PropertyChangeListener
{
protected PixelSelectionPanel selector; // Display panel
protected KeyPanel key; // editing panel
protected LearningPanel learnPanel; // Moving throug frames
protected ImageOverlay overlay; // To overlay object drawing
protected TOOLImage rawImage; // raw image
protected TOOL tool; // parent class
protected ColorTable colorTable; // current color table
protected VisionState visionState; // processes vision
protected JPanel main_panel; // master panel
protected int imageHeight, imageWidth; // size variables
private Frame currentFrame; // normal frame data
private KeyFrame current; // current KEY data
private int ind; // index of current frame
protected Builder keys; // holds whole KEY.KEY file
protected KeyFrame.Builder newKey; // temporary to build new item
private JSplitPane split_pane; // we split panel up
private boolean split_changing;
private boolean quietMode; // Used when running in batch
private Point start, end;
private String keyName; // filename of Key file
private DataSet currentSet; // which data set we're processing
private int goodBall, badBall; // ball stat variables
private int goodCross, badCross; // cross stat variables
private int okCross, falseCross;
private int goodBlue, badBlue, okBlue; // blue goal stats
private int goodYellow, badYellow, okYellow; // yellow goal stats
private int goodRed, badRed; // red robot stats
private int goodBlueRobot, badBlueRobot; // blue robot stats
private int missedBall, missedCross; // false negatives
private int missedBlue; // ditto
private int missedYellow, missedRed; // ditto
private int missedBlueRobot; // ditto
private String curFrame; // current frame of batch job
private int curFrameIndex; // index
/** Constructor. Makes the panels and sets up the listeners.
* @param t the parent TOOL class
*/
public Learning(TOOL t){
tool = t;
colorTable = tool.getColorTable();
//get all the image panels ready
selector = new PixelSelectionPanel();
selector.changeSettings(ImagePanel.SCALE_AUTO_BOTH);
key = new KeyPanel(this);
setupWindowsAndListeners();
ind = 0;
quietMode = false;
}
/** Returns the current color table. An artifact of copying code from other
places. May not be needed in this class.
@return the current color table
*/
public ColorTable getTable() {
return colorTable;
}
/**
* Sets up all the windows and panels; installs listener onto them.
*/
private void setupWindowsAndListeners(){
//data listeners
tool.getDataManager().addDataListener(this);
// create the main panel
main_panel = new JPanel();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
main_panel.setLayout(gridbag);
// create the panel that will hold the images
JPanel images_panel = new JPanel();
images_panel.setLayout(new GridLayout(1, 1));
c.weightx = 1;
c.weighty = 5;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridheight = GridBagConstraints.RELATIVE;
gridbag.setConstraints(images_panel, c);
main_panel.add(images_panel);
// within that panel, we have a split view of the two images
split_pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
split_pane.setLeftComponent(selector);
split_pane.setRightComponent(key);
split_pane.setDividerLocation(.8); // initial divider location
split_pane.setResizeWeight(.8); // how to distribute new space
split_changing = false;
split_pane.addPropertyChangeListener(this);
images_panel.add(split_pane);
// set up mouse listeners
selector.addMouseListener(this);
key.addMouseListener(this);
selector.addMouseMotionListener(this);
key.addMouseMotionListener(this);
learnPanel = new LearningPanel(this);
main_panel.add(learnPanel);
main_panel.setFocusable(true);
main_panel.requestFocusInWindow();
learnPanel.fixButtons();
quietMode = false;
}
/** @return JPanel holding all of Calibrate stuff */
public JPanel getContentPane() {
return main_panel;
}
// Methods dealing with moving through the frames
/** Move backwards one frame.
*/
public void getLastImage() {
tool.getDataManager().last();
// fix the backward skipping button
learnPanel.fixButtons();
}
/** Move backwards one frame.
*/
public void getNextImage() {
tool.getDataManager().next();
// fix the forward skipping button
learnPanel.fixButtons();
}
/** Move forwards to a later frame.
* @param i the frame to move to
*/
public void skipForward(int i) {
tool.getDataManager().skip(i);
// fix the forward skipping button
learnPanel.fixButtons();
}
/** Move backwards to an earlier frame.
* @param i the frame to move to
*/
public void skipBackward(int i) {
tool.getDataManager().revert(i);
// fix the backward skipping button
learnPanel.fixButtons();
}
/** Tell the data manager which image to use.
* This method may not be necessary in this class.
* @param i the index of the image
*/
public void setImage(int i) {
tool.getDataManager().set(i);
}
/** Flips either from batch of off
*/
public void toggleQuietMode() {
quietMode = !quietMode;
}
/** Check if there is another image forward. Used
* to set the button correctly.
* @return true when there is an image
*/
public boolean canGoForward() {
return tool.getDataManager().hasElementAfter();
}
/** Check if there is another image backward. Used
* to set the button correctly.
* @return true when there is an image
*/
public boolean canGoBackward() {
return tool.getDataManager().hasElementBefore();
}
/** @return the parent class
*/
public TOOL getTool() {
return tool;
}
/** @return true if we have a thresholded image, else false. */
public boolean hasImage() {
return false;
}
/** @return true if in quiet mode */
public boolean getQuietMode() {
return quietMode;
}
////////////////////////////////////////////////////////////
// LISTENER METHODS
////////////////////////////////////////////////////////////
// MouseListener methods
public void mouseClicked(MouseEvent e) {}
// When mouse enters, make sure the cursor is the rectangular swatch
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) {
start = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
}
// MouseMotionListener methods
public void mouseDragged(MouseEvent e) {
end = e.getPoint();
mouseMoved(e);
}
// PropertyChangeListener method
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)
&& !split_changing) {
split_changing = true;
split_pane.setDividerLocation(.5);
split_changing = false;
}
else if (e.getPropertyName().equals(ImagePanel.X_SCALE_CHANGE)) {
}
}
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
}
//mouseWheelListener Methods
public void mouseWheelMoved(MouseWheelEvent e){
}
//dataListener Methods
/** A new data set has been selected. The big thing here
* is to check for our key file. If it doesn't exist then
* we need to create a temporary version of one in case we
* decide to edit it. So we either read the data into our
* data structure or we fill our data structure with default
* values for every frame. The file stuff uses Google's
* protocol buffers system.
* @param s the Dataset that was selected
* @param f the current frame within the dataset
*/
public void notifyDataSet(DataSet s, Frame f) {
boolean keyExists = true;
currentSet = s;
keys = Keys.newBuilder();
keyName = s.path()+"KEY.KEY";
// See if the key exists.
try {
FileInputStream input = new FileInputStream(keyName);
keys.mergeFrom(input);
input.close();
} catch (FileNotFoundException e) {
keyExists = false;
System.out.println(keyName + ": not found. Creating a new file.");
} catch (java.io.IOException e) {
System.out.println("Problems with key file");
}
if (!keyExists) {
for (int i = 0; i < s.size(); i++) {
// make a new key for the file and add it
KeyFrame next =
KeyFrame.newBuilder()
.setHumanChecked(false)
.setBall(false)
.setBlueGoal(GoalType.NO_POST)
.setYellowGoal(GoalType.NO_POST)
.setCross(CrossType.NO_CROSS)
.setRedRobots(0)
.setBlueRobots(0)
.build();
keys.addFrame(next);
}
}
notifyFrame(f);
}
//to do: clean up this code - Octavian
/** A new frame has been selected. We need to update all of our
* information - vision, our key, etc.
* @param f the frame
*/
public void notifyFrame(Frame f) {
if (!quietMode) {
currentFrame = f;
if (!f.hasImage())
return;
//if visionState is null, initialize, else just load the frame
if (visionState == null)
visionState = new VisionState(f, tool.getColorTable());
else
visionState.newFrame(f, tool.getColorTable());
rawImage = visionState.getImage();
colorTable = visionState.getColorTable();
// Since we now handle different sized frames, it's possible to
// switch between modes, changing the image's size without updating
// the overlay. This will catch that
if(overlay == null || overlay.getWidth() != rawImage.getWidth()) {
overlay = new ImageOverlay(rawImage.getWidth(),rawImage.getHeight());
}
imageHeight = rawImage.getHeight();
imageWidth = rawImage.getWidth();
overlay.generateNewEdgeImage(rawImage);
selector.updateImage(rawImage);
visionState.update(false, f);
visionState.updateObjects();
// retrieve the frame information
ind = f.index();
current = keys.getFrame(ind);
// setup the buttons on the key panel to reflect the contents of the file
key.setHumanStatus(current.getHumanChecked());
if (current.getHumanChecked()) {
key.setHumanStatus(true);
key.setBallStatus(current.getBall());
key.setBlueGoalStatus(current.getBlueGoal());
key.setYellowGoalStatus(current.getYellowGoal());
key.setCrossStatus(current.getCross());
key.setRedRobotStatus(current.getRedRobots());
key.setBlueRobotStatus(current.getBlueRobots());
newKey =
KeyFrame.newBuilder()
.setHumanChecked(current.getHumanChecked())
.setBall(current.getBall())
.setBlueGoal(current.getBlueGoal())
.setYellowGoal(current.getYellowGoal())
.setCross(current.getCross())
.setRedRobots(current.getRedRobots())
.setBlueRobots(current.getBlueRobots());
} else {
// set up based upon vision data
key.setHumanStatus(false);
key.setBallStatus(getBall());
key.setBlueGoalStatus(getBlueGoal());
key.setYellowGoalStatus(getYellowGoal());
key.setCrossStatus(getCross());
key.setRedRobotStatus(getRedRobots());
key.setBlueRobotStatus(getBlueRobots());
newKey =
KeyFrame.newBuilder()
.setHumanChecked(current.getHumanChecked())
.setBall(getBall())
.setBlueGoal(getBlueGoal())
.setYellowGoal(getYellowGoal())
.setCross(getCross())
.setRedRobots(getRedRobots())
.setBlueRobots(getBlueRobots());
}
// write out the vision data in the GUI
key.setBall(getBallString());
key.setBlueGoal(getBlueGoalString());
key.setYellowGoal(getYellowGoalString());
key.setCross(getCrossString());
key.setRedRobot(getRedRobotString());
key.setBlueRobot(getBlueRobotString());
//learnPanel.setOverlays();
// set up the builder in case we decide to edit
selector.setOverlayImage(visionState.getThreshOverlay());
selector.repaint();
// They loaded something so make sure our buttons reflect the
// active state; e.g. that our undo stack and redo stack are
// empty.
learnPanel.fixButtons();
// 0 based indexing.
learnPanel.setText("Image " + (f.index()) + " of " +
(f.dataSet().size() - 1) +
" - processed in " + visionState.getProcessTime() +
" micro secs");
}
}
/* We often get a series of frames with the same data. In this case the
personn editing is saying that this frame is basically the same as the
last. So get its info and substitute it for the vision data.
*/
public void useLast() {
int ind = currentFrame.index();
current = keys.getFrame(ind - 1);
// setup the buttons on the key panel to reflect the contents of the file
key.setHumanStatus(false);
key.setBallStatus(current.getBall());
key.setBlueGoalStatus(current.getBlueGoal());
key.setYellowGoalStatus(current.getYellowGoal());
key.setCrossStatus(current.getCross());
key.setRedRobotStatus(current.getRedRobots());
key.setBlueRobotStatus(current.getBlueRobots());
newKey =
KeyFrame.newBuilder()
.setHumanChecked(current.getHumanChecked())
.setBall(current.getBall())
.setBlueGoal(current.getBlueGoal())
.setYellowGoal(current.getYellowGoal())
.setCross(current.getCross())
.setRedRobots(current.getRedRobots())
.setBlueRobots(current.getBlueRobots());
}
/** Run a "batch" learning job. We're going to bootstrap this.
Our first goal is simply to run all the frames in the current
directory and collect statistics on the ones that are marked
for human approval.
*/
public void runBatch () {
initStats();
quietMode = true;
int framesProcessed = 0;
long t = System.currentTimeMillis();
curFrame = currentSet.path();
for (Frame d : currentSet) {
try {
currentSet.load(d.index());
} catch (TOOLException e) {
System.out.println("Couldn't load frame");
}
current = keys.getFrame(d.index());
curFrameIndex = d.index();
if (current.getHumanChecked()) {
// we have good data, so let's process the frame
visionState.newFrame(d, tool.getColorTable());
visionState.update(false, d);
visionState.updateObjects();
updateBallStats();
updateGoalStats();
updateCrossStats();
updateRobotStats();
framesProcessed++;
}
}
t = System.currentTimeMillis() - t;
quietMode = false;
printStats(framesProcessed, t);
}
/** Run a recursive batch job. We'll grab the higher level part of the
current path and try running batch on every data set it contains.
Obviously this is not for the faint of heart as it could take a very
long time depending on the amount of data contained.
*/
public void runRecursiveBatch() {
System.out.println("Running batch job");
initStats();
quietMode = true;
int framesProcessed = 0;
long t = System.currentTimeMillis();
String topPath = currentSet.path();
boolean screen = false;
screen = learnPanel.getOnlyBalls() || learnPanel.getOnlyGoals() ||
learnPanel.getOnlyCrosses() || learnPanel.getOnlyBots();
// We need to get rid of the current directory
int end = topPath.length() - 2;
for ( ; end > -1 && !topPath.substring(end, end+1).equals(System.getProperty("file.separator"));
end--) {}
if (end > -1) {
topPath = topPath.substring(0, end+1);
// topPath should now contain the parent directory pathname
// now we need to start retrieving all of the data sets that contain it
FileSource source = (FileSource)(tool.getSourceManager().activeSource());
List<DataSet> dataList = source.getDataSets();
for (DataSet d : dataList) {
if (d.path().startsWith(topPath)) {
// we have a target data set
curFrame = d.path();
String keyName = d.path()+"KEY.KEY";
// See if the key exists.
try {
FileInputStream input = new FileInputStream(keyName);
keys.clear();
keys.mergeFrom(input);
input.close();
for (Frame f : d) {
try {
f.load();
} catch (TOOLException e) {
System.out.println("Couldn't load frame");
}
current = keys.getFrame(f.index());
curFrameIndex = f.index();
if (current.getHumanChecked() &&
(!screen || (learnPanel.getOnlyBalls() && current.getBall()) ||
(learnPanel.getOnlyGoals() && (current.getBlueGoal().getNumber() != 0 ||
current.getYellowGoal().getNumber() != 0)) ||
(learnPanel.getOnlyCrosses() && current.getCross().getNumber() != 0) ||
(learnPanel.getOnlyBots() && (current.getRedRobots() != 0 ||
current.getBlueRobots() != 0)))) {
// we have good data, so let's process the frame
visionState.newFrame(f, tool.getColorTable());
visionState.update(false, f);
visionState.updateObjects();
updateBallStats();
updateGoalStats();
updateCrossStats();
updateRobotStats();
framesProcessed++;
}
try {
f.unload();
} catch (TOOLException e) {
System.out.println("Problem unloading frame");
}
}
} catch (FileNotFoundException e) {
// key file doesn't exist, so skip it
} catch (java.io.IOException e) {
// something went wrong, so keep going
}
}
}
}
t = System.currentTimeMillis() - t;
quietMode = false;
printStats(framesProcessed, t);
}
/** Learn a new color table. Start by gathering
current path and try running batch on every data set it contains.
While doing that collect a bunch of stats on each of the colors
we care about.
Obviously this is not for the faint of heart as it could take a very
long time depending on the amount of data contained.
*/
public void runRecursiveBatchLearning() {
initStats();
System.out.println("Starting color learning");
quietMode = true;
int framesProcessed = 0;
long t = System.currentTimeMillis();
String topPath = currentSet.path();
boolean screen = false;
int balls = 0, yposts = 0, bposts = 0, crosses = 0, brobots = 0, rrobots = 0, greens = 0;
// We need to get rid of the current directory
int end = topPath.length() - 2;
List<DataSet> dataList;
for ( ; end > -1 && !topPath.substring(end, end+1).equals(System.getProperty("file.separator"));
end--) {}
if (end > -1) {
visionState.initStats();
topPath = topPath.substring(0, end+1);
// topPath should now contain the parent directory pathname
// now we need to start retrieving all of the data sets that contain it
FileSource source = (FileSource)(tool.getSourceManager().activeSource());
dataList = source.getDataSets();
for (DataSet d : dataList) {
if (d.path().startsWith(topPath)) {
// we have a target data set
curFrame = d.path();
String keyName = d.path()+"KEY.KEY";
// See if the key exists.
try {
FileInputStream input = new FileInputStream(keyName);
keys.clear();
keys.mergeFrom(input);
input.close();
for (Frame f : d) {
try {
f.load();
} catch (TOOLException e) {
System.out.println("Couldn't load frame");
}
current = keys.getFrame(f.index());
curFrameIndex = f.index();
if (current.getHumanChecked()) {
// we have good data, so let's process the frame
visionState.newFrame(f, tool.getColorTable());
// we need to figure out what objects are in the frame
boolean or, yell, bl, wh, re, na;
or = current.getBall();
if (or) {
balls++;
}
switch (current.getYellowGoal()) {
case NO_POST: yell = false;
break;
default:
yell = true;
yposts++;
}
switch (current.getBlueGoal()) {
case NO_POST: bl = false;
break;
default:
bl = true;
bposts++;
}
switch (current.getCross()) {
case NO_CROSS: wh = false;
break;
default:
wh = true;
crosses++;
}
re = current.getRedRobots() > 0;
na = current.getBlueRobots() > 0;
if (re) rrobots++;
if (na) brobots++;
//if (!re && !na) {
greens += visionState.learnGreenWhite();
//}
visionState.updateStats(or, yell, bl, wh, re, na);
framesProcessed++;
}
try {
f.unload();
} catch (TOOLException e) {
System.out.println("Problem unloading frame");
}
}
} catch (FileNotFoundException e) {
// key file doesn't exist, so skip it
} catch (java.io.IOException e) {
// something went wrong, so keep going
}
}
}
System.out.println("Processed "+framesProcessed+" with "+balls);
visionState.updateGreenWhite(greens);
// now get the general color ranges of green and white
int yMin = 500, yMax = -1, uMin = 500, uMax = -1, vMin = 500, vMax = -1;
// now do the same thing, but process green and white slightly differently
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 128; j++) {
for (int k = 0; k < 128; k++) {
byte color = colorTable.getRawColor(i, j, k);
if (color == Vision.GREEN) {
yMin = Math.min(yMin, i);
yMax = Math.max(yMax, i);
uMin = Math.min(uMin, j);
uMax = Math.max(uMax, j);
vMin = Math.min(vMin, k);
vMax = Math.max(vMax, k);
}
}
}
}
boolean secondPass = true;
System.out.println("Values "+yMin+" "+yMax+" "+uMin+" "+uMax+" "+vMin+" "+vMax);
int updated = 0;
visionState.initStats();
for (DataSet d : dataList) {
if (d.path().startsWith(topPath) && secondPass) {
// we have a target data set
curFrame = d.path();
String keyName = d.path()+"KEY.KEY";
// See if the key exists.
try {
FileInputStream input = new FileInputStream(keyName);
keys.clear();
keys.mergeFrom(input);
input.close();
for (Frame f : d) {
try {
f.load();
} catch (TOOLException e) {
System.out.println("Couldn't load frame");
}
current = keys.getFrame(f.index());
curFrameIndex = f.index();
if (current.getHumanChecked()) {
// we have good data, so let's process the frame
visionState.newFrame(f, tool.getColorTable());
// we need to figure out what objects are in the frame
boolean or, yell, bl, wh, re, na;
or = current.getBall();
switch (current.getYellowGoal()) {
case NO_POST: yell = false;
break;
default:
yell = true;
}
switch (current.getBlueGoal()) {
case NO_POST: bl = false;
break;
default:
bl = true;
}
switch (current.getCross()) {
case NO_CROSS: wh = false;
break;
default:
wh = true;
}
re = current.getRedRobots() > 0;
na = current.getBlueRobots() > 0;
int temp = 0;
//if (!re && !na && !or) {
temp = visionState.moreLearnGreenWhite(yMin, yMax, uMin, uMax,
vMin, vMax);
//}
visionState.updateStats(or, yell, bl, wh, re, na);
if (temp > 0) {
System.out.println("Updated "+temp+" valuesin frame "+curFrame+" "+curFrameIndex);
updated+= temp;
}
}
try {
f.unload();
} catch (TOOLException e) {
System.out.println("Problem unloading frame");
}
}
} catch (FileNotFoundException e) {
// key file doesn't exist, so skip it
} catch (java.io.IOException e) {
// something went wrong, so keep going
}
}
}
visionState.updateGreenWhite(0);
System.out.println("UPdated "+updated);
t = System.currentTimeMillis() - t;
quietMode = false;
visionState.printStats(framesProcessed, balls, yposts, bposts, crosses, rrobots, brobots, false);
// now let's see if we can improve on that
/*for (DataSet d : dataList) {
if (d.path().startsWith(topPath)) {
// we have a target data set
curFrame = d.path();
String keyName = d.path()+"KEY.KEY";
// See if the key exists.
try {
FileInputStream input = new FileInputStream(keyName);
keys.clear();
keys.mergeFrom(input);
input.close();
for (Frame f : d) {
try {
f.load();
} catch (TOOLException e) {
System.out.println("Couldn't load frame");
}
current = keys.getFrame(f.index());
curFrameIndex = f.index();
if (current.getHumanChecked()) {
// we have good data, so let's process the frame
visionState.newFrame(f, tool.getColorTable());
// we need to figure out what objects are in the frame
boolean or, yell, bl, wh, re, na;
or = current.getBall();
switch (current.getYellowGoal()) {
case NO_POST: yell = false;
break;
default:
yell = true;
}
switch (current.getBlueGoal()) {
case NO_POST: bl = false;
break;
default:
bl = true;
}
switch (current.getCross()) {
case NO_CROSS: wh = false;
break;
default:
wh = true;
}
re = current.getRedRobots() > 0;
na = current.getBlueRobots() > 0;
if (re) rrobots++;
if (na) brobots++;
visionState.reviseStats(or, yell, bl, wh, re, na);
}
try {
f.unload();
} catch (TOOLException e) {
System.out.println("Problem unloading frame");
}
}
} catch (FileNotFoundException e) {
// key file doesn't exist, so skip it
} catch (java.io.IOException e) {
// something went wrong, so keep going
}
}*/
System.out.println("Updating color table");
//visionState.printStats(framesProcessed, balls, yposts, bposts, crosses, rrobots, brobots, true);
System.out.println("Revision finished");
}
}
/** Initialize all of our statistics variables
*/
public void initStats() {
goodBall = 0; badBall = 0; goodCross = 0; badCross = 0; falseCross = 0; okCross = 0;
goodBlue = 0; badBlue = 0; goodYellow = 0; badYellow = 0; okBlue=0; okYellow=0;
goodRed = 0; badRed = 0; goodBlueRobot = 0; badBlueRobot = 0;
missedBall = 0; missedCross = 0; missedBlue = 0; missedYellow = 0;
missedRed = 0; missedBlueRobot = 0;
}
/** Print out statistics.
*/
public void printStats(int processed, long t) {
System.out.println("Processed "+processed+" frames in "+(t / 1000)+" seconds.");
System.out.println("Ball Statistics: Good : "+goodBall+" False positives: "+
badBall+" Missed: "+missedBall);
System.out.println("Blue Goal Statistics: Good: "+goodBlue+" Fair: "+
okBlue+" false positives: "+badBlue+" missed: "+missedBlue);
System.out.println("Yellow Goal Statistics: Good: "+goodYellow+" Fair: "+
okYellow+" false positives: "+badYellow+" missed: "+missedYellow);
System.out.println("Cross Statistics: Good: "+goodCross+" OK: "+okCross+
" False positives: "+falseCross+" badID: "+
badCross+" missed: "+missedCross);
}
/** Compare our key file against vision and update stats accordingly
*/
public void updateBallStats() {
if (current.getBall()) {
if (visionState.getBallVision()) {
goodBall++;
}else {
missedBall++;
if (learnPanel.getMissedBalls())
System.out.println("Missed ball in "+curFrame+" frame "+curFrameIndex);
}
} else if (visionState.getBallVision()) {
badBall++;
if (learnPanel.getFalseBalls())
System.out.println("False ball in "+curFrame+" frame "+curFrameIndex);
}
}
/** Compare our key file against vision and update stats accordingly
*/
public void updateGoalStats() {
switch (current.getBlueGoal()) {
case NO_POST:
switch (visionState.getBlueGoalVision()) {
case NO_POST: break;
case LEFT:
case RIGHT:
case UNSURE:
if (learnPanel.getFalseGoals())
System.out.println("False Goal Post in "+curFrame+
" frame "+curFrameIndex);
badBlue++; break;
case BOTH: badBlue += 2;
if (learnPanel.getFalseGoals())
System.out.println("Two False Goal Posts in "+curFrame+
" frame "+curFrameIndex);
}
break;
case LEFT:
switch (visionState.getBlueGoalVision()) {
case NO_POST: missedBlue++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case LEFT: goodBlue++; break;
case RIGHT: badBlue++;
if (learnPanel.getFalseGoals() && learnPanel.getMissedGoals())
System.out.println("Bad Goal Post ID in "+curFrame+
" frame "+curFrameIndex);
break;
case UNSURE: okBlue++; break;
case BOTH: badBlue++;
if (learnPanel.getFalseGoals())
System.out.println("Extra Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
}
break;
case RIGHT:
switch (visionState.getBlueGoalVision()) {
case NO_POST: missedBlue++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case LEFT: badBlue++;
if (learnPanel.getFalseGoals() && learnPanel.getMissedGoals())
System.out.println("Bad Goal Post ID in "+curFrame+
" frame "+curFrameIndex);
break;
case RIGHT: goodBlue++; break;
case UNSURE: okBlue++; break;
case BOTH: badBlue++;
if (learnPanel.getFalseGoals())
System.out.println("Extra Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
}
break;
case BOTH:
switch (visionState.getBlueGoalVision()) {
case NO_POST: missedBlue += 2;
if (learnPanel.getMissedGoals())
System.out.println("Missed two goals in"+curFrame+
" frame "+curFrameIndex);
break;
case LEFT: missedBlue++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case RIGHT: missedBlue++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case UNSURE: missedBlue++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
okBlue++; missedBlue++;
break;
case BOTH: goodBlue+= 2; break;
}
break;
case UNSURE:
switch (visionState.getBlueGoalVision()) {
case NO_POST: missedBlue++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case LEFT: okBlue++; break;
case RIGHT: okBlue++; break;
case UNSURE: goodBlue++; break;
case BOTH: badBlue++; okBlue++;
if (learnPanel.getFalseGoals())
System.out.println("Extra Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
}
break;
}
switch (current.getYellowGoal()) {
case NO_POST:
switch (visionState.getYellowGoalVision()) {
case NO_POST: break;
case LEFT:
case RIGHT:
case UNSURE:
if (learnPanel.getFalseGoals())
System.out.println("False Goal Post in "+curFrame+
" frame "+curFrameIndex);
badYellow++; break;
case BOTH:
if (learnPanel.getFalseGoals())
System.out.println("Two False Goal Posts in "+curFrame+
" frame "+curFrameIndex);
badYellow += 2;
}
break;
case LEFT:
switch (visionState.getYellowGoalVision()) {
case NO_POST: missedYellow++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case LEFT: goodYellow++; break;
case RIGHT: badYellow++;
if (learnPanel.getFalseGoals() && learnPanel.getMissedGoals())
System.out.println("Bad Goal Post ID in "+curFrame+
" frame "+curFrameIndex);
break;
case UNSURE: okYellow++; break;
case BOTH: badYellow++;
if (learnPanel.getFalseGoals())
System.out.println("Extra Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
}
break;
case RIGHT:
switch (visionState.getYellowGoalVision()) {
case NO_POST: missedYellow++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case LEFT: badYellow++;
if (learnPanel.getFalseGoals() && learnPanel.getMissedGoals())
System.out.println("Bad Goal Post ID in "+curFrame+
" frame "+curFrameIndex);
break;
case RIGHT: goodYellow++; break;
case UNSURE: okYellow++; break;
case BOTH: badYellow++;
if (learnPanel.getFalseGoals())
System.out.println("Extra Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
}
break;
case BOTH:
switch (visionState.getYellowGoalVision()) {
case NO_POST: missedYellow += 2;
if (learnPanel.getMissedGoals())
System.out.println("Missed two Goal Posts in "+curFrame+
" frame "+curFrameIndex);
break;
case LEFT: missedYellow++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case RIGHT: missedYellow++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case UNSURE: missedYellow++; okYellow++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case BOTH: goodYellow+= 2; break;
}
break;
case UNSURE:
switch (visionState.getYellowGoalVision()) {
case NO_POST: missedYellow++;
if (learnPanel.getMissedGoals())
System.out.println("Missed a Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
case LEFT: okYellow++; break;
case RIGHT: okYellow++; break;
case UNSURE: goodYellow++; break;
case BOTH: badYellow++; okYellow++;
if (learnPanel.getMissedGoals())
System.out.println("Missed Goal Post in "+curFrame+
" frame "+curFrameIndex);
break;
}
break;
}
}
/** Check our key file against our vision system and collect stats.
*/
public void updateCrossStats() {
switch (current.getCross()) {
case NO_CROSS:
switch (visionState.getCrossVision()) {
case NO_CROSS: break;
case BLUE:
case YELLOW:
case UNKNOWN:
falseCross++;
if (learnPanel.getFalseCrosses())
System.out.println("False Cross in "+curFrame+
" frame "+curFrameIndex);
break;
case DOUBLE_CROSS: falseCross+=2;
if (learnPanel.getFalseCrosses())
System.out.println("Two False Crosses in "+curFrame+
" frame "+curFrameIndex);
break;
}
break;
case BLUE:
switch (visionState.getCrossVision()) {
case NO_CROSS: missedCross++;
if (learnPanel.getMissedCrosses())
System.out.println("Missed Cross in "+curFrame+
" frame "+curFrameIndex);
break;
case BLUE: goodCross++;
break;
case YELLOW: badCross++;
if (learnPanel.getFalseCrosses())
System.out.println("Bad Cross in "+curFrame+
" frame "+curFrameIndex);
break;
case UNKNOWN:
okCross++; break;
case DOUBLE_CROSS: badCross++; goodCross++;
if (learnPanel.getFalseCrosses())
System.out.println("False Cross in "+curFrame+
" frame "+curFrameIndex);
break;
}
break;
case YELLOW:
switch (visionState.getCrossVision()) {
case NO_CROSS: missedCross++;
if (learnPanel.getMissedCrosses())
System.out.println("Missed Cross in "+curFrame+
" frame "+curFrameIndex);
break;
case BLUE: badCross++;
if (learnPanel.getFalseCrosses())
System.out.println("Bad Cross in "+curFrame+
" frame "+curFrameIndex);
break;
case YELLOW: goodCross++; break;
case UNKNOWN:
okCross++; break;
case DOUBLE_CROSS: badCross++; goodCross++;
if (learnPanel.getFalseCrosses())
System.out.println("False Cross in "+curFrame+
" frame "+curFrameIndex);
break;
}
break;
case UNKNOWN:
switch (visionState.getCrossVision()) {
case NO_CROSS: missedCross++;
if (learnPanel.getMissedCrosses())
System.out.println("Missed Cross in "+curFrame+
" frame "+curFrameIndex);
break;
case BLUE:
case YELLOW:
okCross++; break;
case UNKNOWN:
goodCross++; break;
case DOUBLE_CROSS: badCross++; goodCross++;
if (learnPanel.getFalseCrosses())
System.out.println("False Cross in "+curFrame+
" frame "+curFrameIndex);
break;
}
break;
case DOUBLE_CROSS:
switch (visionState.getCrossVision()) {
case NO_CROSS: missedCross+=2;
if (learnPanel.getMissedCrosses())
System.out.println("Two Missed Crosses in "+curFrame+
" frame "+curFrameIndex);
break;
case BLUE:
case YELLOW:
case UNKNOWN:
missedCross++;
goodCross++;
if (learnPanel.getMissedCrosses())
System.out.println("Missed Cross in "+curFrame+
" frame "+curFrameIndex);
break;
case DOUBLE_CROSS: goodCross+=2; break;
}
}
}
/** Someday we'll use this to collect robot stats. But first we need to be
able to recognize them!
*/
public void updateRobotStats() {
}
/** Returns the overlay containing image edges. Can probably be dumped.
* @ return the overlay
*/
public ImageOverlay getEdgeOverlay() {
return overlay;
}
/** Returns the object the runs vision processing for us.
* @return link to vision
*/
public VisionState getVisionState() {
return visionState;
}
/** Used to set the information in the Key file.
* @param hasBall whether or not the frame has a ball
*/
public void setBall(boolean hasBall) {
if (newKey != null) {
newKey.setBall(hasBall);
}
}
/** When the "Write" button is pressed this is executed.
* It writes the contents of our data structure to the KEY.KEY
* file.
*/
public void writeData() {
// Write the new key file back to disk.
try {
FileOutputStream output = new FileOutputStream(keyName);
keys.build().writeTo(output);
output.close();
newKey = null;
} catch (java.io.IOException e) {
System.out.println("Problems with key file");
}
// now as odd as this may seem, reread the data!
// this is because we have already used this builder
keys = Keys.newBuilder();
try {
FileInputStream input = new FileInputStream(keyName);
keys.mergeFrom(input);
input.close();
} catch (FileNotFoundException e) {
System.out.println(keyName + ": not found. Creating a new file.");
} catch (java.io.IOException e) {
System.out.println("Problems with key file");
}
}
/** Used to set the information in the Key file.
* @param hasHuman whether or not the frame was human approved
*/
public void setHuman(boolean hasHuman) {
if (newKey != null) {
newKey.setHumanChecked(true);
keys.setFrame(ind , newKey);
newKey =
KeyFrame.newBuilder()
.setHumanChecked(current.getHumanChecked())
.setBall(current.getBall())
.setBlueGoal(current.getBlueGoal())
.setYellowGoal(current.getYellowGoal())
.setCross(current.getCross())
.setRedRobots(current.getRedRobots())
.setBlueRobots(current.getBlueRobots());
}
key.setHumanStatus(hasHuman);
}
/** Used to set the information in the Key file.
* @param which whether or not the frame has a cross and what type
*/
public void setCross(CrossType which) {
if (newKey != null)
newKey.setCross(which);
}
/** Used to set the information in the Key file.
* @param which whether or not the frame has a yellow goal and what type
*/
public void setYellowGoal(GoalType which) {
if (newKey != null)
newKey.setYellowGoal(which);
}
/** Used to set the information in the Key file.
* @param which whether or not the frame has a blue goal and what type
*/
public void setBlueGoal(GoalType which) {
if (newKey != null)
newKey.setBlueGoal(which);
}
/** Used to set the information in the Key file.
* @param howMany the number of red robots
*/
public void setRedRobot(int howMany) {
if (newKey != null)
newKey.setRedRobots(howMany);
}
/** Used to set the information in the Key file.
* @param howMany the number of blue robots
*/
public void setBlueRobot(int howMany) {
if (newKey != null)
newKey.setBlueRobots(howMany);
}
/** Used to get information from vision.
* @return whether there is a ball or not
*/
public boolean getBall() {
if (visionState == null) return false;
return visionState.getBallVision();
}
/** Used to get information from vision.
* @return status of blue goal
*/
public GoalType getBlueGoal() {
if (visionState == null) return GoalType.NO_POST;
return visionState.getBlueGoalVision();
}
/** Used to get information from vision.
* @return status of yellow goal
*/
public GoalType getYellowGoal() {
if (visionState == null) return GoalType.NO_POST;
return visionState.getYellowGoalVision();
}
/** Used to get information from vision.
* @return status of field cross
*/
public CrossType getCross() {
if (visionState == null) return CrossType.NO_CROSS;
return visionState.getCrossVision();
}
/** Used to get information from vision.
* @return how many red robots
*/
public int getRedRobots() {
if (visionState == null) return 0;
return visionState.getRedRobotsVision();
}
/** Used to get information from vision.
* @return how many blue robots
*/
public int getBlueRobots() {
if (visionState == null) return 0;
return visionState.getBlueRobotsVision();
}
/** Used to get information from vision.
* @return whether human has approved or not
*/
public String getHuman() {
//return visionState.getHumanString();
return "No";
}
/** Based on current state returns an appropriate description for
* display.
* @return ball descriptor
*/
public String getBallString() {
if (visionState == null) return "No Frame Loaded";
return visionState.getBallString();
}
/** Based on current state returns an appropriate description for
* display.
* @return cross descriptor
*/
public String getCrossString() {
if (visionState == null) return "No Frame Loaded";
return visionState.getCrossString();
}
/** Based on current state returns an appropriate description for
* display.
* @return red robot descriptor
*/
public String getRedRobotString() {
if (visionState == null) return "No Frame Loaded";
return visionState.getRedRobotString();
}
/** Based on current state returns an appropriate description for
* display.
* @return blue robot descriptor
*/
public String getBlueRobotString() {
if (visionState == null) return "No Frame Loaded";
return visionState.getBlueRobotString();
}
/** Based on current state returns an appropriate description for
* display.
* @return blue goal descriptor
*/
public String getBlueGoalString() {
if (visionState == null) return "No Frame Loaded";
return visionState.getBlueGoalString();
}
/** Based on current state returns an appropriate description for
* display.
* @return yellow goal descriptor
*/
public String getYellowGoalString() {
if (visionState == null) return "No Frame Loaded";
return visionState.getYellowGoalString();
}
}
| [
"echown@bowdoin.edu"
] | echown@bowdoin.edu |
aa23e68eefdb1ff77a23588c87839842162cf812 | fdb29405779daf4432c8c7dce183c73db8fd6705 | /commercetools-models/src/main/java/io/sphere/sdk/channels/ChannelDraftBuilder.java | 50ed6fd3ca05d790413885771a01677a205d4fb1 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | Saandji/sphere-jvm-sdk | c669d255065aab240248e259a85c482904dfb6e1 | 1baf4dac7a8fa50d164617fdf7d2801ccbd241e1 | refs/heads/master | 2021-01-12T22:09:09.842877 | 2016-03-16T11:16:56 | 2016-03-16T11:16:56 | 53,948,125 | 0 | 0 | null | 2016-03-15T13:47:26 | 2016-03-15T13:47:26 | null | UTF-8 | Java | false | false | 1,586 | java | package io.sphere.sdk.channels;
import io.sphere.sdk.models.Base;
import io.sphere.sdk.models.Builder;
import io.sphere.sdk.models.LocalizedString;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Set;
/**
* Builder for {@link ChannelDraft}.
*/
public final class ChannelDraftBuilder extends Base implements Builder<ChannelDraftDsl> {
private final String key;
private Set<ChannelRole> roles = Collections.emptySet();
@Nullable
private LocalizedString name;
@Nullable
private LocalizedString description;
private ChannelDraftBuilder(final String key) {
this.key = key;
}
public static ChannelDraftBuilder of(final String key) {
return new ChannelDraftBuilder(key);
}
public static ChannelDraftBuilder of(final ChannelDraft template) {
return new ChannelDraftBuilder(template.getKey())
.roles(template.getRoles())
.name(template.getName())
.description(template.getDescription());
}
public ChannelDraftBuilder description(@Nullable final LocalizedString description) {
this.description = description;
return this;
}
public ChannelDraftBuilder name(@Nullable final LocalizedString name) {
this.name = name;
return this;
}
public ChannelDraftBuilder roles(final Set<ChannelRole> roles) {
this.roles = roles;
return this;
}
@Override
public ChannelDraftDsl build() {
return new ChannelDraftDsl(key, roles, name, description);
}
}
| [
"michael.schleichardt@commercetools.de"
] | michael.schleichardt@commercetools.de |
9952479825408323004c8f40375027c8b14bcc0c | 64d9c191c830cfbba2e5243262e5f279f03511a0 | /src/main/java/labs/lab1/checklist/PresizeCollectionObjects.java | da33d6239d1a3c3b5c9eb7d8b8660db97b3b223f | [] | no_license | Morok1/optimization | 536024fb0f7341c4a3c1aa872ca3a70f5e2b2e48 | dda49289110404125925c80d899e3588d431dee5 | refs/heads/master | 2020-06-19T05:37:29.728863 | 2019-08-31T20:29:40 | 2019-08-31T20:29:40 | 196,582,287 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 101 | java | package labs.lab1.checklist;
//Presize collection objects.
public class PresizeCollectionObjects {
}
| [
"zhenyasmagin@yandex.ru"
] | zhenyasmagin@yandex.ru |
688975a4da4a05f8cf6d3da39841d8e0aacd1bb1 | ad186d3fc9d710287ab7804850d72d63e6c12e7c | /src/tp/pr5/gui/RobotPanel.java | 1591225895a8136d668aba2df50d83d3897b838f | [] | no_license | enribahor/walle-scape | ec60ace0455bddbae8197bca68e7d634f686120f | f04ade33855733e50eb3ca9f33dee4add77c4280 | refs/heads/master | 2021-08-23T14:56:55.811253 | 2017-12-05T09:19:29 | 2017-12-05T09:19:29 | 113,159,933 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,107 | java | package tp.pr5.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import tp.pr5.RobotEngineObserver;
import tp.pr5.items.InventoryObserver;
import tp.pr5.items.Item;
import tp.pr5.items.ItemContainer;
/**
*
* @author Antonio Núñez Guerrero
*
* RobotPanel displays information about the robot and its inventory. More specifically, it contains labels to show the
* robot fuel and the weight of recycled material and a table that represents the robot inventory. Each row displays
* information about an item contained in the inventory.
*/
@SuppressWarnings("serial")
public class RobotPanel extends JPanel implements RobotEngineObserver, InventoryObserver{
private final String TITLE_PANEL = "Robot info";
private final String FUEL = "Fuel: ";
private final String RECYCLED = "Recycled: ";
private JLabel JLabelInfo;
private RobotTable robotTable;
private JTable table;
private String itemId;//Atributo para saber que fila de la tabla se ha seleccionado
private ItemContainer itemContainer;
public RobotPanel(){
this.itemContainer = new ItemContainer();
initPanelTable();
}
/**
* Método que inicializa el PanelTable
*/
void initPanelTable(){
//Creacion
this.robotTable = new RobotTable(this.itemContainer);
this.table = new JTable(this.robotTable);
this.JLabelInfo = new JLabel();
//Inicializacion
this.setBorder(new TitledBorder(TITLE_PANEL));
this.JLabelInfo.setHorizontalAlignment(JTextField.CENTER);
//this.table.addMouseListener(new ListenerTable());
//Colocacion estetica
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(150,125));
//Añadir
this.add(this.JLabelInfo, BorderLayout.NORTH);
this.add( new JScrollPane(this.table), BorderLayout.CENTER);
}
/**
* Método que cambia las jLabel de fuel y recycled de robotTable
* @param fuel - entero que representa la cantidad de fuel a la que queremos cambiar el JLabel
* @param recycled - entero que representa la cantidad de recycled a la que queremos cambiar el JLabel
*/
public void changeJLabels(int fuel, int recycled){
this.JLabelInfo.setText(FUEL + fuel + " " + RECYCLED + recycled);
}
/**
*
* @return el robotTable
*/
public RobotTable getRobotTable(){
return robotTable;
}
/**
*
* @return el JLabelInfo
*/
public JLabel getJLabelInfo(){
return JLabelInfo;
}
/**
*
* @return el itemId
*/
public String getItemId() {
return itemId;
}
/**
* Método que sirve para fijar el atributo Item
* @param itemId
*/
public void setItemId(String itemId) {
this.itemId = itemId;
}
/**
*
* @author Antonio
*
* Clase que representa el oyente de la tabla
*/
/*public class ListenerTable implements MouseListener{
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int row = table.rowAtPoint(e.getPoint());
String id = (String) table.getValueAt(row, 0);
itemId = id;
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}*/
/**
* Notifica que el contenedor ha cambiado
* @param inventory - Nuevo inventario
*/
@Override
public void inventoryChange(List<Item> inventory) {
// TODO Auto-generated method stub
itemContainer.setContainer(inventory);
this.robotTable.setContainerItem(itemContainer);
}
/**
* Notifica que el usuario solicita una instrucción scan en el inventario
* @param inventoryDescription - Información sobre el inventario
*/
@Override
public void inventoryScanned(String inventoryDescription) {
// TODO Auto-generated method stub
}
/**
* Notifica que el usuario desea escanear un objeto del inventario
* @param description - Descrición del objeto
*/
@Override
public void itemScanned(String description) {
// TODO Auto-generated method stub
}
/**
* Notifica que un objeto se ha gastado y que hay que eliminarlo del contenedor.
* Después invocará al método inventoryChange
* @param itemName - Nombre del objeto gastado
*/
@Override
public void itemEmpty(String itemName) {
// TODO Auto-generated method stub
}
/**
* El robot engine informa si ha ocurrido algún error
* @param msg - Mensaje de error
*/
@Override
public void raiseError(String msg) {
// TODO Auto-generated method stub
//JOptionPane.showMessageDialog(null, msg, null, JOptionPane.ERROR_MESSAGE);
}
/**
* El robot engine informa que ha habido una petición de la ayuda
* @param help - Un string con la información de ayuda
*/
@Override
public void communicationHelp(String help) {
// TODO Auto-generated method stub
}
/**
* El robot engine informa que el robot se ha apagado porque ha llegado a su nave espacial o porque se ha quedado
* sin fuel
* @param atShip - true si el robot se apaga porque ha llegado a la nave espacial y false si el robot se apaga porque se
* se ha quedado sin fuel
*/
@Override
public void engineOff(boolean atShip) {
// TODO Auto-generated method stub
}
/**
* El robot engine informa que la comunicación ha terminado
*/
@Override
public void communicationCompleted() {
// TODO Auto-generated method stub
}
/**
* El robot engine informa que el fuel y/o la cantidad de material reciclado ha cambiado
* @param fuel - Cantidad actual de fuel
* @param recycledMaterial - Cantidad actual de material reciclado
*/
@Override
public void robotUpdate(int fuel, int recycledMaterial) {
// TODO Auto-generated method stub
this.JLabelInfo.setText(FUEL + fuel + " " + RECYCLED + recycledMaterial);
}
/**
* El robot engine informa que el robot quiere decir algo
* @param message - El mensaje del robot
*/
@Override
public void robotSays(String message) {
// TODO Auto-generated method stub
JOptionPane.showMessageDialog(null, message);
}
/**
* El robot engine informa de que se ha terminado el juego
*/
@Override
public void endGame() {
// TODO Auto-generated method stub
}
/**
* @return un string con el nombre del item seleccionado
*/
public String getSelectedItem(){
int row = this.table.getSelectedRow();
return (String) this.table.getValueAt(row, 0);
}
}
| [
"enguike@hotmail.es"
] | enguike@hotmail.es |
cfb43fdce21390a657c2366f86a9f2956391f6a8 | bbd8770e9689ba94953477fb9e3c468a7ec3aaef | /src/com/zftlive/android/library/third/ormlite/field/types/BaseDataType.java | b892b9ad859110b4fc9314d378ba44790df96e43 | [] | no_license | jiandaima/zftlive | 1ce945ffbffc262604673eada7949e01b7464bd0 | d08dbd65ef6d597d580a92b82f3a5348da188a1d | refs/heads/master | 2021-04-29T08:46:07.717053 | 2016-08-25T12:53:55 | 2016-08-25T12:53:55 | 77,670,412 | 1 | 0 | null | 2016-12-30T07:46:21 | 2016-12-30T07:46:21 | null | UTF-8 | Java | false | false | 4,286 | java | package com.zftlive.android.library.third.ormlite.field.types;
import java.lang.reflect.Field;
import java.sql.SQLException;
import com.zftlive.android.library.third.ormlite.field.BaseFieldConverter;
import com.zftlive.android.library.third.ormlite.field.DataPersister;
import com.zftlive.android.library.third.ormlite.field.FieldType;
import com.zftlive.android.library.third.ormlite.field.SqlType;
import com.zftlive.android.library.third.ormlite.support.DatabaseResults;
/**
* Base data type that defines the default persistance methods for the various data types.
*
* <p>
* Here's a good page about the <a href="http://docs.codehaus.org/display/CASTOR/Type+Mapping" >mapping for a number of
* database types</a>:
* </p>
*
* <p>
* <b>NOTE:</b> If you are creating your own custom database persister, you probably will need to override the
* {@link BaseFieldConverter#sqlArgToJava(FieldType, Object, int)} method as well which converts from a SQL data to
* java.
* </p>
*
* @author graywatson
*/
public abstract class BaseDataType extends BaseFieldConverter implements DataPersister {
/**
* Type of the data as it is persisted in SQL-land. For example, if you are storing a DateTime, you might consider
* this to be a {@link SqlType#LONG} if you are storing it as epoche milliseconds.
*/
private final SqlType sqlType;
private final Class<?>[] classes;
/**
* @param sqlType
* Type of the class as it is persisted in the databases.
* @param classes
* Associated classes for this type. These should be specified if you want this type to be always used
* for these Java classes. If this is a custom persister then this array should be empty.
*/
public BaseDataType(SqlType sqlType, Class<?>[] classes) {
this.sqlType = sqlType;
this.classes = classes;
}
public abstract Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException;
public abstract Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos)
throws SQLException;
public boolean isValidForField(Field field) {
if (classes.length == 0) {
// we can't figure out the types so we just say it is valid
return true;
}
for (Class<?> clazz : classes) {
if (clazz.isAssignableFrom(field.getType())) {
return true;
}
}
// if classes are specified and one of them should match
return false;
}
public Class<?> getPrimaryClass() {
if (classes.length == 0) {
return null;
} else {
return classes[0];
}
}
/**
* @throws SQLException
* If there are problems creating the config object. Needed for subclasses.
*/
public Object makeConfigObject(FieldType fieldType) throws SQLException {
return null;
}
public SqlType getSqlType() {
return sqlType;
}
public Class<?>[] getAssociatedClasses() {
return classes;
}
public String[] getAssociatedClassNames() {
return null;
}
public Object convertIdNumber(Number number) {
// by default the type cannot convert an id number
return null;
}
public boolean isValidGeneratedType() {
return false;
}
public boolean isEscapedDefaultValue() {
// default is to not escape the type if it is a number
return isEscapedValue();
}
public boolean isEscapedValue() {
return true;
}
public boolean isPrimitive() {
return false;
}
public boolean isComparable() {
return true;
}
public boolean isAppropriateId() {
return true;
}
public boolean isArgumentHolderRequired() {
return false;
}
public boolean isSelfGeneratedId() {
return false;
}
public Object generateId() {
throw new IllegalStateException("Should not have tried to generate this type");
}
public int getDefaultWidth() {
return 0;
}
public boolean dataIsEqual(Object fieldObj1, Object fieldObj2) {
if (fieldObj1 == null) {
return (fieldObj2 == null);
} else if (fieldObj2 == null) {
return false;
} else {
return fieldObj1.equals(fieldObj2);
}
}
public boolean isValidForVersion() {
return false;
}
public Object moveToNextValue(Object currentValue) {
return null;
}
public Object resultStringToJava(FieldType fieldType, String stringValue, int columnPos) throws SQLException {
return parseDefaultString(fieldType, stringValue);
}
}
| [
"zengfantian@BJJR-ZJ0216.360buyAD.local"
] | zengfantian@BJJR-ZJ0216.360buyAD.local |
72d9331adc4b22c612d901929b5ad40728edf47e | 51d977bc80a6c02b80b37d9921427bd78ee2e978 | /modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationMessage.java | b64633de2bd22a344c45ee61106e95ef3348741c | [
"Apache-2.0"
] | permissive | joegnelson/swagger-codegen | 5f1911d4befa929ba139cf66967dbcfd02db6218 | 559e6d907dd9d5035cfb67fb9b8092027e767239 | refs/heads/master | 2021-01-24T04:43:16.714825 | 2015-06-11T08:25:52 | 2015-06-11T08:25:52 | 31,788,798 | 2 | 2 | null | 2015-03-06T20:59:09 | 2015-03-06T20:59:09 | null | UTF-8 | Java | false | false | 502 | java | package com.wordnik.swagger.generator.util;
public class ValidationMessage {
private String path, message, severity;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
} | [
"fehguy@gmail.com"
] | fehguy@gmail.com |
3c3a61a75a7036643e59b26aad469889d54b5f7b | 835c5e5a428465a1bb14aa2922dd8bf9d1f83648 | /bitcamp-java/src/main/java/com/eomcs/oop/ex03/Exam0320.java | cc73e9dabe682d32b6009f24e5e0ca7d0f9719c6 | [] | no_license | juneglee/bitcamp-study | cc1de00c3e698db089d0de08488288fb86550260 | 605bddb266510109fb78ba440066af3380b25ef1 | refs/heads/master | 2020-09-23T13:00:46.749867 | 2020-09-18T14:26:39 | 2020-09-18T14:26:39 | 225,505,347 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,910 | java | // 인스턴스 메서드 응용
package com.eomcs.oop.ex03;
import java.util.Scanner;
public class Exam0320 {
static class Score {
String name;
int kor;
int eng;
int math;
int sum;
float average;
// 다음 메서드와 같이 인스턴스 변수를 사용하는 경우 인스턴스 메서드로 정의한다.
public void compute() {
// 내장 변수 this에는 compute()를 호출할 때 넘겨준 인스턴스 주소가 들어 있다.
this.sum = this.kor + this.eng + this.math;
this.average = this.sum / 3f;
}
}
public static void main(String[] args) {
Scanner keyScan = new Scanner(System.in);
System.out.print("성적 데이터를 입력하세요(예: 홍길동 100 100 100)> ");
Score s1 = new Score();
s1.name = keyScan.next();
s1.kor = keyScan.nextInt();
s1.eng = keyScan.nextInt();
s1.math = keyScan.nextInt();
System.out.print("성적 데이터를 입력하세요(예: 홍길동 100 100 100)> ");
Score s2 = new Score();
s2.name = keyScan.next();
s2.kor = keyScan.nextInt();
s2.eng = keyScan.nextInt();
s2.math = keyScan.nextInt();
// 특정 인스턴스에 대해 작업을 수행할 때는 인스턴스 메서드를 호출한다.
s1.compute(); // s1에 들어 있는 인스턴스 주소는 compute()에 전달된다.
s2.compute(); // 이번에는 s2에 들어 있는 주소를 compute()에 전달한다.
System.out.printf("%s, %d, %d, %d, %d, %.1f\n",
s1.name, s1.kor, s1.eng, s1.math, s1.sum, s1.average);
System.out.printf("%s, %d, %d, %d, %d, %.1f\n",
s2.name, s2.kor, s2.eng, s2.math, s2.sum, s2.average);
}
}
| [
"klcpop1@example.com"
] | klcpop1@example.com |
f9e00cb0b5574626ba2d17505ff1dc3cb37f2687 | 0d4a4a5d2d3dd0f3d54ba70a3dc6c145209e6f27 | /src/main/java/com/dowlandaiello/melon/crypto/Hash.java | b09589f64e6ea8bdac4c9ad5494d21f9af740f73 | [
"MIT"
] | permissive | dowlandaiello/melon | 83a8d21c482483b74dc94acb92c00875e6358549 | eeb867912c5059e3ca1d422098713337b3f80a1d | refs/heads/master | 2021-07-12T04:58:26.625769 | 2019-09-24T20:54:47 | 2019-09-24T20:54:47 | 205,951,968 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,499 | java | package com.dowlandaiello.melon.crypto;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jcajce.provider.digest.SHA3;
/**
* Represents a generic hash.
*
* @author Dowland Aiello
* @since 1.0
*/
public class Hash {
/**
* The contents of the hash.
*/
public final byte[] contents;
/**
* Initializes a new Hash.
*
* @param b the desired contents of the hash
*/
public Hash(byte[] b) {
this.contents = b; // Set contents
}
/**
* Hash a given input via sha3.
*
* @param b the input to hash
* @return the hashed input
*/
public static Hash sha3(byte[] b) {
SHA3.DigestSHA3 digest = new SHA3.Digest256(); // Initialize sha3 digest
return new Hash(digest.digest(b)); // Return hash
}
/**
* Convert a given string to a hash.
*
* @param s the string to decode
*/
public static Hash fromString(String s) {
try {
return new Hash((byte[]) Hex.decodeHex(s.toCharArray())); // Return the decoded hash
} catch (DecoderException e) {
return new Hash(null); // Return an empty hash
}
}
/**
* Converts a hash to a hex-encoded string.
*
* @return the hex-encoded string representation of the hash
*/
public String toString() {
return Hex.encodeHexString(this.contents); // Return hex-encoded string
}
} | [
"mitsukomegumii@gmail.com"
] | mitsukomegumii@gmail.com |
fd4d9bb9843dbaa826b93aaa3670d31c4b8f67a7 | 08aed40afb8ff046084c2385e3564d36a6b390e0 | /desafio-03/mrcrch/java/PalindromeNumbers.java | 36fe554ed0861a6b55080a569906ccb69448e16a | [] | no_license | OsProgramadores/op-desafios | f59036a90f852ed70bd6197e6e5ea21d1f4a9716 | c055c7ac8090dc8c54180fba39dcf975171c5cd1 | refs/heads/master | 2023-09-04T01:03:21.691805 | 2023-08-24T21:09:45 | 2023-08-24T21:09:45 | 96,814,966 | 130 | 418 | null | 2023-09-14T00:41:34 | 2017-07-10T19:44:10 | C | UTF-8 | Java | false | false | 4,246 | java | import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
public class PalindromeNumbers {
private static final int countDigits(long number) {
return str(number).length();
}
private static final String str(long number) {
return String.valueOf(number);
}
private static final String reverse(long number) {
return new StringBuilder(str(number)).reverse()
.toString();
}
private static final Collection<Long> generate(final long digits) {
// Todo número de 0 a 9 é palíndromo
if (digits == 1) {
return LongStream.rangeClosed(0, 9)
.boxed()
.collect(Collectors.toList());
}
// Identifica os máximos e mínimos de acordo com a quantidade de dígitos
// Exempĺo: O intervalo para um palíndromo de 4 dígitos será [10,100)
long max = (long) Math.pow(10, digits / 2);
long min = max / 10;
if (digits % 2 == 0) {
// Caso a quantidade de dígitos seja par, basta percorrer o intervalo concatenando o valor com o seu inverso
// Exemplo: 21 irá virar 2112
return LongStream.range(min, max)
.map(l -> Long.valueOf(str(l) + reverse(l)))
.boxed()
.collect(Collectors.toList());
}
// Caso a quantidade de dígitos seja ímpar, há um passo adicional com uma iteração de 1 a 9
// Exemplo: 21 irá virar 21012, 21112, 21312, ..., 21912
Collection<Long> result = new ArrayList<>();
for (long l = min; l < max; l++) {
for (int i = 0; i < 10; i++) {
long p = Long.valueOf(str(l) + i + reverse(l));
result.add(p);
}
}
return result;
}
private static final Collection<Long> generate(final long min, final long max) {
int digitsMin = countDigits(min);
int digitsMax = countDigits(max);
Collection<Long> result = new ArrayList<>();
for (int i = digitsMin; i <= digitsMax; i++) {
// Gera todos os palíndromos com a quantidade de dígitos
Collection<Long> temp = generate(i);
// Remove valores menores que o mínimo
if (i == digitsMin) {
temp = temp.stream()
.filter(number -> number >= min)
.collect(Collectors.toList());
}
// Remove valores maiores que o máximo
if (i == digitsMax) {
temp = temp.stream()
.filter(number -> number <= max)
.collect(Collectors.toList());
}
result.addAll(temp);
}
return result;
}
public static void main(final String[] args) {
long min = 0;
long max = 1000;
if (args.length > 0) {
if (args.length != 2) {
throw new IllegalArgumentException(
"Quantidade de parâmetros inválida. São esperados 2 parâmetro (min/max)");
}
final String paramMin = args[0];
final String paramMax = args[1];
try {
min = Long.valueOf(paramMin);
} catch (final NumberFormatException e) {
throw new IllegalArgumentException("Parâmetro mínimo não é um número válido: " + paramMin);
}
try {
max = Long.valueOf(paramMax);
} catch (final NumberFormatException e) {
throw new IllegalArgumentException("Parâmetro máximo não é um número válido: " + paramMax);
}
}
if (min < 0) {
throw new IllegalArgumentException("Valor mínimo não pode ser negativo: " + min);
}
if (max < 0) {
throw new IllegalArgumentException("Valor máximo não pode ser negativo: " + max);
}
if (max <= min) {
throw new IllegalArgumentException("Valor máximo deve ser maior que o valor mínimo: " + min + "/" + max);
}
System.out.println(generate(min, max));
}
}
| [
"paganini@paganini.net"
] | paganini@paganini.net |
05faa85dc0e69f93e4053862e6c05de43fd6e017 | a66458f0d1ca232f22935d238d6acd1ad7565a16 | /www/autochef/src/main/java/autochef/core/recipes/PopularRecipes.java | 012623bb729bd0559fe60767c3fc4bff33507d31 | [] | no_license | jayaddison/autochef | 096b47e37a26f6cd6330874daa4c17734d03c21c | 371096edf497d4cf4d8b69ce4db2b3bed8b6920a | refs/heads/main | 2023-05-08T15:41:04.307600 | 2010-04-24T17:18:30 | 2022-04-01T18:26:22 | 207,615,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 360 | java | package autochef.core.recipes;
import autochef.core.ingredients.*;
import autochef.core.database.*;
import java.sql.*;
import java.util.*;
public class PopularRecipes
{
public static Collection<IngredientLink> getRecipes(String languageID)
{
Collection<IngredientLink> links = new LinkedList<IngredientLink>();
return links;
}
}
| [
"jay@jp-hosting.net"
] | jay@jp-hosting.net |
99910c8ce21cc9a11b8935c199e91784c6e7ccc7 | c1eb2bd1ff25cf563e529c69ef1f0665e669e79a | /src/customFont/customFont.java | cf0e5a90e65ef2cb9654e4bbbba42ce83d9c9057 | [] | no_license | ejiro1111/STOUPETCARE | 29e033222db04bb54e6f9d691a6e67f2b725e67d | 96e7f3ee4a8854ae77cc133174192ab3e740c3e8 | refs/heads/main | 2023-06-04T05:00:09.929197 | 2021-06-20T16:26:58 | 2021-06-20T16:26:58 | 378,684,360 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 219 | java | package customFont;
import java.awt.Font;
public class customFont {
public static Font normalFont = new Font("Tahoma",Font.PLAIN,14);
public static Font titleFont = new Font("Tahoma",Font.BOLD,18);
} | [
"noreply@github.com"
] | noreply@github.com |
6b366e8488b4fc117bc4d0dfea14af1ae2ee2b9a | 4ffb06240abb3b28c041ea2baa6f9d24fa653a24 | /master/news-server/src/main/java/com/masterchengzi/newsserver/dao/impl/NewsCommentDaoImpl.java | 2e2f3e5e42ab49536a080f4e4c3ee55022e4e66a | [] | no_license | mmchengzi/master | bee0dda4c31286a61cc931f4f7c12add5897e9b7 | 5500ee15a39f193d924dc8ec5836f6b3db779651 | refs/heads/master | 2023-05-01T02:34:34.298888 | 2020-01-03T10:07:49 | 2020-01-03T10:07:49 | 154,302,615 | 0 | 0 | null | 2023-04-14T17:39:56 | 2018-10-23T09:43:38 | Java | UTF-8 | Java | false | false | 1,062 | java | package com.masterchengzi.newsserver.dao.impl;
import com.masterchengzi.newsserver.dao.NewsCommentDao;
import com.masterchengzi.newsserver.entity.NewsComment;
import com.masterchengzi.newsserver.mapper.NewsCommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class NewsCommentDaoImpl implements NewsCommentDao {
@Autowired
private NewsCommentMapper newsCommentMapper;
@Override
public List<NewsComment> getNewsComment(String newsId) {
Map map = new HashMap();
map.put("newsId", newsId);
return newsCommentMapper.getNewsComment(map);
}
@Override
public int delete(String newsId) {
Map map = new HashMap();
map.put("newsId", newsId);
return newsCommentMapper.delete(map);
}
@Override
public int insert(NewsComment record) {
return newsCommentMapper.insert(record);
}
@Override
public int update(NewsComment record) {
return newsCommentMapper.update(record);
}
}
| [
"1173727598@qq.com"
] | 1173727598@qq.com |
32c283e3ff40f53a29c5da50975c6dcaf6213ccf | 3bfea37d184819279a64979a89dec90adc97273d | /src/main/java/net/hyper_pigeon/eldritch_mobs/mixin/PersistentProjectileEntityMixin.java | ff94a63b9f86e6ea5ab96423495eb1590f13a694 | [
"CC0-1.0"
] | permissive | haykam821/Eldritch-Mobs | 7c8262ce1d1c004a07433ed3e93e216f0c14ffd4 | 23f983a6b7082d4d52b43e5b8b4a432d206b77cb | refs/heads/master | 2022-11-14T17:55:36.382026 | 2020-07-08T18:45:54 | 2020-07-08T18:45:54 | 278,496,644 | 0 | 0 | null | 2020-07-10T00:01:41 | 2020-07-10T00:01:41 | null | UTF-8 | Java | false | false | 1,251 | java | package net.hyper_pigeon.eldritch_mobs.mixin;
import net.hyper_pigeon.eldritch_mobs.EldritchMobsMod;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.projectile.PersistentProjectileEntity;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PersistentProjectileEntity.class)
public abstract class PersistentProjectileEntityMixin extends Entity {
@Shadow
private double damage;
public PersistentProjectileEntityMixin(EntityType<?> type, World world) {
super(type, world);
}
@Inject(method = "<init>(Lnet/minecraft/entity/EntityType;Lnet/minecraft/entity/LivingEntity;Lnet/minecraft/world/World;)V", at = @At("RETURN"))
private void onInit(EntityType type, LivingEntity owner, World world, CallbackInfo callbackInfo) {
if(EldritchMobsMod.ELDRITCH_MODIFIERS.get(owner).hasMod("sniper")){
damage = damage*2;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
7ec1f3fd59a5c4231e3de35a33198363b58f73e1 | 1cc6988da857595099e52dd9dd2e6c752d69f903 | /ZimbraSelenium/src/java/com/zimbra/qa/selenium/projects/octopus/ui/DisplayFilePreview.java | ac73544e6765da01fee5ec3e5bddff8ee31384cd | [] | no_license | mmariani/zimbra-5682-slapos | e250d6a8d5ad4ddd9670ac381211ba4b5075de61 | d23f0f8ab394d3b3e8a294e10f56eaef730d2616 | refs/heads/master | 2021-01-19T06:58:19.601688 | 2013-03-26T16:30:38 | 2013-03-26T16:30:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,063 | java | /*
* ***** BEGIN LICENSE BLOCK *****
*
* Zimbra Collaboration Suite Server
* Copyright (C) 2011, 2012 VMware, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
*
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.qa.selenium.projects.octopus.ui;
import com.zimbra.qa.selenium.framework.ui.AbsApplication;
import com.zimbra.qa.selenium.framework.ui.AbsDisplay;
import com.zimbra.qa.selenium.framework.ui.AbsPage;
import com.zimbra.qa.selenium.framework.ui.Button;
import com.zimbra.qa.selenium.framework.util.HarnessException;
public class DisplayFilePreview extends AbsDisplay {
public static class Locators {
public static final Locators zFilePreview = new Locators(
"css=div[id=my-files-preview]");
public static final Locators zFileWatchIcon = new Locators(
"css=div[id=my-files-preview-toolbar] span[class=file-info-view-watch-icon]");
public static final Locators zFileImageIcon = new Locators(
"css=div[id=my-files-preview-toolbar] span[class=file-info-view-file-icon]>span[class^=Img]");
public static final Locators zHistory = new Locators(
"css=div[id=my-files-preview] div[id=my-files-preview-toolbar] button[id=show-activitystream-button]");
public static final Locators zComments = new Locators(
"css=div[id=my-files-preview] div[id=my-files-preview-toolbar] button[id=my-files-preview-show-comments-button]");
public static final Locators zPreviewFileName=new Locators(
"css=div[id=my-files-preview-toolbar] span[class=file-info-view-file-name]");
public static final Locators zPreviewFileVersion = new Locators(
"css=div[id=my-files-preview-toolbar] span[class=file-info-view-file-version]");
public static final Locators zPreviewFileSize = new Locators(
"css=div[id=my-files-preview-toolbar] span[class=file-info-view-file-size]");
public final String locator;
private Locators(String locator) {
this.locator = locator;
}
}
/**
* The various displayed fields in preview panel
*/
public static enum Field {
Name, Version, Size, Body
}
public DisplayFilePreview(AbsApplication application) {
super(application);
logger.info("new " + DisplayFilePreview.class.getCanonicalName());
}
@Override
public String myPageName() {
return (this.getClass().getName());
}
@Override
public AbsPage zPressButton(Button button) throws HarnessException {
logger.info(myPageName() + " zPressButton(" + button + ")");
tracer.trace("Click button " + button);
if (button == null)
throw new HarnessException("Button cannot be null!");
// Default behavior variables
String buttonLocator = null;
AbsPage page = null; // If set, this page will be returned
// Based on the button specified, take the appropriate action(s)
if (button == Button.B_WATCH) {
buttonLocator = Locators.zFileWatchIcon.locator
+ " span[class^=unwatched-icon]";
} else if (button == Button.B_UNWATCH) {
buttonLocator = Locators.zFileWatchIcon.locator
+ " span[class^=watched-icon]";
} else if (button == Button.B_HISTORY) {
buttonLocator = Locators.zHistory.locator;
page = new DialogFileHistory(MyApplication,
((AppOctopusClient) MyApplication).zPageOctopus);
} else if (button == Button.B_COMMENTS) {
buttonLocator = Locators.zComments.locator;
page = new DisplayFileComments(MyApplication);
} else {
throw new HarnessException("no logic defined for button " + button);
}
if (!this.sIsElementPresent(buttonLocator))
throw new HarnessException("Button is not present: "
+ buttonLocator);
// Default behavior, process the locator by clicking on it
// Click it
sClickAt(buttonLocator,"0,0");
// If the app is busy, wait for it to become active
zWaitForBusyOverlay();
if (page != null)
page.zWaitForActive();
return page;
}
/**
* Get the string value of the specified field
*
* @return the displayed string value
* @throws HarnessException
*/
public String zGetFileProperty(Field field) throws HarnessException {
logger.info("DocumentPreview.zGetDocumentProperty(" + field + ")");
String fileName =null;
String version=null;
String size = null;
if (field == Field.Name) {
if (this.sIsElementPresent(DisplayFilePreview.Locators.zPreviewFileName.locator)){
fileName =this.sGetText(DisplayFilePreview.Locators.zPreviewFileName.locator);
}
return fileName;
} else if (field == Field.Body) {
/*
* To get the body contents, need to switch iframes
*/
try {
this.sSelectFrame("//iframe");
String bodyLocator = "css=body";
// Make sure the body is present
if (!this.sIsElementPresent(bodyLocator))
throw new HarnessException("Unable to preview body!");
// Get the body value
// String body = this.sGetText(bodyLocator).trim();
String html = this.zGetHtml(bodyLocator);
logger.info("DocumentPreview GetBody(" + bodyLocator + ") = "
+ html);
return (html);
} finally {
// Make sure to go back to the original iframe
this.sSelectFrame("relative=top");
}
} else if (field == Field.Version) {
if (this.sIsElementPresent(DisplayFilePreview.Locators.zPreviewFileVersion.locator)){
version =this.sGetText(DisplayFilePreview.Locators.zPreviewFileVersion.locator);
}
return version;
} else if (field == Field.Size) {
if (this.sIsElementPresent(DisplayFilePreview.Locators.zPreviewFileSize.locator)){
size =this.sGetText(DisplayFilePreview.Locators.zPreviewFileSize.locator);
}
return size;
} else {
throw new HarnessException(" no such field " + field);
}
}
@Override
public boolean zIsActive() throws HarnessException {
if (zWaitForElementPresent(Locators.zFilePreview.locator, "3000"))
return true;
else
return false;
}
}
| [
"marco.mariani@nexedi.com"
] | marco.mariani@nexedi.com |
41cf09f35000a913911f829a58f7b43136d043ee | 223ecebd0e439cc8e9fa47c1afa19d28775e2304 | /src/com/google/gwt/sample/stockwatcher/client/StockPrice.java | e5c2d90081bc8661975038f0c8816b620328acdf | [] | no_license | monL/Lab2_Repo | e03b3a0fc86f1549a9ab175d79d497ac9de40058 | 56374d42baa0ead3e9d7ef758e47b0e310e5d09f | refs/heads/master | 2020-05-19T21:45:47.286761 | 2014-09-21T08:42:14 | 2014-09-21T08:42:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 906 | java | package com.google.gwt.sample.stockwatcher.client;
public class StockPrice {
private String symbol;
private double price;
private double change;
public StockPrice() {
}
public StockPrice(String symbol, double price, double change) {
this.symbol = symbol;
this.price = price;
this.change = change;
}
public String getSymbol() {
return this.symbol;
}
public double getPrice() {
return this.price;
}
public double getChange() {
return this.change;
}
public double getChangePercent() {
return 100.0 * this.change / this.price;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public void setPrice(double price) {
this.price = price;
}
public void setChange(double change) {
this.change = change;
}
public void doMoreStuff(){
//conflict conflicts maybe
}
}
| [
"monzhee@gmail.com"
] | monzhee@gmail.com |
2967eb9259c8370938b1d2a59723f6fbc2aa19c0 | 45c4da9c0578d728ffb0a7408fd88fc052e952f9 | /EvsBatch27_android/app/src/main/java/com/example/aqibjaved/evsbatch27_android/com/signup/validators/SignUpValidator.java | 1cf28b9ceae84a21892130d998d09e135fce499e | [] | no_license | aqib1/Java-Android-2k16 | 571d00831d6c5c00bb7089392719cf33349f6044 | da8cd01d001ffc97a1ddacec2d66c7f77babe215 | refs/heads/master | 2020-08-22T01:08:31.022204 | 2019-10-20T00:47:24 | 2019-10-20T00:47:24 | 216,287,509 | 6 | 0 | null | null | null | null | UTF-8 | Java | false | false | 863 | java | package com.example.aqibjaved.evsbatch27_android.com.signup.validators;
import com.example.aqibjaved.evsbatch27_android.com.contants.app.Constants;
import com.example.aqibjaved.evsbatch27_android.com.model.signup.User;
/**
* Created by AQIB JAVED on 3/4/2018.
*/
public class SignUpValidator {
public boolean isValidUserName(User user){
return Character.isLetter(user.getName().charAt(Constants.indexForUserNameValidationCriteria));
}
public boolean isValidPassword(User user){
return user.getPassword().length() >= Constants.passwordMaxLength && user.getPassword().equals(user.getConfirmPassword());
}
public boolean isValidNumber(User user){
return user.getContactNumber().length() == Constants.validNumberMinLength;
}
public boolean allFiledEntered(User user){
return !user.isEmpty();
}
}
| [
"aqibbutt3078@gmail.com"
] | aqibbutt3078@gmail.com |
60fa5f98193db4981de274fff1c98e62149fce5a | 89e1811c3293545c83966995cb000c88fc95fa79 | /MCHH-api/src/main/java/com/threefiveninetong/mchh/appMember/vo/resp/MemberMoodRecordByDayInfoRespVo.java | 39ed15ec28ba09424ef2e6e9121f09e96602345f | [] | no_license | wxddong/MCHH-parent | 9cafcff20d2f36b5d528fd8dd608fa9547327486 | 2898fdf4e778afc01b850d003899f25005b8e415 | refs/heads/master | 2021-01-01T17:25:29.109072 | 2017-07-23T02:28:59 | 2017-07-23T02:28:59 | 96,751,862 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 535 | java | package com.threefiveninetong.mchh.appMember.vo.resp;
import java.util.List;
import com.threefiveninetong.mchh.core.vo.BaseVo;
/**
* 会员查询一天的心情语录信息响应参数
* @author zhanght
*/
public class MemberMoodRecordByDayInfoRespVo extends BaseVo {
//心情语录列表
private List<MoodRecordVo> moodRecordList;
public List<MoodRecordVo> getMoodRecordList() {
return moodRecordList;
}
public void setMoodRecordList(List<MoodRecordVo> moodRecordList) {
this.moodRecordList = moodRecordList;
}
}
| [
"wxd_1024@163.com"
] | wxd_1024@163.com |
fe6e33fc888bf6308ab8666772b0b5a108b7234f | 0aae3166a9d7c1ee7ab7ec2c4de790a9b9ff9413 | /src/classes/RechercherProjet.java | e45e2af77b4cbf3a98c30d62b1e66b533652b1e3 | [] | no_license | xavix01/PulpeFicton2 | 5d669ba1658be332943431e52e5b27d0c5f24ab3 | d03d80d7ff5e7d32e6116cab1fc89dc5a87e1528 | refs/heads/master | 2021-01-22T21:32:49.648022 | 2013-09-11T16:53:20 | 2013-09-11T16:53:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,443 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package classes;
import DAO.DAOEtudiant;
import DAO.DAOFactory;
import DAO.DAOProjet;
import DAO.DAOParticipe;
import beans.Client;
import beans.Projet;
import java.util.Vector;
/**
*
* @author xavix
*/
public class RechercherProjet {
DAOFactory dAOFactory;
Projet projet;
public RechercherProjet() {
dAOFactory = new DAOFactory();
projet = new Projet();
}
/**
* Enregistre les informations passé en paramètre dans un bean projet. puis
* envoi les informations à la DAOParticipe
*
* @param idProjetSelectionne
* @return boolean
*/
public boolean aUneEquipe(String idProjetSelectionne) {
DAOParticipe dAOParticipe = dAOFactory.getDAOParticipe();
projet.setId_projet(Integer.parseInt(idProjetSelectionne));
if (dAOParticipe.equipeProjet(projet).isEmpty()) {
return false;
}
return true;
}
/**
* Enregistre les informations passé en paramètre dans un bean projet, puis
* les envois à la DAOProjet le nombre de jour de ce projet est calculé.
*
* @param idProjet
* @return int
*/
public int nbreJourTravailleProjet(String idProjet) {
DAOProjet dAOProjet = dAOFactory.getDAOProjet();
projet.setId_projet(Integer.parseInt(idProjet));
dAOProjet.infoProjet(projet);
return projet.getDuree_projet() * 5;
}
/**
* Enregistre les informations passé en paramètre dans un bean Client, puis
* l'envoi à la DAOProjet
*
* @param idClient
* @return Vector<Vector>
*/
public Vector projetClient(String idClient) {
DAOProjet dAOProjet = dAOFactory.getDAOProjet();
Client client = new Client();
client.setId_client(Integer.parseInt(idClient));
Vector vector = new Vector();
vector = dAOProjet.getProjetClientConsultation(client);
return vector;
}
/**
* Enregistre les informations passé en paramètre dans un bean Projet, puis
* l'envoi à la DAOEtudiant
*
* @param idprojet
* @return Vector<Vector>
*/
public Vector etudiantDuProjet(int idprojet) {
DAOEtudiant daoEtudiant = dAOFactory.getDAOEtudiant();
projet.setId_projet(idprojet);
return daoEtudiant.getEtudiantProjet(projet);
}
}
| [
"xavix@xavix"
] | xavix@xavix |
4902bfdef892e2327382ec231f7acc7da9a9c2b2 | a484a3994e079fc2f340470a658e1797cd44e8de | /app/src/main/java/shangri/example/com/shangri/model/bean/response/ChoiceAnchorsBean.java | 78e0daf27dc7265ca928dcb648352afadb2d6d3d | [] | no_license | nmbwq/newLiveHome | 2c4bef9b2bc0b83038dd91c7bf7a6a6a2c987437 | fde0011f14e17ade627426935cd514fcead5096c | refs/heads/master | 2020-07-12T20:33:23.502494 | 2019-08-28T09:55:52 | 2019-08-28T09:55:52 | 204,899,192 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,230 | java | package shangri.example.com.shangri.model.bean.response;
import java.io.Serializable;
import java.util.List;
/**
* Created by Administrator on 2018/1/5.
*/
public class ChoiceAnchorsBean implements Serializable {
/**
* current_page : 1
* total_page : 1
* anchors : [{"register_guild_id":"1","anchor_name":"Coco💐阿标"},{"register_guild_id":"2","anchor_name":"🛡盾上加鹿🦌"},{"register_guild_id":"3","anchor_name":"四爷"},{"register_guild_id":"4","anchor_name":"大大-"},{"register_guild_id":"5","anchor_name":"习惯了一个人"}]
*/
private String current_page;
private int total_page;
private List<AnchorsBean> anchors;
public String getCurrent_page() {
return current_page;
}
public void setCurrent_page(String current_page) {
this.current_page = current_page;
}
public int getTotal_page() {
return total_page;
}
public void setTotal_page(int total_page) {
this.total_page = total_page;
}
public List<AnchorsBean> getAnchors() {
return anchors;
}
public void setAnchors(List<AnchorsBean> anchors) {
this.anchors = anchors;
}
public static class AnchorsBean {
/**
* register_guild_id : 1
* anchor_name : Coco💐阿标
*/
private String register_guild_id;
private String anchor_name;
private String uid;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getRegister_guild_id() {
return register_guild_id;
}
public void setRegister_guild_id(String register_guild_id) {
this.register_guild_id = register_guild_id;
}
public String getAnchor_name() {
return anchor_name;
}
public void setAnchor_name(String anchor_name) {
this.anchor_name = anchor_name;
}
}
}
| [
"1763312610@qq.com"
] | 1763312610@qq.com |
a418d564b4128029dc46d2b10703e73a65265451 | 4b1886601b8c464850c252cc5ab099d70fa0a4ce | /src/common/flan/server/AAGunType.java | b3341641ad71ae7a651b9ce6badc420a87e1c43a | [] | no_license | 0xC6607Eo1/FlansMod | 832cf8e08c4c1133858bb1e39d923b921b895e7a | ec9e4e87a2cd8de26331e0e1502bc79d29de7661 | refs/heads/master | 2021-01-10T21:30:29.112337 | 2012-09-03T15:05:47 | 2012-09-03T15:05:47 | 5,647,555 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,822 | java | package flan.server;
import java.io.BufferedReader;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import cpw.mods.fml.client.FMLClientHandler;
import net.minecraft.src.ItemStack;
public class AAGunType extends InfoType
{
public List<BulletType> ammo = new ArrayList<BulletType>();
public int reloadTime;
public int recoil = 5;
public int accuracy;
public int damage;
public int shootDelay;
public int numBarrels;
public boolean fireAlternately;
public int health;
public int gunnerX;
public int gunnerY;
public int gunnerZ;
public String shootSound;
public String reloadSound;
public Object model;
public String texture;
public float topViewLimit = 75F;
public float bottomViewLimit = 0F;
public static List<AAGunType> infoTypes = new ArrayList<AAGunType>();
public AAGunType(BufferedReader file, String pack)
{
super(pack);
do
{
String line = null;
try
{
line = file.readLine();
} catch (Exception e)
{
break;
}
if (line == null)
{
break;
}
if (line.startsWith("//"))
continue;
String[] split = line.split(" ");
if (split.length < 2)
continue;
read(split, file);
} while (true);
infoTypes.add(this);
}
protected void read(String[] arg0, BufferedReader file)
{
super.read(arg0, file);
try
{
if (arg0[0].equals("Model"))
{
model = FlansMod.proxy.loadAAGunModel(arg0, shortName);
}
if (arg0[0].equals("Texture"))
{
texture = arg0[1];
}
if (arg0[0].equals("Damage"))
{
damage = Integer.parseInt(arg0[1]);
}
if (arg0[0].equals("ReloadTime"))
{
reloadTime = Integer.parseInt(arg0[1]);
}
if (arg0[0].equals("Recoil"))
{
recoil = Integer.parseInt(arg0[1]);
}
if (arg0[0].equals("Accuracy"))
{
accuracy = Integer.parseInt(arg0[1]);
}
if (arg0[0].equals("ShootDelay"))
{
shootDelay = Integer.parseInt(arg0[1]);
}
if (arg0[0].equals("ShootSound"))
{
shootSound = "aaguns." + arg0[1];
FMLClientHandler.instance().getClient().installResource("newSound/aaguns/" + arg0[1] + ".ogg", new File(FMLClientHandler.instance().getClient().mcDataDir, "/Flan/" + contentPack + "/sounds/" + arg0[1] + ".ogg"));
}
if (arg0[0].equals("ReloadSound"))
{
reloadSound = "aaguns." + arg0[1];
FMLClientHandler.instance().getClient().installResource("newSound/aaguns/" + arg0[1] + ".ogg", new File(FMLClientHandler.instance().getClient().mcDataDir, "/Flan/" + contentPack + "/sounds/" + arg0[1] + ".ogg"));
}
if (arg0[0].equals("FireAlternately"))
{
fireAlternately = arg0[1].equals("True");
}
if (arg0[0].equals("NumBarrels"))
{
numBarrels = Integer.parseInt(arg0[1]);
}
if (arg0[0].equals("Health"))
{
health = Integer.parseInt(arg0[1]);
}
if (arg0[0].equals("TopViewLimit"))
{
topViewLimit = Float.parseFloat(arg0[1]);
}
if (arg0[0].equals("BottomViewLimit"))
{
bottomViewLimit = Float.parseFloat(arg0[1]);
}
if (arg0[0].equals("Ammo"))
{
BulletType type = BulletType.getBullet(arg0[1]);
if (type != null)
{
ammo.add(type);
}
}
if (arg0[0].equals("GunnerPos"))
{
gunnerX = Integer.parseInt(arg0[1]);
gunnerY = Integer.parseInt(arg0[2]);
gunnerZ = Integer.parseInt(arg0[3]);
}
} catch (Exception e)
{
FlansMod.log("" + e);
}
}
public boolean isAmmo(BulletType type)
{
return ammo.contains(type);
}
public boolean isAmmo(ItemStack stack)
{
if (stack == null)
return false;
if (stack.getItem() instanceof ItemBullet)
{
return isAmmo(((ItemBullet) stack.getItem()).type);
}
return false;
}
public static AAGunType getAAGun(String s)
{
for (AAGunType gun : infoTypes)
{
if (gun.shortName.equals(s))
return gun;
}
return null;
}
}
| [
"gtaman12@gmail.com"
] | gtaman12@gmail.com |
151fb53a94f50268c22ced718764f246c8efeb8d | a58ba8493fe715e07e00decb94db64de1bab4986 | /rainhadasucata/src/main/java/br/onevision/rainhadasucata/controller/ServletLogin.java | ff3aa4f4524624e87662a3247a0bc7d29e088cda | [
"MIT"
] | permissive | senac-semestre3/projetoIntegrador3 | 4d471f33b38e6208fcbfc57a4fe20ff0d8ef8149 | 9d2a9c0cc714c60df2b50f38c33a29e3dd40b80d | refs/heads/master | 2021-01-19T09:00:10.817727 | 2017-06-12T19:52:15 | 2017-06-12T19:52:15 | 87,141,701 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,172 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.onevision.rainhadasucata.controller;
import br.onevision.rainhadasucata.dao.DaoUsuario;
import br.onevision.rainhadasucata.model.Usuario;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Willian Vieira
*/
@WebServlet(name = "ServletLogin", urlPatterns = {"/login"})
public class ServletLogin extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String nome = request.getParameter("nome");
String senha = request.getParameter("senha");
try {
DaoUsuario daoUsuario = new DaoUsuario();
Usuario usuario = new Usuario();
usuario = daoUsuario.obterNomeSenha(nome, senha);
nome = usuario.getNome();
if (usuario.getNome() != null && usuario.getSenha() != null) {
HttpSession sessao = request.getSession();
sessao.setAttribute("sessionusuario", usuario);
//trocar para request getdispacher
response.sendRedirect("comum.jsp");
}
} catch (Exception e) {
HttpSession sessao = request.getSession();
sessao.setAttribute("session-usuario-n-encontrado", "1");
response.sendRedirect("login.jsp");
}
}
}
| [
"everton_roliveira@outlook.com"
] | everton_roliveira@outlook.com |
54fed7a7df0fb5dfb2ef6df2c5e2505fbd1176ed | fdb515c91ec3239f4721dcf3355e7f8d07a23ae4 | /CMP 338 HW 4/src/QueueInterface.java | 20ad27168c459018a1038b9fba9ebddfd0c3f6d8 | [] | no_license | lbcmp/Data-Structures-Fall-2020 | f8d7684972b5dc364e3b8de9a40f6fe2a2477bdd | 0fc763daa6dfcc338d6961210b97fb4d617c3e65 | refs/heads/main | 2023-04-06T14:21:31.593286 | 2021-04-16T16:24:25 | 2021-04-16T16:24:25 | 358,654,156 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,045 | java | import java.util.NoSuchElementException;
/**
*
* Generic interface for a FIFO queue.
*
* @author Sameh Fakhouri
*
* @param <E> The type of Object that the queue will accept.
*
*/
public interface QueueInterface<E> extends Iterable<E> {
/**
* This method is called to determine if the queue is empty.
*
* @return Returns <b>true</b> if the queue is empty, otherwise it returns <b>false</b>.
*/
public boolean isEmpty();
/**
* This method is called to obtain the count of elements in the list.
*
* @return Returns the numbers of elements that are currently in the queue.
*/
public int size();
/**
*
* Adds the specified element into the stack if it is possible to do so immediately without
* violating capacity restrictions, otherwise, throwing an IllegalStateException
* if no space is currently available or NullPointerException if the specified element is null.
*
* @param e The element to add.
*
* @throws IllegalStateException If the element cannot be added at this time due to capacity restrictions.
* @throws NullPointerException If the specified element being added is null.
*
*/
public void enqueue(E e) throws IllegalStateException, NullPointerException;
/**
*
* Retrieves, but does not remove, the head of this queue.
*
* @return The element at the head of the queue or null if the queue is empty.
*
*/
public E peek();
/**
*
* Retrieves and removes the element at the head of this queue.
*
* @return The element at the head of the queue or null if the queue is empty.
*
*/
public E dequeue();
/**
*
* Retrieves and removes the element at the specified index.
*
* @param index The index of the element to be removed.
*
* @return The element at the specified index.
*
* @throws NoSuchElementException If the specified index is invalid.
*
*/
public E dequeue(int index) throws NoSuchElementException;
/**
*
* Removes all elements from the queue.
*
*/
public void removeAll();
}
| [
"noreply@github.com"
] | noreply@github.com |
5f33a75533bcb98d704241e10be3e065dea86fe7 | 3aa4eb3a19a4b1154d9c7d2445feedd100943958 | /nvwa-validate/src/test/java/com/skymobi/market/commons/validate/ValidateTestSuite.java | 531c13fc07faf940514747f04952dc120d1a9d28 | [] | no_license | big-mouth-cn/nvwa | de367065600d6e751cb432df660f377b57052654 | 6a460cf62c65ed70478a6e9ef3b5a142e8775d19 | refs/heads/master | 2020-04-12T02:25:02.566820 | 2018-01-15T04:34:33 | 2018-01-15T04:34:33 | 57,180,498 | 20 | 26 | null | null | null | null | UTF-8 | Java | false | false | 1,195 | java | package com.skymobi.market.commons.validate;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.skymobi.market.commons.validate.factory.AnnotationValidatorFactoryTest;
import com.skymobi.market.commons.validate.internal.BeanValidatorTest;
import com.skymobi.market.commons.validate.internal.CollectionValidatorTest;
import com.skymobi.market.commons.validate.internal.LengthValidatorTest;
import com.skymobi.market.commons.validate.internal.NotGreatThanValidatorTest;
import com.skymobi.market.commons.validate.internal.NotLaterThanValidatorTest;
import com.skymobi.market.commons.validate.internal.NotNullValidatorTest;
import com.skymobi.market.commons.validate.internal.NumericValidatorTest;
import com.skymobi.market.commons.validate.internal.PatternValidatorTest;
@RunWith(Suite.class)
@SuiteClasses( { BeanValidatorTest.class, CollectionValidatorTest.class, LengthValidatorTest.class,
NotGreatThanValidatorTest.class, NotLaterThanValidatorTest.class,
NotNullValidatorTest.class, NumericValidatorTest.class, PatternValidatorTest.class,
AnnotationValidatorFactoryTest.class })
public class ValidateTestSuite {
}
| [
"huxiao.mail@qq.com"
] | huxiao.mail@qq.com |
e59d1b97a2fe2f599d4661264fe64e3247107565 | 91cdca929eef9a648105f1d1af8d15afaef4c251 | /src/pdf/Format1.java | 3f4d9ac698bc82d6c45e288348ad32205600e79d | [] | no_license | rahulvrma10/resume_builder | ecaa89be7043b7f01b1ff9457b20f0ffb2c779cd | a12b2d173a8b0ecdd7f6dc5116542a1d20612b2f | refs/heads/master | 2020-04-09T07:15:04.751605 | 2018-12-03T07:12:25 | 2018-12-03T07:12:25 | 160,147,484 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,138 | java |
package pdf;
import resume_builder.Resume_Builder;
import connection.Connect;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class Format1 {
public static String temp;
public static FileOutputStream fo;
public static PdfWriter writer;
String query;
public void createPdf() throws DocumentException,IOException
{
temp = System.getProperty("java.io.tmpdir")+"0011223344.pdf";
// step 1
Document document = new Document();
// step 2
fo= new FileOutputStream(temp);
writer=PdfWriter.getInstance(document,fo );
document.setPageSize(PageSize.LETTER);
document.setMargins(36, 36, 36, 36);
document.setMarginMirroring(false);
// step 3
document.open();
// step 4
Rectangle rect= new Rectangle(28, 20, 580, 770); //Page Border
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(2);
rect.setBorderColor(BaseColor.BLACK);
document.add(rect);
try
{
Connect.getConnection();
String place;
query = "select name,email,contact,address,state,objective from person where id='"+Resume_Builder.id+"'";
ResultSet rs = Connect.st.executeQuery(query);
if(rs.first())
{
place = rs.getString("state");
Font tableHead= new Font (Font.FontFamily.UNDEFINED, 12, Font.BOLD, BaseColor.BLACK);
//Name heading
Font font = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD, BaseColor.BLACK);
Paragraph title= new Paragraph(rs.getString("name"),font);
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
//contact, address, email, city
Font content= new Font (Font.FontFamily.UNDEFINED, 12, Font.NORMAL, BaseColor.BLACK);
Paragraph info= new Paragraph(rs.getString("contact"),content);
info.setSpacingAfter(0.5f);
info.setAlignment(Element.ALIGN_CENTER);
document.add(info);
info= new Paragraph(rs.getString("email"),content);
info.setSpacingAfter(0.5f);
info.setAlignment(Element.ALIGN_CENTER);
document.add(info);
info= new Paragraph(rs.getString("address"),content);
info.setSpacingAfter(0.5f);
info.setAlignment(Element.ALIGN_CENTER);
document.add(info);
info= new Paragraph(rs.getString("state"),content);
info.setSpacingAfter(2.0f);
info.setAlignment(Element.ALIGN_CENTER);
document.add(info);
//
Font heading= new Font (Font.FontFamily.TIMES_ROMAN, 16, Font.BOLDITALIC, BaseColor.BLACK);
PdfPTable table = new PdfPTable(1); //to left align info and right align addr
table.setWidthPercentage(100);
table.setSpacingAfter(2.0f);
table.setSpacingBefore(30.0f);
PdfPCell cell = new PdfPCell(new Paragraph("CAREER OBJECTIVE",heading));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.disableBorderSide(Rectangle.BOX);
cell.setBackgroundColor (new BaseColor (221,243,249));
//cell.setExtraParagraphSpace(1.5f);
table.addCell(cell);
document.add(table);
info = new Paragraph(rs.getString("objective"),content);
info.setAlignment(Element.ALIGN_LEFT);
document.add(info);
table = new PdfPTable(1); //to left align info and right align addr
table.setWidthPercentage(100);
table.setSpacingAfter(2.0f);
table.setSpacingBefore(30.0f);
cell = new PdfPCell(new Paragraph("ACADEMICS",heading));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.disableBorderSide(Rectangle.BOX);
cell.setBackgroundColor (new BaseColor (221,243,249));
table.addCell(cell);
document.add(table);
query = "select * from education where id = '"+Resume_Builder.id+"'";
rs = Connect.st.executeQuery(query);
Chunk c;
List unorderedList = new List(List.UNORDERED);
while(rs.next())
{
c= new Chunk(rs.getString("degree")+" from "+rs.getString("institute")+" ("+rs.getString("university")+") with an aggregate of "+rs.getString("marks")+" (Year "+rs.getString("year")+")",content);
unorderedList.add(new ListItem(c));
}
document.add(unorderedList);
//skills
query = "select * from skills where id = '"+Resume_Builder.id+"'";
rs = Connect.st.executeQuery(query);
if(rs.first())
{
table = new PdfPTable(1); //to left align info and right align addr
table.setWidthPercentage(100);
table.setSpacingAfter(2.0f);
table.setSpacingBefore(30.0f);
cell = new PdfPCell(new Paragraph("TECHNICAL & NON-TECHNICAL SKILLS",heading));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.disableBorderSide(Rectangle.BOX);
cell.setBackgroundColor (new BaseColor (221,243,249));
table.addCell(cell);
document.add(table);
unorderedList = new List(List.UNORDERED);
//
boolean b=rs.first();
while(b)
{
c= new Chunk(rs.getString("skill"),content);;
unorderedList.add(new ListItem(c));
b=rs.next();
}
document.add(unorderedList);
}
//experience
query = "select * from experience where id = '"+Resume_Builder.id+"'";
rs = Connect.st.executeQuery(query);
if(rs.first())
{
table = new PdfPTable(1); //to left align info and right align addr
table.setWidthPercentage(100);
table.setSpacingAfter(2.0f);
table.setSpacingBefore(30.0f);
cell = new PdfPCell(new Paragraph("RECENT EMPLOYERS",heading));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.disableBorderSide(Rectangle.BOX);
cell.setBackgroundColor (new BaseColor (221,243,249));
table.addCell(cell);
document.add(table);
table=new PdfPTable(4);
table.setWidthPercentage(90);
table.setSpacingBefore(30.0f); // Space Before table starts, like margin-top in
table.setSpacingAfter(30.0f);
cell = new PdfPCell(new Paragraph("Employer Name",tableHead));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Job Description",tableHead));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("From",tableHead));;
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("To",tableHead));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
boolean b=rs.first();
while(b)
{
table.addCell(rs.getString("employer"));
table.addCell(rs.getString("job"));
table.addCell(rs.getString("f_date"));
table.addCell(rs.getString("t_date"));
b = rs.next();
}
document.add(table);
}
//projects
query = "select * from project where id = '"+Resume_Builder.id+"'";
rs = Connect.st.executeQuery(query);
if(rs.first())
{
table = new PdfPTable(1); //to left align info and right align addr
table.setWidthPercentage(100);
table.setSpacingAfter(2.0f);
table.setSpacingBefore(30.0f);
cell = new PdfPCell(new Paragraph("PROJECTS",heading));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.disableBorderSide(Rectangle.BOX);
cell.setBackgroundColor (new BaseColor (221,243,249));
table.addCell(cell);
document.add(table);
boolean b=rs.first();
while(b)
{
unorderedList = new List(List.UNORDERED);
c= new Chunk(rs.getString("name"),tableHead);;
unorderedList.add(new ListItem(c));
document.add(unorderedList);
info = new Paragraph(" "+rs.getString("details"),content);
//info.setKeepTogether(true);
document.add(info);
b = rs.next();
}
}
//Strengths
query = "select * from strengths where id = '"+Resume_Builder.id+"'";
rs = Connect.st.executeQuery(query);
if(rs.first())
{
table = new PdfPTable(1); //to left align info and right align addr
table.setWidthPercentage(100);
table.setSpacingAfter(2.0f);
table.setSpacingBefore(30.0f);
cell = new PdfPCell(new Paragraph("STRENGTHS",heading));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.disableBorderSide(Rectangle.BOX);
cell.setBackgroundColor (new BaseColor (221,243,249));
table.addCell(cell);
document.add(table);
unorderedList = new List(List.UNORDERED);
//
boolean b=rs.first();
while(b)
{
c= new Chunk(rs.getString("strength"),content);
unorderedList.add(new ListItem(c));
b=rs.next();
}
document.add(unorderedList);
}
//References
query = "select * from reference where id = '"+Resume_Builder.id+"'";
rs = Connect.st.executeQuery(query);
if(rs.first())
{
table = new PdfPTable(1); //to left align info and right align addr
table.setWidthPercentage(100);
table.setSpacingAfter(2.0f);
table.setSpacingBefore(30.0f);
cell = new PdfPCell(new Paragraph("REFERENCES",heading));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.disableBorderSide(Rectangle.BOX);
cell.setBackgroundColor (new BaseColor (221,243,249));
table.addCell(cell);
document.add(table);
unorderedList = new List(List.UNORDERED);
//
boolean b=rs.first();
while(b)
{
c= new Chunk(rs.getString("reference"),content);
unorderedList.add(new ListItem(c));
b=rs.next();
}
document.add(unorderedList);
}
table = new PdfPTable(1); //to left align info and right align addr
table.setWidthPercentage(100);
table.setSpacingAfter(2.0f);
table.setSpacingBefore(30.0f);
cell = new PdfPCell(new Paragraph("DECLARATION",heading));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.disableBorderSide(Rectangle.BOX);
cell.setBackgroundColor (new BaseColor (221,243,249));
table.addCell(cell);
document.add(table);
SimpleDateFormat st = new SimpleDateFormat("dd-MM-yyyy"); //sets Format of date - make sure MM is in capital
info =new Paragraph("I hereby declare that the above-mentioned information is correct up to my knowledge and I bear the responsibility for the correctness of the above-mentioned particulars."
+ "\nDate : "+st.format(new Date())+""
+ "\nPlace : "+place,content);
document.add(info);
//document.add(rect);
}
}
catch(Exception e)
{
System.out.println("problem in createPdcontent");
}
document.add(rect);
document.close();
}
public static void main(String args[])
{
Format1 for1 = new Format1();
try
{
for1.createPdf();
System.out.println("Pdf created successfully");
}
catch(DocumentException e1)
{
System.out.println(e1 + "doc exception");
}
catch(IOException e1)
{
System.out.println(e1 + " io exeption");
}
}
}
| [
"rahul@ordertrainings.com"
] | rahul@ordertrainings.com |
e36a4c0dec98ec749b4bb87d42b41c677b1d6506 | a463de3511d6609605240acad0dac0f18693c564 | /SpringWeb/src/main/java/com/zrs/dao/UserDao.java | b13b52d556fbb1e436f9ded3d029cf6225cdaba9 | [] | no_license | zhangRoxy/Spring2 | eb969a780e0e54c5ee38c64d9c9e54d78c2f47d7 | acd196eccc509e3913821d68098b5e449fb711d2 | refs/heads/main | 2023-03-13T05:30:29.653130 | 2021-03-05T16:33:36 | 2021-03-05T16:33:36 | 344,538,406 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 142 | java | package com.zrs.dao;
import com.zrs.bean.User;
import java.util.List;
public interface UserDao {
List<User> getUsers();
}
| [
"noreply@github.com"
] | noreply@github.com |
ee49ceab9ea4bb65e3a5e1c2b6463a61e896c141 | 563b5d5386969e6380e27d99566eb22da5b3d536 | /src/com/ecust/action/admin/CourseDetailInfoAction.java | 972fc52ddd76debd102a41c63f2dbd678a67f0a5 | [] | no_license | dynastywind/iTouchable | afe920a2fe3417045d1dfc05aa901bbdd04fd02d | 639786a0904e24175f4f5e9b6a2aee867a8e1b6d | refs/heads/master | 2016-09-05T19:15:52.421925 | 2014-05-17T02:43:27 | 2014-05-17T02:43:27 | 10,099,880 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 766 | java | package com.ecust.action.admin;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.ecust.action.common.BaseAction;
@SuppressWarnings("serial")
@ParentPackage("struts-default")
@Namespace("/admin")
@Results({@Result(name="success",location="/admin/courseDetail_info.jsp"),@Result(name="error",type="redirect",location="/index.jsp")})
public class CourseDetailInfoAction extends BaseAction{
@Action("courseDetailInfo")
public String execute() throws Exception {
return SUCCESS;
}
}
| [
"ligabriel12@gmail.com"
] | ligabriel12@gmail.com |
268644282e6dda6877b1207477af45adae23094b | 8d295a7c76fe43c296bf6dc3465c359dc3bdba3c | /it.univaq.mancoosi.packagemm/src/it/univaq/mancoosi/packagemm/impl/PostinstIconsImpl.java | 69714943b9581f4bff4e741f47cf05d648dd8b3a | [] | no_license | davidediruscio/evoss | 8cb1a58d9262378918284eccceda0e0b938f4ba2 | 02285ad1c4bad3b7450cce6bda51481089a3a498 | refs/heads/master | 2020-12-24T13:43:50.753825 | 2016-09-28T09:58:09 | 2016-09-28T09:58:09 | 32,138,890 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 3,623 | java | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package it.univaq.mancoosi.packagemm.impl;
import it.univaq.mancoosi.packagemm.File;
import it.univaq.mancoosi.packagemm.PackagemmPackage;
import it.univaq.mancoosi.packagemm.PostinstIcons;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Postinst Icons</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link it.univaq.mancoosi.packagemm.impl.PostinstIconsImpl#getDirectories <em>Directories</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class PostinstIconsImpl extends UpdateEnvironmentStatementImpl implements PostinstIcons {
/**
* The cached value of the '{@link #getDirectories() <em>Directories</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDirectories()
* @generated
* @ordered
*/
protected EList<File> directories;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PostinstIconsImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return PackagemmPackage.eINSTANCE.getPostinstIcons();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<File> getDirectories() {
if (directories == null) {
directories = new EObjectContainmentEList<File>(File.class, this, PackagemmPackage.POSTINST_ICONS__DIRECTORIES);
}
return directories;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case PackagemmPackage.POSTINST_ICONS__DIRECTORIES:
return ((InternalEList<?>)getDirectories()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case PackagemmPackage.POSTINST_ICONS__DIRECTORIES:
return getDirectories();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case PackagemmPackage.POSTINST_ICONS__DIRECTORIES:
getDirectories().clear();
getDirectories().addAll((Collection<? extends File>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case PackagemmPackage.POSTINST_ICONS__DIRECTORIES:
getDirectories().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case PackagemmPackage.POSTINST_ICONS__DIRECTORIES:
return directories != null && !directories.isEmpty();
}
return super.eIsSet(featureID);
}
} //PostinstIconsImpl
| [
"massimo.delrosso@c8f2f23f-27b7-32fa-be4b-d2bc113dbd9a"
] | massimo.delrosso@c8f2f23f-27b7-32fa-be4b-d2bc113dbd9a |
65272488162bcb1d63baa3b4623eb299582dd266 | 0e7a8943d743a26ff5ede167b97045e9a5dbf646 | /RelativelyPrimePowers.java | 12c73bce851e867a4c6b23ab6da3b5b7ee84f972 | [] | no_license | mooncrater31/Competitive-Programming | dd7657eda25b269ec3873cc78920fb87edbccc41 | 7cf2c8fc00e24d1575f8b1ebb1136a01d393979a | refs/heads/master | 2020-03-31T04:32:20.498065 | 2020-01-19T09:58:38 | 2020-01-19T09:58:38 | 151,909,755 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 214 | java | import java.io.InputStreamReader ;
import java.io.BufferedReader ;
import java.util.* ;
public class RelativelyPrimePowers
{
public static void main(String args[]) throws Exception
{
}
}
| [
"mooncraterrocks@gmail.com"
] | mooncraterrocks@gmail.com |
b9bb6fdec1560460a84982c1dfa04d7745333105 | 9b3836305bb03417296bfbac6c728b4c25a542b7 | /src/main/java/io/automation/data/util/Randomizer.java | f090cdbd395f16553a0568f1423e8571c319b9f5 | [] | no_license | arsaww/sql-generator | be3a54b7264a838ff7c502e308e871752cf3b9e6 | 87f6ad41ca1a84d8779dacb149bf9b89a8ca8fae | refs/heads/master | 2021-01-22T08:17:53.006617 | 2017-05-27T16:26:47 | 2017-05-27T16:26:47 | 92,608,874 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 350 | java | package io.automation.data.util;
import java.util.concurrent.ThreadLocalRandom;
/**
* Created by Bonso on 5/20/2017.
*/
public class Randomizer {
public static int random(int min, int max){
return ThreadLocalRandom.current().nextInt(min, max + 1);
}
public static int random(int max){
return random(0,max);
}
}
| [
"maiKai0e!"
] | maiKai0e! |
64b5abadb52dbd873f86070018d7c40cf828c7a7 | 2d2e434453637a2250552317b5f266ca8b4ab7c8 | /src/edu/uthscsa/ric/volume/formats/jpeg/JPEGLosslessDecoder.java | 70a6669fc6ee25490acad1fbd00679e0bbf064ce | [
"MIT"
] | permissive | ming-hai/JPEGLosslessDecoder | 9f9af162af50d5956460b37bc20b5eedad1d6a90 | 46bd20eabbb53da4ef262d5edef1b1e7eddccd69 | refs/heads/master | 2021-01-21T09:17:27.422734 | 2015-12-15T15:35:53 | 2015-12-15T15:35:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,756 | java | /*
* Copyright (C) 2015 Michael Martinez
* Changes: Added support for selection values 2-7, fixed minor bugs &
* warnings, split into multiple class files, and general clean up.
*
* 08-25-2015: Helmut Dersch agreed to a license change from LGPL to MIT.
*/
/*
* Copyright (C) Helmut Dersch
*
* 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 edu.uthscsa.ric.volume.formats.jpeg;
import java.io.IOException;
import java.nio.ByteBuffer;
public class JPEGLosslessDecoder implements DataStream {
private final ByteBuffer buffer;
private final FrameHeader frame;
private final HuffmanTable huffTable;
private final QuantizationTable quantTable;
private final ScanHeader scan;
private final int HuffTab[][][] = new int[4][2][MAX_HUFFMAN_SUBTREE * 256];
private final int IDCT_Source[] = new int[64];
private final int nBlock[] = new int[10]; // number of blocks in the i-th Comp in a scan
private final int[] acTab[] = new int[10][]; // ac HuffTab for the i-th Comp in a scan
private final int[] dcTab[] = new int[10][]; // dc HuffTab for the i-th Comp in a scan
private final int[] qTab[] = new int[10][]; // quantization table for the i-th Comp in a scan
private boolean restarting;
private int dataBufferIndex;
private int marker;
private int markerIndex;
private int numComp;
private int restartInterval;
private int selection;
private int xDim, yDim;
private int xLoc;
private int yLoc;
private int mask;
private int[] outputData;
private int[] outputRedData;
private int[] outputGreenData;
private int[] outputBlueData;
private static final int IDCT_P[] = { 0, 5, 40, 16, 45, 2, 7, 42, 21, 56, 8, 61, 18, 47, 1, 4, 41, 23, 58, 13, 32, 24, 37, 10, 63, 17, 44, 3, 6, 43, 20,
57, 15, 34, 29, 48, 53, 26, 39, 9, 60, 19, 46, 22, 59, 12, 33, 31, 50, 55, 25, 36, 11, 62, 14, 35, 28, 49, 52, 27, 38, 30, 51, 54 };
private static final int TABLE[] = { 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63 };
public static final int RESTART_MARKER_BEGIN = 0xFFD0;
public static final int RESTART_MARKER_END = 0xFFD7;
public static final int MAX_HUFFMAN_SUBTREE = 50;
public static final int MSB = 0x80000000;
public JPEGLosslessDecoder(final byte[] data) {
buffer = ByteBuffer.wrap(data);
frame = new FrameHeader();
scan = new ScanHeader();
quantTable = new QuantizationTable();
huffTable = new HuffmanTable();
}
public int[][] decode() throws IOException {
int current, scanNum = 0;
final int pred[] = new int[10];
int[][] outputRef = null;
xLoc = 0;
yLoc = 0;
current = get16();
if (current != 0xFFD8) { // SOI
throw new IOException("Not a JPEG file");
}
current = get16();
while (((current >> 4) != 0x0FFC) || (current == 0xFFC4)) { // SOF 0~15
switch (current) {
case 0xFFC4: // DHT
huffTable.read(this, HuffTab);
break;
case 0xFFCC: // DAC
throw new IOException("Program doesn't support arithmetic coding. (format throw new IOException)");
case 0xFFDB:
quantTable.read(this, TABLE);
break;
case 0xFFDD:
restartInterval = readNumber();
break;
case 0xFFE0:
case 0xFFE1:
case 0xFFE2:
case 0xFFE3:
case 0xFFE4:
case 0xFFE5:
case 0xFFE6:
case 0xFFE7:
case 0xFFE8:
case 0xFFE9:
case 0xFFEA:
case 0xFFEB:
case 0xFFEC:
case 0xFFED:
case 0xFFEE:
case 0xFFEF:
readApp();
break;
case 0xFFFE:
readComment();
break;
default:
if ((current >> 8) != 0xFF) {
throw new IOException("ERROR: format throw new IOException! (decode)");
}
}
current = get16();
}
if ((current < 0xFFC0) || (current > 0xFFC7)) {
throw new IOException("ERROR: could not handle arithmetic code!");
}
frame.read(this);
current = get16();
do {
while (current != 0x0FFDA) { //SOS
switch (current) {
case 0xFFC4: //DHT
huffTable.read(this, HuffTab);
break;
case 0xFFCC: //DAC
throw new IOException("Program doesn't support arithmetic coding. (format throw new IOException)");
case 0xFFDB:
quantTable.read(this, TABLE);
break;
case 0xFFDD:
restartInterval = readNumber();
break;
case 0xFFE0:
case 0xFFE1:
case 0xFFE2:
case 0xFFE3:
case 0xFFE4:
case 0xFFE5:
case 0xFFE6:
case 0xFFE7:
case 0xFFE8:
case 0xFFE9:
case 0xFFEA:
case 0xFFEB:
case 0xFFEC:
case 0xFFED:
case 0xFFEE:
case 0xFFEF:
readApp();
break;
case 0xFFFE:
readComment();
break;
default:
if ((current >> 8) != 0xFF) {
throw new IOException("ERROR: format throw new IOException! (Parser.decode)");
}
}
current = get16();
}
final int precision = frame.getPrecision();
if (precision == 8) {
mask = 0xFF;
} else {
mask = 0xFFFF;
}
final ComponentSpec[] components = frame.getComponents();
scan.read(this);
numComp = scan.getNumComponents();
selection = scan.getSelection();
final ScanComponent[] scanComps = scan.components;
final int[][] quantTables = quantTable.quantTables;
for (int i = 0; i < numComp; i++) {
final int compN = scanComps[i].getScanCompSel();
qTab[i] = quantTables[components[compN].quantTableSel];
nBlock[i] = components[compN].vSamp * components[compN].hSamp;
dcTab[i] = HuffTab[scanComps[i].getDcTabSel()][0];
acTab[i] = HuffTab[scanComps[i].getAcTabSel()][1];
}
xDim = frame.getDimX();
yDim = frame.getDimY();
outputRef = new int[numComp][];
if (numComp == 1) {
outputData = new int[xDim * yDim];
outputRef[0] = outputData;
} else {
outputRedData = new int[xDim * yDim]; // not a good use of memory, but I had trouble packing bytes into int. some values exceeded 255.
outputGreenData = new int[xDim * yDim];
outputBlueData = new int[xDim * yDim];
outputRef[0] = outputRedData;
outputRef[1] = outputGreenData;
outputRef[2] = outputBlueData;
}
scanNum++;
while (true) { // Decode one scan
final int temp[] = new int[1]; // to store remainder bits
final int index[] = new int[1];
temp[0] = 0;
index[0] = 0;
for (int i = 0; i < 10; i++) {
pred[i] = (1 << (precision - 1));
}
if (restartInterval == 0) {
current = decode(pred, temp, index);
while ((current == 0) && ((xLoc < xDim) && (yLoc < yDim))) {
output(pred);
current = decode(pred, temp, index);
}
break; //current=MARKER
}
for (int mcuNum = 0; mcuNum < restartInterval; mcuNum++) {
restarting = (mcuNum == 0);
current = decode(pred, temp, index);
output(pred);
if (current != 0) {
break;
}
}
if (current == 0) {
if (markerIndex != 0) {
current = (0xFF00 | marker);
markerIndex = 0;
} else {
current = get16();
}
}
if ((current >= RESTART_MARKER_BEGIN) && (current <= RESTART_MARKER_END)) {
//empty
} else {
break; //current=MARKER
}
}
if ((current == 0xFFDC) && (scanNum == 1)) { //DNL
readNumber();
current = get16();
}
} while ((current != 0xFFD9) && ((xLoc < xDim) && (yLoc < yDim)) && (scanNum == 0));
return outputRef;
}
@Override
public final int get16() {
final int value = (buffer.getShort(dataBufferIndex) & 0xFFFF);
dataBufferIndex += 2;
return value;
}
@Override
public final int get8() {
return buffer.get(dataBufferIndex++) & 0xFF;
}
private int decode(final int prev[], final int temp[], final int index[]) throws IOException {
if (numComp == 1) {
return decodeSingle(prev, temp, index);
} else if (numComp == 3) {
return decodeRGB(prev, temp, index);
} else {
return -1;
}
}
private int decodeSingle(final int prev[], final int temp[], final int index[]) throws IOException {
// At the beginning of the first line and
// at the beginning of each restart interval the prediction value of 2P – 1 is used, where P is the input precision.
if (restarting) {
restarting = false;
prev[0] = (1 << (frame.getPrecision() - 1));
} else {
switch (selection) {
case 2:
prev[0] = getPreviousY(outputData);
break;
case 3:
prev[0] = getPreviousXY(outputData);
break;
case 4:
prev[0] = (getPreviousX(outputData) + getPreviousY(outputData)) - getPreviousXY(outputData);
break;
case 5:
prev[0] = getPreviousX(outputData) + ((getPreviousY(outputData) - getPreviousXY(outputData)) >> 1);
break;
case 6:
prev[0] = getPreviousY(outputData) + ((getPreviousX(outputData) - getPreviousXY(outputData)) >> 1);
break;
case 7:
prev[0] = (int) (((long) getPreviousX(outputData) + getPreviousY(outputData)) / 2);
break;
default:
prev[0] = getPreviousX(outputData);
break;
}
}
for (int i = 0; i < nBlock[0]; i++) {
final int value = getHuffmanValue(dcTab[0], temp, index);
if (value >= 0xFF00) {
return value;
}
final int n = getn(prev, value, temp, index);
final int nRestart = (n >> 8);
if ((nRestart >= RESTART_MARKER_BEGIN) && (nRestart <= RESTART_MARKER_END)) {
return nRestart;
}
prev[0] += n;
}
return 0;
}
private int decodeRGB(final int prev[], final int temp[], final int index[]) throws IOException {
switch (selection) {
case 2:
prev[0] = getPreviousY(outputRedData);
prev[1] = getPreviousY(outputGreenData);
prev[2] = getPreviousY(outputBlueData);
break;
case 3:
prev[0] = getPreviousXY(outputRedData);
prev[1] = getPreviousXY(outputGreenData);
prev[2] = getPreviousXY(outputBlueData);
break;
case 4:
prev[0] = (getPreviousX(outputRedData) + getPreviousY(outputRedData)) - getPreviousXY(outputRedData);
prev[1] = (getPreviousX(outputGreenData) + getPreviousY(outputGreenData)) - getPreviousXY(outputGreenData);
prev[2] = (getPreviousX(outputBlueData) + getPreviousY(outputBlueData)) - getPreviousXY(outputBlueData);
break;
case 5:
prev[0] = getPreviousX(outputRedData) + ((getPreviousY(outputRedData) - getPreviousXY(outputRedData)) >> 1);
prev[1] = getPreviousX(outputGreenData) + ((getPreviousY(outputGreenData) - getPreviousXY(outputGreenData)) >> 1);
prev[2] = getPreviousX(outputBlueData) + ((getPreviousY(outputBlueData) - getPreviousXY(outputBlueData)) >> 1);
break;
case 6:
prev[0] = getPreviousY(outputRedData) + ((getPreviousX(outputRedData) - getPreviousXY(outputRedData)) >> 1);
prev[1] = getPreviousY(outputGreenData) + ((getPreviousX(outputGreenData) - getPreviousXY(outputGreenData)) >> 1);
prev[2] = getPreviousY(outputBlueData) + ((getPreviousX(outputBlueData) - getPreviousXY(outputBlueData)) >> 1);
break;
case 7:
prev[0] = (int) (((long) getPreviousX(outputRedData) + getPreviousY(outputRedData)) / 2);
prev[1] = (int) (((long) getPreviousX(outputGreenData) + getPreviousY(outputGreenData)) / 2);
prev[2] = (int) (((long) getPreviousX(outputBlueData) + getPreviousY(outputBlueData)) / 2);
break;
default:
prev[0] = getPreviousX(outputRedData);
prev[1] = getPreviousX(outputGreenData);
prev[2] = getPreviousX(outputBlueData);
break;
}
int value, actab[], dctab[];
int qtab[];
for (int ctrC = 0; ctrC < numComp; ctrC++) {
qtab = qTab[ctrC];
actab = acTab[ctrC];
dctab = dcTab[ctrC];
for (int i = 0; i < nBlock[ctrC]; i++) {
for (int k = 0; k < IDCT_Source.length; k++) {
IDCT_Source[k] = 0;
}
value = getHuffmanValue(dctab, temp, index);
if (value >= 0xFF00) {
return value;
}
prev[ctrC] = IDCT_Source[0] = prev[ctrC] + getn(index, value, temp, index);
IDCT_Source[0] *= qtab[0];
for (int j = 1; j < 64; j++) {
value = getHuffmanValue(actab, temp, index);
if (value >= 0xFF00) {
return value;
}
j += (value >> 4);
if ((value & 0x0F) == 0) {
if ((value >> 4) == 0) {
break;
}
} else {
IDCT_Source[IDCT_P[j]] = getn(index, value & 0x0F, temp, index) * qtab[j];
}
}
}
}
return 0;
}
// Huffman table for fast search: (HuffTab) 8-bit Look up table 2-layer search architecture, 1st-layer represent 256 node (8 bits) if codeword-length > 8
// bits, then the entry of 1st-layer = (# of 2nd-layer table) | MSB and it is stored in the 2nd-layer Size of tables in each layer are 256.
// HuffTab[*][*][0-256] is always the only 1st-layer table.
//
// An entry can be: (1) (# of 2nd-layer table) | MSB , for code length > 8 in 1st-layer (2) (Code length) << 8 | HuffVal
//
// HuffmanValue(table HuffTab[x][y] (ex) HuffmanValue(HuffTab[1][0],...)
// ):
// return: Huffman Value of table
// 0xFF?? if it receives a MARKER
// Parameter: table HuffTab[x][y] (ex) HuffmanValue(HuffTab[1][0],...)
// temp temp storage for remainded bits
// index index to bit of temp
// in FILE pointer
// Effect:
// temp store new remainded bits
// index change to new index
// in change to new position
// NOTE:
// Initial by temp=0; index=0;
// NOTE: (explain temp and index)
// temp: is always in the form at calling time or returning time
// | byte 4 | byte 3 | byte 2 | byte 1 |
// | 0 | 0 | 00000000 | 00000??? | if not a MARKER
// ^index=3 (from 0 to 15)
// 321
// NOTE (marker and marker_index):
// If get a MARKER from 'in', marker=the low-byte of the MARKER
// and marker_index=9
// If marker_index=9 then index is always > 8, or HuffmanValue()
// will not be called
private int getHuffmanValue(final int table[], final int temp[], final int index[]) throws IOException {
int code, input;
final int mask = 0xFFFF;
if (index[0] < 8) {
temp[0] <<= 8;
input = get8();
if (input == 0xFF) {
marker = get8();
if (marker != 0) {
markerIndex = 9;
}
}
temp[0] |= input;
} else {
index[0] -= 8;
}
code = table[temp[0] >> index[0]];
if ((code & MSB) != 0) {
if (markerIndex != 0) {
markerIndex = 0;
return 0xFF00 | marker;
}
temp[0] &= (mask >> (16 - index[0]));
temp[0] <<= 8;
input = get8();
if (input == 0xFF) {
marker = get8();
if (marker != 0) {
markerIndex = 9;
}
}
temp[0] |= input;
code = table[((code & 0xFF) * 256) + (temp[0] >> index[0])];
index[0] += 8;
}
index[0] += 8 - (code >> 8);
if (index[0] < 0) {
throw new IOException("index=" + index[0] + " temp=" + temp[0] + " code=" + code + " in HuffmanValue()");
}
if (index[0] < markerIndex) {
markerIndex = 0;
return 0xFF00 | marker;
}
temp[0] &= (mask >> (16 - index[0]));
return code & 0xFF;
}
private int getn(final int[] PRED, final int n, final int temp[], final int index[]) throws IOException {
int result;
final int one = 1;
final int n_one = -1;
final int mask = 0xFFFF;
int input;
if (n == 0) {
return 0;
}
if (n == 16) {
if (PRED[0] >= 0) {
return -32768;
} else {
return 32768;
}
}
index[0] -= n;
if (index[0] >= 0) {
if ((index[0] < markerIndex) && !isLastPixel()) { // this was corrupting the last pixel in some cases
markerIndex = 0;
return (0xFF00 | marker) << 8;
}
result = temp[0] >> index[0];
temp[0] &= (mask >> (16 - index[0]));
} else {
temp[0] <<= 8;
input = get8();
if (input == 0xFF) {
marker = get8();
if (marker != 0) {
markerIndex = 9;
}
}
temp[0] |= input;
index[0] += 8;
if (index[0] < 0) {
if (markerIndex != 0) {
markerIndex = 0;
return (0xFF00 | marker) << 8;
}
temp[0] <<= 8;
input = get8();
if (input == 0xFF) {
marker = get8();
if (marker != 0) {
markerIndex = 9;
}
}
temp[0] |= input;
index[0] += 8;
}
if (index[0] < 0) {
throw new IOException("index=" + index[0] + " in getn()");
}
if (index[0] < markerIndex) {
markerIndex = 0;
return (0xFF00 | marker) << 8;
}
result = temp[0] >> index[0];
temp[0] &= (mask >> (16 - index[0]));
}
if (result < (one << (n - 1))) {
result += (n_one << n) + 1;
}
return result;
}
private int getPreviousX(final int data[]) {
if (xLoc > 0) {
return data[((yLoc * xDim) + xLoc) - 1];
} else if (yLoc > 0) {
return getPreviousY(data);
} else {
return (1 << (frame.getPrecision() - 1));
}
}
private int getPreviousXY(final int data[]) {
if ((xLoc > 0) && (yLoc > 0)) {
return data[(((yLoc - 1) * xDim) + xLoc) - 1];
} else {
return getPreviousY(data);
}
}
private int getPreviousY(final int data[]) {
if (yLoc > 0) {
return data[((yLoc - 1) * xDim) + xLoc];
} else {
return getPreviousX(data);
}
}
private boolean isLastPixel() {
return (xLoc == (xDim - 1)) && (yLoc == (yDim - 1));
}
private void output(final int PRED[]) {
if (numComp == 1) {
outputSingle(PRED);
} else {
outputRGB(PRED);
}
}
private void outputSingle(final int PRED[]) {
if ((xLoc < xDim) && (yLoc < yDim)) {
outputData[(yLoc * xDim) + xLoc] = mask & PRED[0];
xLoc++;
if (xLoc >= xDim) {
yLoc++;
xLoc = 0;
}
}
}
private void outputRGB(final int PRED[]) {
if ((xLoc < xDim) && (yLoc < yDim)) {
outputRedData[(yLoc * xDim) + xLoc] = PRED[0];
outputGreenData[(yLoc * xDim) + xLoc] = PRED[1];
outputBlueData[(yLoc * xDim) + xLoc] = PRED[2];
xLoc++;
if (xLoc >= xDim) {
yLoc++;
xLoc = 0;
}
}
}
private int readApp() throws IOException {
int count = 0;
final int length = get16();
count += 2;
while (count < length) {
get8();
count++;
}
return length;
}
private String readComment() throws IOException {
final StringBuffer sb = new StringBuffer();
int count = 0;
final int length = get16();
count += 2;
while (count < length) {
sb.append((char) get8());
count++;
}
return sb.toString();
}
private int readNumber() throws IOException {
final int Ld = get16();
if (Ld != 4) {
throw new IOException("ERROR: Define number format throw new IOException [Ld!=4]");
}
return get16();
}
public int getNumComponents() {
return numComp;
}
public int getPrecision() {
return frame.getPrecision();
}
}
| [
"martinezmj@uthscsa.edu"
] | martinezmj@uthscsa.edu |
5a98ae06e13f68cfe2616312543d67b4a9f30597 | 61a994e7089e22b1a72d16d6f7853ce366d0f36d | /projectCode/src/exercise2/Database.java | 4fdbae8ad0d6789ef147daf1a8f3cc02cf4394db | [] | no_license | Mattie432/Software-Systems-Componentes-A | 8147dd35f0cc2eeedcf9b89f9d7446cb1b186d92 | 5466c9a6ec8f168e1eb4bd20e1402c3b180d01be | refs/heads/master | 2021-01-23T13:44:24.748576 | 2014-09-13T01:07:46 | 2014-09-13T01:07:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 23,128 | java | package exercise2;
import java.sql.*;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
public class Database {
private Connection dbConn = null;
/**
* Constructor for the database, this
* initialises the connection to the server.
*/
public Database() {
connectToDatabase();
}
/**
* Establish a connection to the database.
*/
public void connectToDatabase() {
System.out.println();
String dbName = "jdbc:postgresql://dbteach2.cs.bham.ac.uk/mattie432";
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
System.out.println("Driver not found");
}
System.out.println("PostgreSQL driver registered.");
try {
dbConn = DriverManager.getConnection(dbName, "mxf203", "password");
System.out.println("Database accessed!");
dbConn.setAutoCommit(false);
} catch (SQLException ex) {
ex.printStackTrace();
}
if (dbConn != null) {
} else {
System.out.println("Failed to make connection");
}
}
/**
* Close the connection to the database.
*/
public void disconnectFromDatabase() {
System.out.println();
try {
dbConn.close();
System.out.println("Database connection closed");
} catch (SQLException e) {
System.out.println("Error closing database \n");
e.printStackTrace();
}
}
/**
* Creates all of the tables in the database for testing purposes.
*/
public void createTables() {
System.out.println();
System.out.println("Starting table creation.");
int numSqlQueries = 9;
String[] sql = new String[numSqlQueries];
PreparedStatement stmt = null;
String[] tableNames = new String[9];
tableNames[0] = "Title";
tableNames[1] = "Student";
tableNames[2] = "Session";
tableNames[3] = "Type";
tableNames[4] = "NextOfKin";
tableNames[5] = "Lecturer";
tableNames[6] = "Course";
tableNames[7] = "Marks";
tableNames[8] = "StudentContact";
// constraints, length checks on strings
sql[0] = "CREATE TABLE Titles (" +
"titleID SERIAL, " +
"titleString varchar(500) UNIQUE NOT NULL," +
"PRIMARY KEY (titleID)" +
");";
sql[1] = "CREATE TABLE Student (" +
"studentID SERIAL, " +
"titleID int NOT NULL," +
"forname varchar(100)," +
"familyName varchar(100), " +
"dateOfBirth DATE NOT NULL," +
"sex varchar(1) NOT NULL," +
"PRIMARY KEY (studentID)," +
"FOREIGN KEY (titleID) REFERENCES Titles(titleID)" +
");";
sql[2] = "CREATE TABLE Session (" +
"sessionID SERIAL, " +
"sessionString varchar(500) NOT NULL," +
"PRIMARY KEY (sessionID)" +
");";
sql[3] = "CREATE TABLE Type (" +
"typeID SERIAL, " +
"typeString varchar(500) NOT NULL," +
"PRIMARY KEY (typeID)" +
");";
sql[4] = "CREATE TABLE NextOfKin (" +
"studentID int NOT NULL, " +
"eMailAddress varchar(500)," +
"postalAddress varchar(500), " +
"FOREIGN KEY (studentID) REFERENCES Student(studentID)"
+ ");";
sql[5] = "CREATE TABLE Lecturer (" +
"lecturerID SERIAL, " +
"titleID int," +
"forname varchar(100)," +
"familyName varchar(100), " +
"PRIMARY KEY (LecturerID)," +
"FOREIGN KEY (titleID) REFERENCES Titles(titleID)" +
");";
sql[6] = "CREATE TABLE Course (" +
"courseID SERIAL, " +
"courseName varchar(500) UNIQUE NOT NULL," +
"courseDescription varchar(500), " +
"lecturerID int NOT NULL," +
"PRIMARY KEY (courseID)," +
"FOREIGN KEY (lecturerID) REFERENCES Lecturer(lecturerID)" +
");";
sql[7] = "CREATE TABLE Marks (" +
"studentID int NOT NULL, " +
"courseID int NOT NULL," +
"year int NOT NULL CHECK(year>=1 AND year<=5)," +
"sessionID int NOT NULL, " +
"typeID int NOT NULL," +
"mark int NOT NULL," +
"notes varchar(500)," +
"FOREIGN KEY (studentID) REFERENCES Student(studentID)," +
"FOREIGN KEY (courseID) REFERENCES Course(courseID)," +
"FOREIGN KEY (sessionID) REFERENCES Session(sessionID)," +
"FOREIGN KEY (typeID) REFERENCES Type(typeID)" +
");";
sql[8] = "CREATE TABLE StudentContact (" +
"studentID int NOT NULL, " +
"eMailAddress varchar(100)," +
"postalAddress varchar(100), " +
"FOREIGN KEY (studentID) REFERENCES Student(studentID)" +
");";
for (int i = 0; i < numSqlQueries; i++) {
try {
stmt = dbConn.prepareStatement(sql[i]);
stmt.executeUpdate();
dbConn.commit();
System.out.println("Table created: " + tableNames[i]);
} catch (SQLException e) {
System.out.println("Error creating a new table");
e.printStackTrace();
// try rollback
if (dbConn != null) {
try {
dbConn.rollback();
System.out.println("Rollback sucsessfull");
} catch (Exception ex) {
System.out.println("Could not rollback changes");
}
}
} finally {
// close connection
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Error closing the statement connection");
e.printStackTrace();
}
}
}
System.out.println("Finished table creation.");
}
/**
* Removes all of the tables from the database.
*/
public void removeTables() {
System.out.println();
System.out.println("Starting table removal.");
int numTableNames = 9;
String[] tableNames = new String[numTableNames];
PreparedStatement stmt = null;
tableNames[0] = "Titles";
tableNames[1] = "Student";
tableNames[2] = "Session";
tableNames[3] = "Type";
tableNames[4] = "NextOfKin";
tableNames[5] = "Lecturer";
tableNames[6] = "Course";
tableNames[7] = "Marks";
tableNames[8] = "StudentContact";
for (int i = numTableNames - 1; i >= 0; i--) {
try {
String sql = "DROP TABLE " + tableNames[i] + ";";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
System.out.println("Table dropped: " + tableNames[i]);
} catch (SQLException e) {
System.out.println("Error dropping a table");
e.printStackTrace();
// try rollback
if (dbConn != null) {
try {
dbConn.rollback();
System.out.println("Rollback sucsessfull");
} catch (Exception ex) {
System.out.println("Could not rollback changes");
}
}
} finally {
// close connection
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Error closing the statement connection");
e.printStackTrace();
}
}
}
System.out.println("Table removal finished.");
}
/**
* Returns a prepared statement object ready to
* query the database.
* @param sql String - the SQL code to be rub
* @return PreparedStatement - the prepared statement to execute
*/
public PreparedStatement queryDatabaseStart(String sql){
PreparedStatement stmt = null;
try {
stmt = dbConn.prepareStatement(sql);
return stmt;
} catch (SQLException e) {
System.out.println("Error in queryDatabaseStart");
}
return stmt;
}
/**
* Allows insertion of data into the database. The sql string should
* have '?' where the variables are to go.
* @param sql String - the SQL update string
* @param values ArrayList<Object> - an array of objects corresponding to the variables in the sql string.
*/
public void insertDatabaseStart(String sql, ArrayList<Object> values){
PreparedStatement stmt = null;
try {
stmt = dbConn.prepareStatement(sql);
for(int i = 0; i<values.size(); i++){
if(values.get(i).getClass().equals(Integer.class)){
//int
stmt.setInt(i+1,(Integer) values.get(i));
}else if(values.get(i).getClass().equals(String.class)){
//string
stmt.setString(i+1, (String) values.get(i));
}
}
stmt.executeUpdate();
dbConn.commit();
System.out.println("Update sucsessful!");
} catch (SQLException e) {
System.out.println("Error inserting record.");
System.out.println(e.getMessage());
// try rollback
if (dbConn != null) {
try {
dbConn.rollback();
System.out.println("Rollback sucsessfull");
} catch (Exception ex) {
System.out.println("Could not rollback changes");
}
}
}finally{
try {
stmt.close();
stmt = null;
} catch (SQLException e) {
System.out.println("Could not close update connection.");
e.printStackTrace();
}
System.out.println();
}
}
/**
* This initialises the adding of test data to the database.
*/
public void addTestData() {
int numStudents = 100;
int numTitles = 5;
int numType = 3;
int numNextOfKin = 50;
int numLecturer = 15;
int numCourse = 100;
int numMarks = 100;
System.out.println();
System.out.println("Starting adding test data.");
addTestData_Title(numTitles);
addTestData_Student(numStudents, numTitles);
addTestData_Session();
addTestData_Type(numType);
addTestData_NextOfKin(numStudents, numNextOfKin);
addTestData_Lecturer(numLecturer, numTitles);
addTestData_Course(numCourse, numLecturer);
addTestData_Marks(numMarks, numCourse, numType, numStudents);
addTestData_StudentContact(numStudents);
System.out.println("Finished adding test data.");
System.out.println();
}
/**
* Adds test data to the Titles table.
* @param numTitles int - Number of titles to add
*/
private void addTestData_Title(int numTitles) {
String[] titles = new String[numTitles];
titles[0] = "Mr";
titles[1] = "Mrs";
titles[2] = "Miss";
titles[3] = "Dr";
titles[4] = "Ms";
PreparedStatement stmt = null;
try {
for (int i = 0; i < numTitles; i++) {
try {
String sql = "INSERT INTO Titles(titleString) VALUES(" +
"'" + titles[i] + "');";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
} catch (SQLException e) {
System.out.println("Error inserting :" + titles[i]);
e.printStackTrace();
try {
dbConn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
System.out.println("Test data inserted: Titles");
} finally {
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Could not close PreparedStatement connection");
e.printStackTrace();
}
}
}
/**
* Adds test data to the Student table.
* @param numStudents int - number of students to add
* @param numTitles int - number of titles already added
*/
private void addTestData_Student(int numStudents, int numTitles) {
PreparedStatement stmt = null;
try {
for (int i = 0; i < numStudents; i++) {
try {
String sql = "INSERT INTO " +
"Student(titleID, forname, familyName, dateOfBirth, sex) " +
"VALUES(" +
"'" + randomNumberBetween(1, numTitles) + "', " +
"'" + "forname" + (i+1) + "', " +
"'" + "familyName" + (i+1) + "', " +
"'" + randomDateOfBirth() + "', " +
"'" + randomSex() + "'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
} catch (SQLException e) {
System.out.println("Error inserting : Student " + i);
e.printStackTrace();
try {
dbConn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
System.out.println("Test data inserted: Students");
} finally {
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Could not close PreparedStatement connection");
e.printStackTrace();
}
}
}
/**
* Adds test data to the Session table.
*/
@SuppressWarnings("resource")
private void addTestData_Session() {
PreparedStatement stmt = null;
try {
try {
String sql = "INSERT INTO " +
"Session(sessionString) " +
"VALUES(" +
"'May/Aug'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
sql = "INSERT INTO " +
"Session(sessionString) " +
"VALUES(" +
"'Jan/Feb'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
} catch (SQLException e) {
System.out.println("Error inserting : Sessions");
e.printStackTrace();
try {
dbConn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
System.out.println("Test data inserted: Sessions");
} finally {
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Could not close PreparedStatement connection");
e.printStackTrace();
}
}
}
/**
* Adds test data to the Type table.
* @param numType int - Number of types to add
*/
@SuppressWarnings("resource")
private void addTestData_Type(int numType){
PreparedStatement stmt = null;
try {
try {
String sql = "INSERT INTO " +
"Type(typeString) " +
"VALUES(" +
"'normal'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
sql = "INSERT INTO " +
"Type(typeString) " +
"VALUES(" +
"'resit'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
sql = "INSERT INTO " +
"Type(typeString) " +
"VALUES(" +
"'repeat'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
} catch (SQLException e) {
System.out.println("Error inserting : Type");
e.printStackTrace();
try {
dbConn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
System.out.println("Test data inserted: Type");
} finally {
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Could not close PreparedStatement connection");
e.printStackTrace();
}
}
}
/**
* Adds test data to the Next of kin table.
* @param numStudents int - Number of students added
* @param numNextOfKin int - Number of nextOfKin added
*/
@SuppressWarnings("null")
private void addTestData_NextOfKin(int numStudents, int numNextOfKin){
PreparedStatement stmt = null;
try {
int[] usedStudentIDs = new int[numNextOfKin];
for(int i = 0; i < numNextOfKin; i++){
usedStudentIDs[i] = getUniqueRandomNumberBetween(1, numStudents, usedStudentIDs);
try {
String sql = "INSERT INTO " +
"NextOfKin(studentID,eMailAddress,postalAddress) " +
"VALUES(" +
"'" + usedStudentIDs[i] + "', " +
"'" + "emailAddress" + (i+1) +"@testing.com', " +
"'" + "PostalAddress" + (i+1) + "'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
} catch (SQLException e) {
System.out.println("Error inserting : NextOfKin" + i);
usedStudentIDs[i] = (Integer) null;
try {
dbConn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
System.out.println("Test data inserted: NextOfKin");
} finally {
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Could not close PreparedStatement connection");
e.printStackTrace();
}
}
}
/**
* Adds test data to the Lecturer table.
* @param numLecturer int - Number of lecturers to add
* @param numTitles int - Number of titles added
*/
private void addTestData_Lecturer(int numLecturer, int numTitles){
PreparedStatement stmt = null;
try {
for(int i = 0; i < numLecturer; i++){
try {
String sql = "INSERT INTO " +
"Lecturer(titleID,forname,familyName) " +
"VALUES(" +
"'" + randomNumberBetween(1, numTitles) + "', " +
"'" + "forNameLecturer" + (i+1) + "', " +
"'" + "familyNameLecturer" + (i+1) + "'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
} catch (SQLException e) {
System.out.println("Error inserting : Lecturer");
e.printStackTrace();
try {
dbConn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
System.out.println("Test data inserted: Lecturer");
} finally {
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Could not close PreparedStatement connection");
e.printStackTrace();
}
}
}
/**
* Adds test data to the Course table.
* @param numCourse int - number of courses to add
* @param numLecturer int - Number of lecurers added
*/
private void addTestData_Course(int numCourse, int numLecturer){
PreparedStatement stmt = null;
try {
for(int i = 0; i < numCourse; i++){
try {
String sql = "INSERT INTO " +
"Course(courseName, courseDescription, lecturerID) " +
"VALUES(" +
"'" + "courseName" + (i+1) + "', " +
"'" + "courseDescription" + (i+1) + "', " +
"'" + randomNumberBetween(1, numLecturer) + "'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
} catch (SQLException e) {
System.out.println("Error inserting : Course");
e.printStackTrace();
try {
dbConn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
System.out.println("Test data inserted: Course");
} finally {
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Could not close PreparedStatement connection");
e.printStackTrace();
}
}
}
/**
* Adds test data to the Marks table.
* @param numMarks int - Number of marks to add
* @param numCourse int - number of courses added
* @param numType int - number of types added
* @param numStudentsint - number of students added
*/
private void addTestData_Marks(int numMarks, int numCourse, int numType, int numStudents){
PreparedStatement stmt = null;
try {
for(int i = 0; i < numMarks; i++){
try {
int studentID = randomNumberBetween(1, numStudents);
int courseID = randomNumberBetween(1, numCourse);
int year = randomNumberBetween(1, 5);
int sessionID = randomNumberBetween(1, 2);
int typeID = randomNumberBetween(1, numType);
int mark = randomNumberBetween(0, 100);
String notes = "Notes notes note. Note note note notes.";
String sql = "INSERT INTO " +
"Marks(studentID, CourseID, year, sessionID, typeID, mark, notes) " +
"VALUES(" +
"'" + studentID + "', " +
"'" + courseID + "', " +
"'" + year + "', " +
"'" + sessionID + "', " +
"'" + typeID + "', " +
"'" + mark + "', " +
"'" + notes + "'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
} catch (SQLException e) {
System.out.println("Error inserting : Marks");
e.printStackTrace();
try {
dbConn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
System.out.println("Test data inserted: Marks");
} finally {
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Could not close PreparedStatement connection");
e.printStackTrace();
}
}
}
/**
* Adds test data to the StudentContact table.
* @param numStudents int - NUmber of students added
*/
@SuppressWarnings("null")
private void addTestData_StudentContact(int numStudents){
PreparedStatement stmt = null;
try {
int[] listOfUsedIDs = new int[numStudents];
for(int i = 0; i < numStudents; i++){
try {
listOfUsedIDs[i] = getUniqueRandomNumberBetween(1, numStudents, listOfUsedIDs);
String sql = "INSERT INTO " +
"StudentContact(studentID, eMailAddress, postalAddress) " +
"VALUES(" +
"'" + listOfUsedIDs[i] + "', " +
"'" + "eMailAddress" + (i+1) + "@test.com', " +
"'" + "postalAddress" + (i+1) + "'" +
");";
stmt = dbConn.prepareStatement(sql);
stmt.executeUpdate();
dbConn.commit();
} catch (SQLException e) {
System.out.println("Error inserting : StudentContact");
e.printStackTrace();
listOfUsedIDs[i] = (Integer) null;
try {
dbConn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
System.out.println("Test data inserted: StudentContact");
} finally {
try {
stmt.close();
} catch (SQLException e) {
System.out
.println("Could not close PreparedStatement connection");
e.printStackTrace();
}
}
}
/**
* Creats a table from the data in the result set provided.
* @param rs ResultSet - The result set of the query
* @return DefaultTableModel - The completed table model
* @throws SQLException
*/
public DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
/**
* Generates a random number and checks it against the list of previously used ones.
* @param min int - Min value
* @param max int - Max value
* @param listOfUsedIDs int[] - Int array of used values
* @return int - Unique random number.
*/
private int getUniqueRandomNumberBetween(int min, int max, int[] listOfUsedIDs){
int r = randomNumberBetween(min, max);
for(int i = 0; i < listOfUsedIDs.length; i++){
if(listOfUsedIDs[i] == r){
r = getUniqueRandomNumberBetween(min, max, listOfUsedIDs);
}
}
return r;
}
/**
* Generates a random sex.
* @return String - m/f
*/
private String randomSex(){
int i = randomNumberBetween(0,1);
if(i == 0){
return "m";
}else
return "f";
}
/**
* Generates a random date of birth in the format
* dd-mm-yyy
* @return String - Date
*/
private String randomDateOfBirth(){
int year = randomNumberBetween(1950, 2010);
int month = randomNumberBetween(1, 12);
int day = randomNumberBetween(1, 28);
return day + "-" + month + "-" + year;
}
private int randomNumberBetween(int min, int max){
return min + (int)Math.round(Math.random() * (max - min));
}
}
| [
"mattie432@icloud.com"
] | mattie432@icloud.com |
986ff17bcd0d87ff5e4e177b72ade0560ef6cf9b | b0dee27b5d999f2d982b501c33e49f2b0e027795 | /tests/org.openhealthtools.mdht.uml.cda.consol2.tests/src/test/java/org/openhealthtools/mdht/uml/cda/consol/tests/FunctionalStatusSectionTest.java | 20820dcd6284a8474310a157fb9ed2bcdb76bf47 | [] | no_license | vadimnehta/mdht-models | a8e0696f20f1c93353d0db43192835a77e2b99f3 | 588ea77d8fe9e1ca2c97d3b25a361f3b727434c8 | refs/heads/develop | 2020-12-30T23:59:22.885567 | 2015-10-22T05:00:50 | 2015-10-22T05:00:50 | 39,483,189 | 0 | 0 | null | 2015-07-22T03:20:52 | 2015-07-22T03:20:52 | null | UTF-8 | Java | false | false | 30,929 | java | /*******************************************************************************
* Copyright (c) 2011, 2012 Sean Muir and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sean Muir (JKM Software) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.uml.cda.consol.tests;
import java.util.Map;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.ecore.EObject;
import org.junit.Test;
import org.openhealthtools.mdht.uml.cda.CDAFactory;
import org.openhealthtools.mdht.uml.cda.StrucDocText;
import org.openhealthtools.mdht.uml.cda.consol.ConsolFactory;
import org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection;
import org.openhealthtools.mdht.uml.cda.consol.operations.FunctionalStatusSectionOperations;
import org.openhealthtools.mdht.uml.cda.operations.CDAValidationTest;
import org.openhealthtools.mdht.uml.hl7.datatypes.DatatypesFactory;
import org.openhealthtools.mdht.uml.hl7.datatypes.ST;
/**
* <!-- begin-user-doc -->
* A static utility class that provides operations related to '<em><b>Functional Status Section</b></em>' model objects.
* <!-- end-user-doc -->
*
* <p>
* The following operations are supported:
* <ul>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionTemplateId(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Template Id</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionCode(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Code</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionTitle(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Title</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionText(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Text</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionFunctionalStatusResultOrganizer(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Functional Status Result Organizer</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionCognitiveStatusResultOrganizer(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Cognitive Status Result Organizer</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionFunctionalStatusResultObservation(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Functional Status Result Observation</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionCognitiveStatusResultObservation(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Cognitive Status Result Observation</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionFunctionalStatusProblemObservation(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Functional Status Problem Observation</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionCognitiveStatusProblemObservation(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Cognitive Status Problem Observation</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionCaregiverCharacteristics(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Caregiver Characteristics</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionAssessmentScaleObservation(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Assessment Scale Observation</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionNonMedicinalSupplyActivity(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Non Medicinal Supply Activity</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionPressureUlcerObservation(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Pressure Ulcer Observation</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionNumberOfPressureUlcersObservation(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Number Of Pressure Ulcers Observation</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#validateFunctionalStatusSectionHighestPressureUlcerStage(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Functional Status Section Highest Pressure Ulcer Stage</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getFunctionalStatusResultOrganizers() <em>Get Functional Status Result Organizers</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getCognitiveStatusResultOrganizers() <em>Get Cognitive Status Result Organizers</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getFunctionalStatusResultObservations() <em>Get Functional Status Result Observations</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getCognitiveStatusResultObservations() <em>Get Cognitive Status Result Observations</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getFunctionalStatusProblemObservations() <em>Get Functional Status Problem Observations</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getCognitiveStatusProblemObservations() <em>Get Cognitive Status Problem Observations</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getCaregiverCharacteristicss() <em>Get Caregiver Characteristicss</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getAssessmentScaleObservations() <em>Get Assessment Scale Observations</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getNonMedicinalSupplyActivities() <em>Get Non Medicinal Supply Activities</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getPressureUlcerObservations() <em>Get Pressure Ulcer Observations</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getNumberOfPressureUlcersObservations() <em>Get Number Of Pressure Ulcers Observations</em>}</li>
* <li>{@link org.openhealthtools.mdht.uml.cda.consol.FunctionalStatusSection#getHighestPressureUlcerStages() <em>Get Highest Pressure Ulcer Stages</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class FunctionalStatusSectionTest extends CDAValidationTest {
/**
*
* @generated
*/
@Test
public void testValidateFunctionalStatusSectionTemplateId() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionTemplateIdTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionTemplateId",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_TEMPLATE_ID__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionTemplateId(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionTemplateIdTestCase.doValidationTest();
}
/**
*
* @generated
*/
@Test
public void testValidateFunctionalStatusSectionCode() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionCodeTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionCode",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_CODE__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionCode(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionCodeTestCase.doValidationTest();
}
/**
*
* @generated
*/
@Test
public void testValidateFunctionalStatusSectionTitle() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionTitleTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionTitle",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_TITLE__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
ST title = DatatypesFactory.eINSTANCE.createST("title");
target.setTitle(title);
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionTitle(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionTitleTestCase.doValidationTest();
}
/**
*
* @generated
*/
@Test
public void testValidateFunctionalStatusSectionText() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionTextTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionText",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_TEXT__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
StrucDocText text = CDAFactory.eINSTANCE.createStrucDocText();
target.setText(text);
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionText(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionTextTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionFunctionalStatusResultOrganizer() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionFunctionalStatusResultOrganizerTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionFunctionalStatusResultOrganizer",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_FUNCTIONAL_STATUS_RESULT_ORGANIZER__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addOrganizer(ConsolFactory.eINSTANCE.createFunctionalStatusResultOrganizer().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionFunctionalStatusResultOrganizer(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionFunctionalStatusResultOrganizerTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionCognitiveStatusResultOrganizer() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionCognitiveStatusResultOrganizerTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionCognitiveStatusResultOrganizer",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_COGNITIVE_STATUS_RESULT_ORGANIZER__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addOrganizer(ConsolFactory.eINSTANCE.createCognitiveStatusResultOrganizer().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionCognitiveStatusResultOrganizer(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionCognitiveStatusResultOrganizerTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionFunctionalStatusResultObservation() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionFunctionalStatusResultObservationTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionFunctionalStatusResultObservation",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_FUNCTIONAL_STATUS_RESULT_OBSERVATION__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addObservation(ConsolFactory.eINSTANCE.createFunctionalStatusResultObservation().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionFunctionalStatusResultObservation(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionFunctionalStatusResultObservationTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionCognitiveStatusResultObservation() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionCognitiveStatusResultObservationTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionCognitiveStatusResultObservation",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_COGNITIVE_STATUS_RESULT_OBSERVATION__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addObservation(ConsolFactory.eINSTANCE.createCognitiveStatusResultObservation().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionCognitiveStatusResultObservation(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionCognitiveStatusResultObservationTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionFunctionalStatusProblemObservation() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionFunctionalStatusProblemObservationTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionFunctionalStatusProblemObservation",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_FUNCTIONAL_STATUS_PROBLEM_OBSERVATION__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addObservation(ConsolFactory.eINSTANCE.createFunctionalStatusProblemObservation().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionFunctionalStatusProblemObservation(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionFunctionalStatusProblemObservationTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionCognitiveStatusProblemObservation() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionCognitiveStatusProblemObservationTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionCognitiveStatusProblemObservation",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_COGNITIVE_STATUS_PROBLEM_OBSERVATION__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addObservation(ConsolFactory.eINSTANCE.createCognitiveStatusProblemObservation().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionCognitiveStatusProblemObservation(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionCognitiveStatusProblemObservationTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionCaregiverCharacteristics() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionCaregiverCharacteristicsTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionCaregiverCharacteristics",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_CAREGIVER_CHARACTERISTICS__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addObservation(ConsolFactory.eINSTANCE.createCaregiverCharacteristics().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionCaregiverCharacteristics(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionCaregiverCharacteristicsTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionAssessmentScaleObservation() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionAssessmentScaleObservationTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionAssessmentScaleObservation",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_ASSESSMENT_SCALE_OBSERVATION__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addObservation(ConsolFactory.eINSTANCE.createAssessmentScaleObservation().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionAssessmentScaleObservation(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionAssessmentScaleObservationTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionNonMedicinalSupplyActivity() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionNonMedicinalSupplyActivityTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionNonMedicinalSupplyActivity",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_NON_MEDICINAL_SUPPLY_ACTIVITY__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addSupply(ConsolFactory.eINSTANCE.createNonMedicinalSupplyActivity().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionNonMedicinalSupplyActivity(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionNonMedicinalSupplyActivityTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionPressureUlcerObservation() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionPressureUlcerObservationTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionPressureUlcerObservation",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_PRESSURE_ULCER_OBSERVATION__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addObservation(ConsolFactory.eINSTANCE.createPressureUlcerObservation().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionPressureUlcerObservation(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionPressureUlcerObservationTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionNumberOfPressureUlcersObservation() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionNumberOfPressureUlcersObservationTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionNumberOfPressureUlcersObservation",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_NUMBER_OF_PRESSURE_ULCERS_OBSERVATION__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addObservation(ConsolFactory.eINSTANCE.createNumberOfPressureUlcersObservation().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionNumberOfPressureUlcersObservation(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionNumberOfPressureUlcersObservationTestCase.doValidationTest();
}
/**
*
* @generated not
*/
@Test
public void testValidateFunctionalStatusSectionHighestPressureUlcerStage() {
OperationsTestCase<FunctionalStatusSection> validateFunctionalStatusSectionHighestPressureUlcerStageTestCase = new OperationsTestCase<FunctionalStatusSection>(
"validateFunctionalStatusSectionHighestPressureUlcerStage",
operationsForOCL.getOCLValue("VALIDATE_FUNCTIONAL_STATUS_SECTION_HIGHEST_PRESSURE_ULCER_STAGE__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"),
objectFactory) {
@Override
protected void updateToFail(FunctionalStatusSection target) {
}
@Override
protected void updateToPass(FunctionalStatusSection target) {
target.init();
target.addObservation(ConsolFactory.eINSTANCE.createHighestPressureUlcerStage().init());
}
@Override
protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) {
return FunctionalStatusSectionOperations.validateFunctionalStatusSectionHighestPressureUlcerStage(
(FunctionalStatusSection) objectToTest, diagnostician, map);
}
};
validateFunctionalStatusSectionHighestPressureUlcerStageTestCase.doValidationTest();
}
/**
*
* @generated
*/
@Test
public void testGetFunctionalStatusResultOrganizers() {
FunctionalStatusSection target = objectFactory.create();
target.getFunctionalStatusResultOrganizers();
}
/**
*
* @generated
*/
@Test
public void testGetCognitiveStatusResultOrganizers() {
FunctionalStatusSection target = objectFactory.create();
target.getCognitiveStatusResultOrganizers();
}
/**
*
* @generated
*/
@Test
public void testGetFunctionalStatusResultObservations() {
FunctionalStatusSection target = objectFactory.create();
target.getFunctionalStatusResultObservations();
}
/**
*
* @generated
*/
@Test
public void testGetCognitiveStatusResultObservations() {
FunctionalStatusSection target = objectFactory.create();
target.getCognitiveStatusResultObservations();
}
/**
*
* @generated
*/
@Test
public void testGetFunctionalStatusProblemObservations() {
FunctionalStatusSection target = objectFactory.create();
target.getFunctionalStatusProblemObservations();
}
/**
*
* @generated
*/
@Test
public void testGetCognitiveStatusProblemObservations() {
FunctionalStatusSection target = objectFactory.create();
target.getCognitiveStatusProblemObservations();
}
/**
*
* @generated
*/
@Test
public void testGetCaregiverCharacteristicss() {
FunctionalStatusSection target = objectFactory.create();
target.getCaregiverCharacteristicss();
}
/**
*
* @generated
*/
@Test
public void testGetAssessmentScaleObservations() {
FunctionalStatusSection target = objectFactory.create();
target.getAssessmentScaleObservations();
}
/**
*
* @generated
*/
@Test
public void testGetNonMedicinalSupplyActivities() {
FunctionalStatusSection target = objectFactory.create();
target.getNonMedicinalSupplyActivities();
}
/**
*
* @generated
*/
@Test
public void testGetPressureUlcerObservations() {
FunctionalStatusSection target = objectFactory.create();
target.getPressureUlcerObservations();
}
/**
*
* @generated
*/
@Test
public void testGetNumberOfPressureUlcersObservations() {
FunctionalStatusSection target = objectFactory.create();
target.getNumberOfPressureUlcersObservations();
}
/**
*
* @generated
*/
@Test
public void testGetHighestPressureUlcerStages() {
FunctionalStatusSection target = objectFactory.create();
target.getHighestPressureUlcerStages();
}
/**
*
* @generated
*/
private static class OperationsForOCL extends FunctionalStatusSectionOperations {
public String getOCLValue(String fieldName) {
String oclValue = null;
try {
oclValue = (String) this.getClass().getSuperclass().getDeclaredField(fieldName).get(this);
} catch (Exception e) {
oclValue = "NO OCL FOUND FOR PROPERTY " + fieldName;
}
return oclValue;
}
}
/**
*
* @generated
*/
private static class ObjectFactory implements TestObjectFactory<FunctionalStatusSection> {
@Override
public FunctionalStatusSection create() {
return ConsolFactory.eINSTANCE.createFunctionalStatusSection();
}
}
/**
*
* @generated
*/
private static OperationsForOCL operationsForOCL = new OperationsForOCL();
/**
*
* @generated
*/
private static ObjectFactory objectFactory = new ObjectFactory();
/**
* Tests Operations Constructor for 100% coverage
* @generated
*/
private static class ConstructorTestClass extends FunctionalStatusSectionOperations {
};
/**
* Tests Operations Constructor for 100% coverage
* @generated
*/
@Test
public void testConstructor() {
new ConstructorTestClass();
} // testConstructor
/**
*
* @generated
*/
@Override
protected EObject getObjectToTest() {
return null;
}
} // FunctionalStatusSectionOperations
| [
"drb.gfc@comcast.net"
] | drb.gfc@comcast.net |
f753331a1ac9ecb5912d61c413f3aab966e2f897 | f7f8c000ec60b25b57b43fbd057d08783f7cb12f | /GoodsRespos/src/com/po/OutResposRecord.java | 02977ed1f42587c74612740f6972608c53e2e26c | [] | no_license | wenbochang888/MVC | f0895c5c0fc3e8eef010f066bef427f10765a7e7 | daad24b52506e47b3b59add10dee64ac596e8bcb | refs/heads/master | 2021-01-01T17:41:39.202338 | 2017-11-11T15:37:44 | 2017-11-11T15:37:44 | 98,136,540 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 955 | java | package com.po;
public class OutResposRecord {
String id;
String outTime;
String outCompany;
String outName;
int num;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOutTime() {
return outTime;
}
public void setOutTime(String outTime) {
this.outTime = outTime;
}
public String getOutCompany() {
return outCompany;
}
public void setOutCompany(String outCompany) {
this.outCompany = outCompany;
}
public String getOutName() {
return outName;
}
public void setOutName(String outName) {
this.outName = outName;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public String toString() {
return "OutResposRecord [id=" + id + ", outTime=" + outTime
+ ", outCompany=" + outCompany + ", outName=" + outName
+ ", num=" + num + "]";
}
}
| [
"727987105@qq.com"
] | 727987105@qq.com |
c9827661d6ce38359470e94b640b63f7c526565a | ddd0d8e65923472fcef2df7a86788947df25a531 | /src/main/java/fr/ensimag/ima/pseudocode/instructions/RTS.java | 1ee5a0f59dd8ff2009455fbb883c361bb776f37c | [] | no_license | JulienBernard3383279/ProjetGL | 4972ebc14ffd38798e9c4f1be57caddee53396d9 | 7dc39d489e0aa1ed5949dff3702baa79f81e93db | refs/heads/master | 2020-04-16T18:42:43.336480 | 2017-01-26T08:31:02 | 2017-01-26T08:31:02 | 165,832,623 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 199 | java | package fr.ensimag.ima.pseudocode.instructions;
import fr.ensimag.ima.pseudocode.NullaryInstruction;
/**
* @author Ensimag
* @date 01/01/2017
*/
public class RTS extends NullaryInstruction {
}
| [
"Patrick.Reignier@inria.fr"
] | Patrick.Reignier@inria.fr |
7e975adf84bb521da02ba4ab87fb9603688e38af | a7139ddf0b0f352f72019504138852b71ea4d35e | /CompanyDetailsService/src/main/java/com/pratibha/rest/companydetails/configuration/ApplicationConfig.java | bedf821b95b4caf0bb4036e1eb158740ad39e8fc | [] | no_license | pratibhasahai2301/SpringRESTApiWithAngularJS | 4f22e274275abba98b11feed263a6794685442e1 | 5dc14adbe0690f19bd72656e70e6a061ca28ef5c | refs/heads/master | 2021-01-10T05:18:48.891638 | 2016-02-18T10:26:47 | 2016-02-18T10:26:47 | 51,937,080 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 654 | java | /**
* ApplicationConfig.java
*/
package com.pratibha.rest.companydetails.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* This class is the annotation based configuration class for the application
*
* @author Pratibha Pandey
*
*/
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.pratibha.rest.companydetails")
public class ApplicationConfig extends WebMvcConfigurerAdapter {
} | [
"pratibhasahai.2301@gmail.com"
] | pratibhasahai.2301@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.