blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cc19dfd6f8190f4026239efc6f173d66ca7b3356 | 1b996fd16eb93c63341a9de377bfeb5cfae4d21e | /src/leetcodeProblems/medium/ZigzagTraversal103.java | 4a3cb01013c272473b2442bb08eb36dbf1584050 | [] | no_license | nikhilagrwl07/Leetcode-Java-Solutions | 8d5fd3a28afdf27b51c1e638cbe0283967f73224 | 28d97dd96d3faa93d6cac975518c08143be53ebe | refs/heads/master | 2021-06-15T06:08:04.860423 | 2021-05-03T15:20:53 | 2021-05-03T15:20:53 | 192,016,779 | 1 | 1 | null | 2021-04-19T13:26:06 | 2019-06-14T23:39:53 | Java | UTF-8 | Java | false | false | 2,406 | java | package leetcodeProblems.medium;
import java.util.*;
public class ZigzagTraversal103 {
public static void main(String[] args) {
ZigzagTraversal103 ob = new ZigzagTraversal103();
TreeNode treeNode = ob.buildTree();
List<List<Integer>> lists = ob.zigzagLevelOrder(treeNode);
System.out.println(lists);
}
private TreeNode buildTree() {
TreeNode root = new TreeNode(3);
TreeNode nine = new TreeNode(9);
TreeNode tweenty = new TreeNode(20);
TreeNode fifteen = new TreeNode(15);
TreeNode seven = new TreeNode(7);
root.left = nine;
root.right = tweenty;
tweenty.left = fifteen;
tweenty.right = seven;
return root;
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if (root == null)
return new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(null);
boolean flip = false;
LinkedList<Integer> levelNode = new LinkedList<>();
Stack<Integer> stack = new Stack<>();
while (!q.isEmpty()) {
TreeNode poll = q.poll();
// System.out.println(poll);
if (poll == null) {
if (flip) {
List<Integer> tmp = new ArrayList<>();
while (!stack.isEmpty()){
tmp.add(stack.pop());
}
result.add(tmp);
stack.clear();
} else {
result.add(new ArrayList<>(levelNode));
levelNode.clear();
}
flip = !flip;
if (q.peek() == null)
break;
q.add(null);
} else {
if (flip) {
stack.push(poll.val);
} else {
levelNode.add(poll.val);
}
if (poll.left != null)
q.offer(poll.left);
if (poll.right != null)
q.offer(poll.right);
}
}
return result;
}
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
}
| [
"[email protected]"
] | |
fec987542b580400fc6866c2b4287d83d295cd80 | 0e0dae718251c31cbe9181ccabf01d2b791bc2c2 | /SCT2/tags/Before_Expression_refactoring/plugins/org.yakindu.sct.model.sgraph/src/org/yakindu/sct/model/sgraph/util/SGraphAdapterFactory.java | 2b474ba33161bb11715dc6fc04ae4e7e9b327351 | [] | no_license | huybuidac20593/yakindu | 377fb9100d7db6f4bb33a3caa78776c4a4b03773 | 304fb02b9c166f340f521f5e4c41d970268f28e9 | refs/heads/master | 2021-05-29T14:46:43.225721 | 2015-05-28T11:54:07 | 2015-05-28T11:54:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 21,890 | java | /**
* Copyright (c) 2011 committers of YAKINDU 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:
* committers of YAKINDU - initial API and implementation
*
*/
package org.yakindu.sct.model.sgraph.util;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
import org.eclipse.emf.ecore.EObject;
import org.yakindu.base.base.DocumentedElement;
import org.yakindu.base.base.NamedElement;
import org.yakindu.sct.model.sgraph.*;
import org.yakindu.sct.model.sgraph.Choice;
import org.yakindu.sct.model.sgraph.CompositeElement;
import org.yakindu.sct.model.sgraph.Declaration;
import org.yakindu.sct.model.sgraph.Effect;
import org.yakindu.sct.model.sgraph.Entry;
import org.yakindu.sct.model.sgraph.Event;
import org.yakindu.sct.model.sgraph.Exit;
import org.yakindu.sct.model.sgraph.FinalState;
import org.yakindu.sct.model.sgraph.Pseudostate;
import org.yakindu.sct.model.sgraph.Reaction;
import org.yakindu.sct.model.sgraph.ReactiveElement;
import org.yakindu.sct.model.sgraph.Region;
import org.yakindu.sct.model.sgraph.RegularState;
import org.yakindu.sct.model.sgraph.SGraphPackage;
import org.yakindu.sct.model.sgraph.Scope;
import org.yakindu.sct.model.sgraph.ScopedElement;
import org.yakindu.sct.model.sgraph.SpecificationElement;
import org.yakindu.sct.model.sgraph.State;
import org.yakindu.sct.model.sgraph.Statechart;
import org.yakindu.sct.model.sgraph.Statement;
import org.yakindu.sct.model.sgraph.Synchronization;
import org.yakindu.sct.model.sgraph.Transition;
import org.yakindu.sct.model.sgraph.Trigger;
import org.yakindu.sct.model.sgraph.Variable;
import org.yakindu.sct.model.sgraph.Vertex;
/**
* <!-- begin-user-doc -->
* The <b>Adapter Factory</b> for the model.
* It provides an adapter <code>createXXX</code> method for each class of the model.
* <!-- end-user-doc -->
* @see org.yakindu.sct.model.sgraph.SGraphPackage
* @generated
*/
public class SGraphAdapterFactory extends AdapterFactoryImpl {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final String copyright = "Copyright (c) 2011 committers of YAKINDU and others.\r\nAll rights reserved. This program and the accompanying materials\r\nare made available under the terms of the Eclipse Public License v1.0\r\nwhich accompanies this distribution, and is available at\r\nhttp://www.eclipse.org/legal/epl-v10.html\r\nContributors:\r\ncommitters of YAKINDU - initial API and implementation\r\n";
/**
* The cached model package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static SGraphPackage modelPackage;
/**
* Creates an instance of the adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SGraphAdapterFactory() {
if (modelPackage == null) {
modelPackage = SGraphPackage.eINSTANCE;
}
}
/**
* Returns whether this factory is applicable for the type of the object.
* <!-- begin-user-doc -->
* This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model.
* <!-- end-user-doc -->
* @return whether this factory is applicable for the type of the object.
* @generated
*/
@Override
public boolean isFactoryForType(Object object) {
if (object == modelPackage) {
return true;
}
if (object instanceof EObject) {
return ((EObject)object).eClass().getEPackage() == modelPackage;
}
return false;
}
/**
* The switch that delegates to the <code>createXXX</code> methods.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SGraphSwitch<Adapter> modelSwitch =
new SGraphSwitch<Adapter>() {
@Override
public Adapter casePseudostate(Pseudostate object) {
return createPseudostateAdapter();
}
@Override
public Adapter caseVertex(Vertex object) {
return createVertexAdapter();
}
@Override
public Adapter caseRegion(Region object) {
return createRegionAdapter();
}
@Override
public Adapter caseTransition(Transition object) {
return createTransitionAdapter();
}
@Override
public Adapter caseFinalState(FinalState object) {
return createFinalStateAdapter();
}
@Override
public Adapter caseVariable(Variable object) {
return createVariableAdapter();
}
@Override
public Adapter caseEvent(Event object) {
return createEventAdapter();
}
@Override
public Adapter caseChoice(Choice object) {
return createChoiceAdapter();
}
@Override
public Adapter caseStatechart(Statechart object) {
return createStatechartAdapter();
}
@Override
public Adapter caseEntry(Entry object) {
return createEntryAdapter();
}
@Override
public Adapter caseExit(Exit object) {
return createExitAdapter();
}
@Override
public Adapter caseReactiveElement(ReactiveElement object) {
return createReactiveElementAdapter();
}
@Override
public Adapter caseReaction(Reaction object) {
return createReactionAdapter();
}
@Override
public Adapter caseTrigger(Trigger object) {
return createTriggerAdapter();
}
@Override
public Adapter caseEffect(Effect object) {
return createEffectAdapter();
}
@Override
public Adapter caseReactionProperty(ReactionProperty object) {
return createReactionPropertyAdapter();
}
@Override
public Adapter caseSpecificationElement(SpecificationElement object) {
return createSpecificationElementAdapter();
}
@Override
public Adapter caseDeclaration(Declaration object) {
return createDeclarationAdapter();
}
@Override
public Adapter caseScope(Scope object) {
return createScopeAdapter();
}
@Override
public Adapter caseScopedElement(ScopedElement object) {
return createScopedElementAdapter();
}
@Override
public Adapter caseSynchronization(Synchronization object) {
return createSynchronizationAdapter();
}
@Override
public Adapter caseState(State object) {
return createStateAdapter();
}
@Override
public Adapter caseStatement(Statement object) {
return createStatementAdapter();
}
@Override
public Adapter caseRegularState(RegularState object) {
return createRegularStateAdapter();
}
@Override
public Adapter caseCompositeElement(CompositeElement object) {
return createCompositeElementAdapter();
}
@Override
public Adapter caseNamedElement(NamedElement object) {
return createNamedElementAdapter();
}
@Override
public Adapter caseDocumentedElement(DocumentedElement object) {
return createDocumentedElementAdapter();
}
@Override
public Adapter defaultCase(EObject object) {
return createEObjectAdapter();
}
};
/**
* Creates an adapter for the <code>target</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param target the object to adapt.
* @return the adapter for the <code>target</code>.
* @generated
*/
@Override
public Adapter createAdapter(Notifier target) {
return modelSwitch.doSwitch((EObject)target);
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Pseudostate <em>Pseudostate</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Pseudostate
* @generated
*/
public Adapter createPseudostateAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Vertex <em>Vertex</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Vertex
* @generated
*/
public Adapter createVertexAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.base.base.NamedElement <em>Named Element</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.base.base.NamedElement
* @generated
*/
public Adapter createNamedElementAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.base.base.DocumentedElement <em>Documented Element</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.base.base.DocumentedElement
* @generated
*/
public Adapter createDocumentedElementAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Region <em>Region</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Region
* @generated
*/
public Adapter createRegionAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Transition <em>Transition</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Transition
* @generated
*/
public Adapter createTransitionAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.FinalState <em>Final State</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.FinalState
* @generated
*/
public Adapter createFinalStateAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.State <em>State</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.State
* @generated
*/
public Adapter createStateAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Statement <em>Statement</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Statement
* @generated
*/
public Adapter createStatementAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.RegularState <em>Regular State</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.RegularState
* @generated
*/
public Adapter createRegularStateAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.CompositeElement <em>Composite Element</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.CompositeElement
* @generated
*/
public Adapter createCompositeElementAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Variable <em>Variable</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Variable
* @generated
*/
public Adapter createVariableAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Event <em>Event</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Event
* @generated
*/
public Adapter createEventAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Choice <em>Choice</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Choice
* @generated
*/
public Adapter createChoiceAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Statechart <em>Statechart</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Statechart
* @generated
*/
public Adapter createStatechartAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Entry <em>Entry</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Entry
* @generated
*/
public Adapter createEntryAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Trigger <em>Trigger</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Trigger
* @generated
*/
public Adapter createTriggerAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Effect <em>Effect</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Effect
* @generated
*/
public Adapter createEffectAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.ReactionProperty <em>Reaction Property</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.ReactionProperty
* @generated
*/
public Adapter createReactionPropertyAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.SpecificationElement <em>Specification Element</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.SpecificationElement
* @generated
*/
public Adapter createSpecificationElementAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Declaration <em>Declaration</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Declaration
* @generated
*/
public Adapter createDeclarationAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Reaction <em>Reaction</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Reaction
* @generated
*/
public Adapter createReactionAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.ReactiveElement <em>Reactive Element</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.ReactiveElement
* @generated
*/
public Adapter createReactiveElementAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Exit <em>Exit</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Exit
* @generated
*/
public Adapter createExitAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Scope <em>Scope</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Scope
* @generated
*/
public Adapter createScopeAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.ScopedElement <em>Scoped Element</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.ScopedElement
* @generated
*/
public Adapter createScopedElementAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.yakindu.sct.model.sgraph.Synchronization <em>Synchronization</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.yakindu.sct.model.sgraph.Synchronization
* @generated
*/
public Adapter createSynchronizationAdapter() {
return null;
}
/**
* Creates a new adapter for the default case.
* <!-- begin-user-doc -->
* This default implementation returns null.
* <!-- end-user-doc -->
* @return the new adapter.
* @generated
*/
public Adapter createEObjectAdapter() {
return null;
}
} //SGraphAdapterFactory
| [
"[email protected]"
] | |
a181e7c88097b439e3e6148bd326254a28b4e3c1 | db6e901331155b96a42f641332ee34c730433a15 | /src/main/java/pl/mg/checkers/message/msgs/ChangeNicknameMessage.java | 736f327c8a0f4b4afcaa4542b4b6ea2cb1fd636b | [] | no_license | mgrzeszczak/checkers-client | e26e44bfb230991c80a549f8902b5b14a0660475 | fe9293f60fcc1908952a7dd24ec4086bd6fe738d | refs/heads/master | 2021-01-18T04:36:55.160658 | 2016-02-10T22:33:19 | 2016-02-10T22:33:19 | 48,804,077 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 526 | java | package pl.mg.checkers.message.msgs;
import pl.mg.checkers.message.Message;
/**
* Created by maciej on 25.12.15.
*/
public class ChangeNicknameMessage extends Message {
private String newNickname;
public ChangeNicknameMessage(String newNickname) {
this.newNickname = newNickname;
}
public ChangeNicknameMessage() {
}
public String getNewNickname() {
return newNickname;
}
public void setNewNickname(String newNickname) {
this.newNickname = newNickname;
}
}
| [
"[email protected]"
] | |
91584883290b227386c88184d9aebe4a8ab16306 | 478106dd8b16402cc17cc39b8d65f6cd4e445042 | /l2junity-gameserver/src/main/java/org/l2junity/gameserver/enums/MatchingRoomType.java | 2c92c8d7a7a753a590a735dc8d56af0e82582c56 | [] | no_license | czekay22/L2JUnderGround | 9f014cf87ddc10d7db97a2810cc5e49d74e26cdf | 1597b28eab6ec4babbf333c11f6abbc1518b6393 | refs/heads/master | 2020-12-30T16:58:50.979574 | 2018-09-28T13:38:02 | 2018-09-28T13:38:02 | 91,043,466 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 848 | java | /*
* Copyright (C) 2004-2015 L2J Unity
*
* This file is part of L2J Unity.
*
* L2J Unity is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* L2J Unity is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.l2junity.gameserver.enums;
/**
* @author Sdw
*/
public enum MatchingRoomType
{
PARTY,
COMMAND_CHANNEL
}
| [
"[email protected]"
] | |
2cf3d4d8462547a992ff55caf91c8c7c97fe867d | 099fc90a03f2e396a447dc5f36d4db1fe3676bce | /core/src/main/java/hivemall/utils/collections/arrays/FloatArray.java | b72bdef37d8d4170ce6be7d9359a2e03b2b0c505 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain",
"OFL-1.1",
"SunPro",
"MIT"
] | permissive | apache/incubator-hivemall | 7f4cc9490a8367ad1add2535f969436eec34fc31 | 34079778a96495ba428940a866b4a08af9f45088 | refs/heads/master | 2023-08-31T08:34:46.336464 | 2022-09-06T15:55:16 | 2022-09-06T15:55:16 | 68,273,151 | 322 | 213 | Apache-2.0 | 2023-04-23T15:03:20 | 2016-09-15T07:00:08 | Java | UTF-8 | Java | false | false | 1,288 | 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 hivemall.utils.collections.arrays;
import java.io.Serializable;
import javax.annotation.Nonnull;
public interface FloatArray extends Serializable {
public float get(int key);
public float get(int key, float valueIfKeyNotFound);
public void put(int key, float value);
public int size();
public int keyAt(int index);
@Nonnull
public float[] toArray();
@Nonnull
public float[] toArray(boolean copy);
public void clear();
}
| [
"[email protected]"
] | |
95c26848834f6ad309f56a59cf9333af017bc244 | 0d3a782e3e5989cd1d5263a6dc93d9e8d867d631 | /pay-web/src/main/java/com/github/dzhai/pay/dubbo/service/impl/PayDubboServiceImpl.java | 8d6e845408b928b6140a3ab3d79c01552cf3a0d7 | [] | no_license | dzhai/pay-module-demo | 277f8194bff13378da76b06ddab1d53ecdc39966 | 85e2e8988d8e5762c0b40741d4187f2d869cbb70 | refs/heads/master | 2021-01-01T03:56:14.870741 | 2016-05-22T09:16:19 | 2016-05-22T09:16:19 | 58,993,842 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,172 | java | package com.github.dzhai.pay.dubbo.service.impl;
import com.github.dzhai.pay.common.PayMethod;
import com.github.dzhai.pay.dto.PaymentData;
import com.github.dzhai.pay.dto.PaymentResultData;
import com.github.dzhai.pay.dto.RefundData;
import com.github.dzhai.pay.dto.RefundResultData;
import com.github.dzhai.pay.payment.service.IPaymentService;
import com.github.dzhai.pay.payment.utils.PaymentUtils;
import com.github.dzhai.pay.service.IPayDubboService;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PayDubboServiceImpl implements IPayDubboService {
@Override
public PaymentResultData paycreate(PaymentData data) {
log.info("----");
Integer paymethod=data.getPayMehtod();
Integer payClientType=data.getPayClientType();
if(paymethod==null){ //如何paymethod是NULL,直接设置paymethod是unionpay 银联
paymethod= PayMethod.UNIONPAY.getId();
}
IPaymentService paymentService=PaymentUtils.getPaymentService(paymethod, payClientType);
PaymentResultData resultData=paymentService.paycreate();
return resultData;
}
@Override
public RefundResultData refund(RefundData data) {
// TODO Auto-generated method stub
return null;
}
}
| [
"[email protected]"
] | |
2e58590561fcaf665f33dc2ff34ce60d810b2403 | 81c7a4aef7cb02ec642843750d99278520addace | /oral_exam2/S5_Scoreboard_Hard/src/Period.java | 18f544a7d6182b3a30080f465d648a8b97098746 | [] | no_license | konnor-s/swd | 7ecf4cad45bff37bce8fe6ab18595b21b0bfeaaa | bca5d84483251fc4f3ef7991d21c3e2f8d336f96 | refs/heads/master | 2023-02-20T06:14:21.087603 | 2020-12-01T16:54:35 | 2020-12-01T16:54:35 | 331,702,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,521 | java | /**
* Defines characteristics of a game period.
* @author Konnor Sommer
*/
public class Period {
/**
* Current period
*/
private int period;
/**
* Length of period in minutes
*/
private final int length;
/**
* Name of period.
*/
private final String name;
/**
* Number of periods
*/
private final int numPeriods;
/**
* Constructs the type of period for this game
* @param period current period
* @param length length in minutes
* @param name name of period
* @param numPeriods number of periods in a game
*/
Period(int period,int length,String name,int numPeriods){
this.period = period;
this.length = length;
this.name = name;
this.numPeriods = numPeriods;
}
/**
* Sets the current period
* @param p current period
*/
public void setPeriod(int p){
period = p;
}
/**
* Returns the current period.
* @return current period
*/
public int getPeriod(){
return period;
}
/**
* Returns the length of a period.
* @return length of period
*/
public int getLength(){
return length;
}
/**
* Returns the name of a period.
* @return name of period
*/
public String getName(){
return name;
}
/**
* Return number of periods
* @return number of periods
*/
public int getNumPeriods(){
return numPeriods;
}
}
| [
"[email protected]"
] | |
2e3c6fbf33cfb854171fbf221b9bf15b47076d35 | 4f2142d37b9dbc4b8f22ecbac2c38484c6ac28fa | /src/main/java/edu/example/Player.java | c59265e3c50547f98448fa59f2e850054ef8e9bb | [] | no_license | ashleymariecramer/salvo | 27ae74198b891ab2ce25f6653a5ede6a0d377fac | 6fac158c7a49095769878c50fc623688383ae3d4 | refs/heads/master | 2021-01-13T13:46:32.825660 | 2017-02-09T17:45:43 | 2017-02-09T17:45:43 | 76,348,957 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,589 | java | /**
* Created by ashleymariecramer on 07/12/16.
*/
package edu.example;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import javax.validation.constraints.Pattern;
import java.util.Set;
@Entity // tells Java to create a 'Player' table for this class
public class Player {
//---------------------Properties(private)----------------------------------
@Id // id instance variable holds the database key for this class.
@GeneratedValue(strategy=GenerationType.AUTO) // tells JPA to get the ID from the DBMS.
private long id;
@NotEmpty (message = "Please enter a nickname")
private String nickname;
@NotEmpty (message = "Please enter a username")
@Email (message = "Please enter valid email address")
@Pattern(regexp=".+@.+\\..+", message="Please provide a valid email address") //checks email has format [email protected]
private String username;
@NotEmpty (message = "Please enter a password")
private String password;
@OneToMany(mappedBy="player", fetch= FetchType.EAGER)
private Set<GamePlayer> gamePlayers;
@OneToMany(mappedBy="player", fetch= FetchType.EAGER)
private Set<GameScore> gameScores;
// ---------------------Constructors(public)----------------------------------
public Player() { }
public Player(String nickname, String email, String password) {
this.nickname = nickname;
this.username = email;
this.password = password;
}
// ---------------------Methods(public)----------------------------------
// Double validation - in Javascript & JAVA - checks nickname, username and password are not empty @Empty
// and also that the username has a correct email format @Email
// Can put these validation annotations either in the getters or in properties (above)
public String getNickname() {
return nickname;
}
public void setNickname(String firstName) {
this.nickname = firstName;
}
@Email (message = "Please enter valid email address")
public String getUsername() {
return username;
}
public void setUsername(String email) {
this.username = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public long getId() {
return id;
}
public Set<GamePlayer> getGamePlayers() {
return gamePlayers;
}
public Set<GameScore> getGameScores() {
return gameScores;
}
}
| [
"[email protected]"
] | |
77fc323ffc1acdf4bd9cb9d145aadccd92d12fdd | 84e88d9818116ec1f44f4e9352415d4575236208 | /src/creational/abstractfactory/ComputerAbstractFactory.java | 800275ab30d4db32687adfdca8017a22273aa6f8 | [] | no_license | kurtke1990/DesignPatterns | a96cbf5842b14e5f2404e29ea4fce98db5372526 | 68d4ee2c73a90ea48546ef599c7011bb33d9f52a | refs/heads/main | 2023-02-25T00:22:32.331010 | 2021-02-01T06:14:51 | 2021-02-01T06:14:51 | 334,109,010 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 127 | java | package creational.abstractfactory;
public interface ComputerAbstractFactory {
Computer createComputer(ComputerSpec spec);
}
| [
"[email protected]"
] | |
665c5437ba8cd0e785b6abe6e940404940920783 | 3966a29da262fa26e9434d602dd8dc113db7036b | /src/main/java/com/modria/questionaire/model/Answer.java | 24bf3c45796f46ac17de79e585f5b6fa5966dc1d | [] | no_license | jayka/dyanmic-questionaire | 81b22f5f3d09d04f64f253065bef9f9a0efba987 | 05a5397e9c6002622278eee55372bec84569fdc1 | refs/heads/master | 2020-05-20T09:22:53.608391 | 2013-12-11T11:47:49 | 2013-12-11T11:47:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 804 | java | package com.modria.questionaire.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="answer")
public class Answer {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
int rowid;
int masterId;
int id;
String value;
public int getRowid() {
return rowid;
}
public void setRowid(int rowid) {
this.rowid = rowid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getMasterId() {
return masterId;
}
public void setMasterId(int masterId) {
this.masterId = masterId;
}
}
| [
"[email protected]"
] | |
5bc6a2fae71ef20f012c34d264e8a36e00824cb9 | 751dca6f553fd22dec40fae52a0490a57985743a | /app/src/test/java/com/johnstrack/odometer/ExampleUnitTest.java | 7beb53bd96e29b8dac603cbaa51641dde26d8b60 | [] | no_license | Braveheart22/Odometer | 6e92be94b2b61bdfbc249861c3da8efccfc8229c | 5f62880ba5e1611ed0757accf55c7aea421f6c4d | refs/heads/master | 2020-03-09T13:15:50.150644 | 2018-04-09T21:34:20 | 2018-04-09T21:34:20 | 128,806,317 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 384 | java | package com.johnstrack.odometer;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
59ec5c6008a334a9508b976d87debb2e252eb359 | b2bfc22d850ddecee37ab55422a5b0041acdccb0 | /src/main/java/by/undrul/shapestask/factory/impl/PointFactoryImpl.java | 86d90b15b8f305f03447c5f9abfa1e61a0e5c63d | [] | no_license | antonundrul/shapesTask | 044e9dc66dadb04908cdc5fe888c7ef8ee8b5213 | 857a6c104a32734924a6380fd7b7e46284b87a15 | refs/heads/master | 2023-04-12T09:57:00.228532 | 2021-05-04T09:51:45 | 2021-05-04T09:51:45 | 361,407,202 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 616 | java | package by.undrul.shapestask.factory.impl;
import by.undrul.shapestask.entity.Point;
import by.undrul.shapestask.factory.PointFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class PointFactoryImpl implements PointFactory {
private static Logger logger = LogManager.getLogger();
public PointFactoryImpl() {
}
@Override
public Point createPoint(double x, double y, double z) {
logger.info("Method to create point start");
Point point = new Point(x, y, z);
logger.info("Point created");
return point;
}
}
| [
"[email protected]"
] | |
2a95094941782b2cb21fe814f36796fe767920fa | d82c200e270aced2b790e6aa389043aa28238aaa | /src/sample/Winner.java | b5638876cf95b18031d51dd1b6b16bb81cd8a224 | [] | no_license | pszczepcio/TicTacToe | 311c9a33300f8d1ad6c5529689571c94a1b57d7c | e8da6dc3743c3db8e581bd8e353329664845529c | refs/heads/master | 2020-09-05T13:34:25.433926 | 2019-11-15T00:22:12 | 2019-11-15T00:22:12 | 220,120,766 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,673 | java | package sample;
import javafx.scene.text.Text;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class Winner {
private List<Long>list = new ArrayList<>();
private String name;
private String sign;
private int fields;
public Winner(String sign, String name) {
this.sign = sign;
this.name = name;
}
public boolean findWinner() {
list.clear();
list.add(checkRow(0,3));
list.add(checkRow(3,6));
list.add(checkRow(6,9));
list.add(checkColumn(0, 3));
list.add(checkColumn(1, 3));
list.add(checkColumn(2, 3));
list.add(checkDiagonal(0, 4));
list.add(checkDiagonal(2, 2));
return list.stream()
.anyMatch(n -> n == 3);
}
private Long checkRow(int firstFieldInRow, int stepNextRow) {
return IntStream.range(firstFieldInRow, stepNextRow)
.filter(n -> Board.getBoard().get(n).getChildren().size() == 2)
.mapToObj(s -> (Text)Board.getBoard().get(s).getChildren().get(1))
.filter(d -> d.getText().equals(sign))
.count();
}
private Long checkColumn(int firstFieldInColumn, int stepToNextColumn) {
return IntStream.iterate(firstFieldInColumn, n -> n + stepToNextColumn)
.limit(3)
.filter(n -> Board.getBoard().get(n).getChildren().size() == 2)
.mapToObj(s -> (Text)Board.getBoard().get(s).getChildren().get(1))
.filter(d -> d.getText().equals(sign))
.count();
}
private Long checkDiagonal(int firstFieldOnDiagonal, int stepNexTFieldOnDiagonal) {
return IntStream.iterate(firstFieldOnDiagonal, n -> n + stepNexTFieldOnDiagonal)
.limit(3)
.filter(n -> Board.getBoard().get(n).getChildren().size() ==2)
.mapToObj(n -> (Text)Board.getBoard().get(n).getChildren().get(1))
.filter(n -> n.getText().equals(sign))
.count();
}
public List<Integer> getWinnersFields() {
List<Integer> winnersFields = new ArrayList<>();
for (int i = 0 ; i < list.size() ; i++){
if (list.get(i) == 3) {
fields = i;
break;
}
}
switch (fields) {
case 0:
winnersFields.add(0);
winnersFields.add(1);
winnersFields.add(2);
break;
case 1:
winnersFields.add(3);
winnersFields.add(4);
winnersFields.add(5);
break;
case 2:
winnersFields.add(6);
winnersFields.add(7);
winnersFields.add(8);
break;
case 3:
winnersFields.add(0);
winnersFields.add(3);
winnersFields.add(6);
break;
case 4:
winnersFields.add(1);
winnersFields.add(4);
winnersFields.add(7);
break;
case 5:
winnersFields.add(2);
winnersFields.add(5);
winnersFields.add(8);
break;
case 6:
winnersFields.add(0);
winnersFields.add(4);
winnersFields.add(8);
break;
case 7:
winnersFields.add(2);
winnersFields.add(4);
winnersFields.add(6);
break;
}
return winnersFields;
}
}
| [
"[email protected]"
] | |
9ee94679b9861e53a28227206bbc5160543f1b3d | 7784ef372e1be8a208362fd2675278ef08393687 | /Hope/src/com/service/ForumService.java | f7ee3357f34b76ad43209dff3fae10618e2ae8ae | [] | no_license | lchcoming/cng1985 | df8eb473ecf6e8d716cd2936c16a60ab718c2c11 | d122b878b9aa3c242f3d12d2ce65761f09666b6d | refs/heads/master | 2016-09-05T12:07:03.838786 | 2011-08-31T00:53:05 | 2011-08-31T00:53:05 | 41,707,910 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,835 | java | package com.service;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ada.daoimpl.ForumDaoImpl;
import com.ada.model.Forum;
public class ForumService extends HttpServlet {
/**
* Constructor of the object.
*/
public ForumService() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String title = request.getParameter("title");
String d = request.getParameter("content");
String type = request.getParameter("type");
Forum forum = new Forum();
forum.setPubtime(new Date());
forum.setTitle(title);
forum.setDescribe(d);
forum.setForumtype(type);
ForumDaoImpl dao =new ForumDaoImpl();
dao.addForum(forum);
response.sendRedirect("/admin/main.jsp");
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
| [
"cng1985@4a583d68-532f-11de-8b28-e1b452efc53a"
] | cng1985@4a583d68-532f-11de-8b28-e1b452efc53a |
9356e209ebf6471bc8fd28f384ca27da279d962a | a25d491e9d4bb218eb6e94444b12e8b8e1d57596 | /nwpu/src/main/java/com/zyw/nwpu/jifen/DuihuanActivity.java | 1cc7279f3f4f33ca0d27f3e26b9fa24d5c908cb1 | [] | no_license | 50mengzhu/NWPU | 7d809d660c068337f2dac7af0b6c8fb0b014b413 | 95976c6d2bd5d8127fd762bd8ea3866f37b92c05 | refs/heads/master | 2021-08-16T15:44:46.055883 | 2017-11-13T05:43:56 | 2017-11-13T05:43:56 | 110,503,926 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,747 | java | package com.zyw.nwpu.jifen;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.xutils.view.annotation.ContentView;
import com.zyw.nwpu.Login;
import com.zyw.nwpu.R;
import com.zyw.nwpu.app.AccountHelper;
import com.zyw.nwpu.base.BaseActivity;
import com.zyw.nwpu.jifen.leancloud.ScoreDetail;
import com.zyw.nwpu.jifen.leancloud.ScoreHelper;
import com.zyw.nwpu.jifen.leancloud.ScoreHelper.GetScoreDetailCallback;
import com.zyw.nwpu.jifen.widget.XListView;
import com.zyw.nwpulib.utils.CommonUtil;
@ContentView(R.layout.activity_duihuan)
public class DuihuanActivity extends BaseActivity implements XListView.IXListViewListener {
private XListView mListView;
List<ScoreDetail> scoreDetailList;
public static void startThis(Context cxt) {
// 判断是否已经登录
if (!AccountHelper.isLogedIn(cxt)) {
CommonUtil.ToastUtils.showShortToast(cxt, "请先登陆");
Login.startThis(cxt);
} else {
Intent intent = new Intent(cxt, DuihuanActivity.class);
cxt.startActivity(intent);
((Activity) cxt).overridePendingTransition(R.anim.slide_in_right, R.anim.fade_outs);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void initView() {
mListView = (XListView) findViewById(R.id.List_duihuanjilu);
mListView.setPullRefreshEnable(false);
mListView.setPullLoadEnable(false);
mListView.setAutoLoadEnable(true);
mListView.setXListViewListener(this);
mListView.setRefreshTime(getTime());
ScoreHelper.getPurchaseRecord(new GetScoreDetailCallback() {
public void onSuccess(List<ScoreDetail> list) {
scoreDetailList = list;
JifenCardAdapter mAdapter = new JifenCardAdapter(DuihuanActivity.this, getItems());
mListView.setAdapter(mAdapter);
}
public void onFailure(String errTip) {
Toast.makeText(DuihuanActivity.this, errTip, Toast.LENGTH_SHORT).show();
}
});
}
private List<JifenCard> getItems() {
List<JifenCard> mCards = new ArrayList<JifenCard>();
for (int i = 0; i < scoreDetailList.size(); i++) {
JifenCard mCard = new JifenCard(scoreDetailList.get(i).getDescription(), scoreDetailList.get(i).getDate(),
scoreDetailList.get(i).getScore());
mCards.add(mCard);
}
return mCards;
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
mListView.autoRefresh();
}
}
@Override
public void onRefresh() {
// mHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// // 这里是对列表的更新。
// ++mRefreshIndex;
// mAdapter = new DuihuanCardAdapter(DuihuanActivity.this,
// getItems(mCount));
// mListView.setAdapter(mAdapter);
// onLoad();
// }
// }, 1000);
}
@Override
public void onLoadMore() {
// mHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// mAdapter.notifyDataSetChanged();
// mCount += 5;
// mAdapter = new DuihuanCardAdapter(DuihuanActivity.this,
// getItems(mCount));
// mListView.setAdapter(mAdapter);
// mListView.setSelection(mCount);
// onLoad();
// }
// }, 1000);
}
private void onLoad() {
mListView.stopRefresh();
mListView.stopLoadMore();
mListView.setRefreshTime(getTime());
}
private String getTime() {
return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA).format(new Date());
}
}
| [
"[email protected]"
] | |
58460814e54aa211129d50bb918123aa7a32651d | 1be3c58802588e168d02fd40600c996699abaed4 | /test/plugin/scenarios/jedis-scenario/src/main/java/org/apache/skywalking/apm/testcase/jedis/controller/CaseController.java | e38b2b2a311bd6279e6072616e66de6d747d3c91 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | zhentaoJin/skywalking | e73a4dd612e01d93981345444a462c47096d6ab5 | dbce5f5cce2cd8ed26ce6d662f2bd6d5a0886bc1 | refs/heads/master | 2021-04-09T23:40:19.407603 | 2020-11-05T15:13:29 | 2020-11-05T15:13:29 | 305,288,772 | 6 | 0 | Apache-2.0 | 2020-10-19T06:48:38 | 2020-10-19T06:48:38 | null | UTF-8 | Java | false | false | 1,952 | 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 org.apache.skywalking.apm.testcase.jedis.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/case")
public class CaseController {
private static final String SUCCESS = "Success";
@Value("${redis.host:127.0.0.1}")
private String redisHost;
@Value("${redis.port:6379}")
private Integer redisPort;
@RequestMapping("/jedis-scenario")
@ResponseBody
public String testcase() throws Exception {
try (RedisCommandExecutor command = new RedisCommandExecutor(redisHost, redisPort)) {
command.set("a", "a");
command.get("a");
command.del("a");
}
return SUCCESS;
}
@RequestMapping("/healthCheck")
@ResponseBody
public String healthCheck() throws Exception {
try (RedisCommandExecutor command = new RedisCommandExecutor(redisHost, redisPort)) {
}
return SUCCESS;
}
}
| [
"[email protected]"
] | |
de265969c1f0d139c9c9ab0ab9227adc242860f9 | 421f0a75a6b62c5af62f89595be61f406328113b | /generated_tests/model_seeding/22_byuic-com.yahoo.platform.yui.compressor.JarClassLoader-1.0-10/com/yahoo/platform/yui/compressor/JarClassLoader_ESTest_scaffolding.java | e792a1e10bfc0e70ef771285ba672807437e6c62 | [] | no_license | tigerqiu712/evosuite-model-seeding-empirical-evaluation | c78c4b775e5c074aaa5e6ca56bc394ec03c2c7c6 | 11a920b8213d9855082d3946233731c843baf7bc | refs/heads/master | 2020-12-23T21:04:12.152289 | 2019-10-30T08:02:29 | 2019-10-30T08:02:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 554 | java | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Sat Oct 26 01:42:40 GMT 2019
*/
package com.yahoo.platform.yui.compressor;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
@EvoSuiteClassExclude
public class JarClassLoader_ESTest_scaffolding {
// Empty scaffolding for empty test suite
}
| [
"[email protected]"
] | |
25150b89c05b8f3a821193109882c88bd440c349 | e6d8ca0907ff165feb22064ca9e1fc81adb09b95 | /src/main/java/com/vmware/vim25/HostServiceSourcePackage.java | e00db708952be737c409997b85bac66739a25260 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | incloudmanager/incloud-vijava | 5821ada4226cb472c4e539643793bddeeb408726 | f82ea6b5db9f87b118743d18c84256949755093c | refs/heads/inspur | 2020-04-23T14:33:53.313358 | 2019-07-02T05:59:34 | 2019-07-02T05:59:34 | 171,236,085 | 0 | 1 | BSD-3-Clause | 2019-02-20T02:08:59 | 2019-02-18T07:32:26 | Java | UTF-8 | Java | false | false | 2,256 | java | /*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of copyright holders nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class HostServiceSourcePackage extends DynamicData {
public String sourcePackageName;
public String description;
public String getSourcePackageName() {
return this.sourcePackageName;
}
public String getDescription() {
return this.description;
}
public void setSourcePackageName(String sourcePackageName) {
this.sourcePackageName=sourcePackageName;
}
public void setDescription(String description) {
this.description=description;
}
} | [
"sjin2008@3374d856-466b-4dc9-8cc5-e1e8506a9ea1"
] | sjin2008@3374d856-466b-4dc9-8cc5-e1e8506a9ea1 |
e7034d04453d7525763a9c3377da0e18ece8f79a | 1b36a06510cdfa0104318fe8e712dd93d50529b4 | /Month2/app/src/main/java/shixun/lj/bw/month/bean/Tou.java | b792ef0289b216a07c6cee3dca307f49b66e9723 | [] | no_license | janggege/one | 1c98b3687d9f026e4602ecccbc03893eee6445e4 | a9343ec493b884e3d0eeb6079e369d7d31ab9531 | refs/heads/master | 2020-04-23T15:33:09.544255 | 2019-02-25T12:52:38 | 2019-02-25T12:52:38 | 171,269,692 | 0 | 0 | null | 2019-02-25T12:54:40 | 2019-02-18T11:13:41 | Java | UTF-8 | Java | false | false | 1,482 | java | package shixun.lj.bw.month.bean;
import java.util.List;
/*
name:刘江
data:2019
*/public class Tou {
private String message;
private String status;
private List<ResultBean> result;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<ResultBean> getResult() {
return result;
}
public void setResult(List<ResultBean> result) {
this.result = result;
}
public static class ResultBean {
private String imageUrl;
private String jumpUrl;
private int rank;
private String title;
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getJumpUrl() {
return jumpUrl;
}
public void setJumpUrl(String jumpUrl) {
this.jumpUrl = jumpUrl;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
}
| [
"[email protected]"
] | |
38e60658e0526977af2289eba4a62e4ff0ac76db | 20e345bea2b7f9662fff2fdd579a40f8397f5710 | /SpringBootIn28Minutes/src/main/java/com/boa/SpringBootIn28Minutes/exception/CustomisedExceptionHandler.java | fcafd93761258c48655451808d79c983510ac66c | [] | no_license | vipin17rathore/vipin_sts_local_repo | 527e8546043e31814e50de3cdd8e63be1c054e3e | 8d17f4d9d00c021009b841eec4fcd78878ff66aa | refs/heads/master | 2023-05-04T18:33:07.973345 | 2021-05-28T10:47:58 | 2021-05-28T10:47:58 | 254,809,014 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,617 | java | package com.boa.SpringBootIn28Minutes.exception;
import java.util.Date;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
@RestController
public class CustomisedExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<ExceptionResponse> handleAllException(Exception ex , WebRequest webreq){
ExceptionResponse response = new ExceptionResponse();
response.setMessage(ex.getMessage());
response.setDate(new Date());
response.setDetails(webreq.getDescription(false));
return new ResponseEntity<ExceptionResponse>(response,HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
ExceptionResponse response = new ExceptionResponse();
response.setMessage(ex.getMessage());
response.setDate(new Date());
response.setDetails(ex.getBindingResult().toString());
return new ResponseEntity<Object>(response,HttpStatus.BAD_REQUEST);
}
}
| [
"[email protected]"
] | |
2720c91c37dbd069c8be2d9ed3e9fcffc01c08e0 | 0995b3a6419ec1a072eef16f5040cd83c123e55d | /src/main/java/com/example/mspr/MsprApplication.java | 6f5ba6c27ecc3301a90d39e21698cda913fb575a | [] | no_license | TheMOKETBOY/MaintEvolApp | 7152565fcef374d811bdebee9479d67146e975b0 | 3ff983fd9a3ef68e586fbe5e3b538dae5702bf71 | refs/heads/master | 2023-06-16T17:57:22.140106 | 2021-07-15T15:58:17 | 2021-07-15T15:58:17 | 386,297,257 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 317 | java | package com.example.mspr;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MsprApplication {
public static void main(String[] args) {
SpringApplication.run(MsprApplication.class, args);
}
}
| [
"[email protected]"
] | |
b2483026849d2fd19663ee1e2df55f3504dfa768 | afc8f7187aa1f0503d37994141d4ad81743adb8c | /RN例子/android/app/src/main/java/com/rnexample/MainApplication.java | f2f57002b0be06708ea93204b4265333e1dc1e4d | [] | no_license | lllyyy/RNNeteaseNews | e25f94fa56cc6aef70859391459a0016ec6fedb1 | ea6fd03b05f098cb7501896c56a2e7273da31613 | refs/heads/master | 2020-03-16T00:24:35.139788 | 2018-12-19T13:07:18 | 2018-12-19T13:07:18 | 132,415,804 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,366 | java | package com.rnexample;
import android.app.Application;
import com.example.customlib.CustomPackage;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.horcrux.svg.SvgPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.microsoft.codepush.react.CodePush;
import com.puti.paylib.PayReactPackage;
import com.puti.upgrade.UpgradePackage;
import com.react.rnspinkit.RNSpinkitPackage;
import com.reactnativecomponent.barcode.RCTCapturePackage;
import com.rnexample.module.NativeConstantPackage;
import com.tencent.bugly.crashreport.CrashReport;
import com.uemnglib.DplusReactPackage;
import com.uemnglib.RNUMConfigure;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import org.devio.rn.splashscreen.SplashScreenReactPackage;
import java.util.Arrays;
import java.util.List;
import cn.jpush.reactnativejpush.JPushPackage;
import cn.reactnative.httpcache.HttpCachePackage;
public class MainApplication extends Application implements ReactApplication {
{
Config.DEBUG = BuildConfig.DEBUG;
PlatformConfig.setWeixin(BuildConfig.WX_APPKEY, BuildConfig.WX_SECRET);
PlatformConfig.setSinaWeibo(BuildConfig.SINA_APPID, BuildConfig.SINA_SECRET, "https://api.weibo.com/oauth2/default.html");
PlatformConfig.setQQZone(BuildConfig.QQ_APPID, BuildConfig.QQ_SECRET);
}
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
protected String getJSBundleFile() {
return CodePush.getJSBundleFile();
}
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new UpgradePackage(),
new PayReactPackage(),
new RCTCapturePackage(),
new CodePush(BuildConfig.CODEPUSH_KEY, getApplicationContext(), BuildConfig.DEBUG),
new SvgPackage(),
new RNDeviceInfo(),
new HttpCachePackage(),
new SplashScreenReactPackage(),
new RNSpinkitPackage(),
new CustomPackage(),
new NativeConstantPackage(),
new DplusReactPackage(),
new JPushPackage(!BuildConfig.DEBUG, !BuildConfig.DEBUG)
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
CrashReport.initCrashReport(getApplicationContext(), BuildConfig.BUGLY_ID, BuildConfig.DEBUG);
RNUMConfigure.init(getApplicationContext(), BuildConfig.UMENG_APPKEY, "android", UMConfigure.DEVICE_TYPE_PHONE, null);
UMConfigure.setLogEnabled(BuildConfig.DEBUG);
}
}
| [
"[email protected]"
] | |
156ab893caab5ac887e6fb82a9f8b5bba2b03ccd | b65fb1d11f30edb765445371dd6de37a98661cb1 | /EmployeeManagementSystem/src/loginBao/LoginBaoInt.java | cd6cb1c0c146e0aeb1dcaa2fa65eefed8ad12498 | [] | no_license | ShreyashTripathi/J2EE-Project-Employee-Management-System- | 4a94a35730a6485090ed82c72e707a3a8eb321ed | df24bc0097a0a563178f6ad72acb388d495db6bc | refs/heads/master | 2023-01-07T12:42:29.810222 | 2020-10-23T07:53:22 | 2020-10-23T07:53:22 | 295,394,431 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 368 | java | package loginBao;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import exception.BusinessException;
import model.MyTable;
import model.User;
public interface LoginBaoInt {
public void loginUser(User user,HttpServletRequest request,HttpServletResponse response,MyTable myTable) throws BusinessException;
}
| [
"[email protected]"
] | |
44057f7febaa6713cc07d4cbae143ce4ba00e6db | 033ac515e37b7902f347502a8cc4501877faa439 | /src/main/java/com/example/task1/entity/Product.java | c26f8f22f7d55a1f2845cfca5985208ac25b17f2 | [] | no_license | Ibrohimjon2151/WareHouse | 05c00823fded7fd0e6759a2165f7cfebed36bfcf | 9abd0b47c702183617ba5978fb2e14a284dc1b02 | refs/heads/master | 2023-08-01T21:42:02.993439 | 2021-10-03T08:19:54 | 2021-10-03T08:19:54 | 413,017,784 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 503 | java | package com.example.task1.entity;
import com.example.task1.entity.template.AbcNameEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
@Entity
@EqualsAndHashCode(callSuper = true)
@Data
public class Product extends AbcNameEntity {
private int code;
@OneToOne
private Measurment measurment;
@ManyToOne
Category category;
@ManyToOne
Attachment attechmant;
}
| [
"[email protected]"
] | |
d6404e16999ac4fb36d5f36fc0ec7d39f6e288ba | 5b8f51919217bb21cadb089eded30cb55e1c9f5e | /113.PathSumII/solution2.java | caef9a6c7fc895f24716a95ddc255c90c9c880d2 | [] | no_license | nora-lu/leetcode-Java | 466dffda29301608899fb4b87d5abfd6247599b1 | 70dc6b2dcf50b6903261597e050860533343d454 | refs/heads/master | 2020-04-09T16:50:55.035975 | 2016-05-27T08:48:03 | 2016-05-27T08:48:03 | 30,814,428 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,294 | java | /* Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
] */
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ret = new ArrayList<>();
if (root == null) { return ret; }
List<Integer> path = new ArrayList<>();
path.add(root.val);
pathSum(root, sum, path, ret);
return ret;
}
private void pathSum(TreeNode node, int sum, List<Integer> path, List<List<Integer>> ret) {
if (node.left == null && node.right == null && node.val == sum) {
ret.add(new ArrayList<Integer>(path));
return;
}
if (node.left != null) {
path.add(node.left.val);
pathSum(node.left, sum - node.val, path, ret);
path.remove(path.size() - 1);
}
if (node.right != null) {
path.add(node.right.val);
pathSum(node.right, sum - node.val, path, ret);
path.remove(path.size() - 1);
}
}
}
| [
"[email protected]"
] | |
aa1708fdc4c3cf25171123f060542fe3316321ba | e674163c2b925e11d5084d573ecb7cf3f273ae8a | /src/com/rackspacecloud/android/ViewServerActivity.java | 88c09d7a3ea7fd79c78c4c7df4651ba393df5f57 | [
"MIT"
] | permissive | patchorang/android-rackspacecloud | 107558ef1e92a8553923ed40218ed710c7f62715 | 9f58d76d048132480b3c7ffe04d7bb0a4ca15d1f | refs/heads/master | 2021-01-01T19:39:25.788090 | 2011-12-13T19:51:53 | 2011-12-13T19:51:53 | 1,828,410 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,750 | java | /**
*
*/
package com.rackspacecloud.android;
import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.client.BasicResponseHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.rackspace.cloud.servers.api.client.CloudServersException;
import com.rackspace.cloud.servers.api.client.Flavor;
import com.rackspace.cloud.servers.api.client.Server;
import com.rackspace.cloud.servers.api.client.ServerManager;
import com.rackspace.cloud.servers.api.client.parsers.CloudServersFaultXMLParser;
/**
* @author Mike Mayo - [email protected] - twitter.com/greenisus
*
*/
public class ViewServerActivity extends Activity {
private Server server;
private boolean ipAddressesLoaded; // to prevent polling from loading tons of duplicates
private Flavor[] flavors;
private String[] flavorNames;
private String selectedFlavorId;
private boolean imageLoaded;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
server = (Server) this.getIntent().getExtras().get("server");
setContentView(R.layout.viewserver);
restoreState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("server", server);
outState.putBoolean("imageLoaded", imageLoaded);
}
private void restoreState(Bundle state) {
if (state != null && state.containsKey("server")) {
server = (Server) state.getSerializable("server");
imageLoaded = state.getBoolean("imageLoaded");
}
loadServerData();
setupButtons();
loadFlavors();
}
private void loadImage() {
// hate to do this, but devices run out of memory after a few rotations
// because the background images are so large
if (!imageLoaded) {
ImageView osLogo = (ImageView) findViewById(R.id.view_server_os_logo);
osLogo.setAlpha(100);
osLogo.setImageResource(server.getImage().logoResourceId());
imageLoaded = true;
}
}
private void loadServerData() {
TextView name = (TextView) findViewById(R.id.view_server_name);
name.setText(server.getName());
TextView os = (TextView) findViewById(R.id.view_server_os);
os.setText(server.getImage().getName());
TextView memory = (TextView) findViewById(R.id.view_server_memory);
memory.setText(server.getFlavor().getRam() + " MB");
TextView disk = (TextView) findViewById(R.id.view_server_disk);
disk.setText(server.getFlavor().getDisk() + " GB");
TextView status = (TextView) findViewById(R.id.view_server_status);
// show status and possibly the progress, with polling
if (!"ACTIVE".equals(server.getStatus())) {
status.setText(server.getStatus() + " - " + server.getProgress() + "%");
new PollServerTask().execute((Void[]) null);
} else {
status.setText(server.getStatus());
}
if (!ipAddressesLoaded) {
// public IPs
int layoutIndex = 12; // public IPs start here
LinearLayout layout = (LinearLayout) this.findViewById(R.id.view_server_layout);
String publicIps[] = server.getPublicIpAddresses();
for (int i = 0; i < publicIps.length; i++) {
TextView tv = new TextView(this.getBaseContext());
tv.setLayoutParams(os.getLayoutParams()); // easy quick styling! :)
tv.setTypeface(tv.getTypeface(), 1); // 1 == bold
tv.setTextSize(os.getTextSize());
tv.setTextColor(Color.WHITE);
tv.setText(publicIps[i]);
layout.addView(tv, layoutIndex++);
}
// private IPs
layoutIndex++; // skip over the Private IPs label
String privateIps[] = server.getPrivateIpAddresses();
for (int i = 0; i < privateIps.length; i++) {
TextView tv = new TextView(this.getBaseContext());
tv.setLayoutParams(os.getLayoutParams()); // easy quick styling! :)
tv.setTypeface(tv.getTypeface(), 1); // 1 == bold
tv.setTextSize(os.getTextSize());
tv.setTextColor(Color.WHITE);
tv.setText(privateIps[i]);
layout.addView(tv, layoutIndex++);
}
loadImage();
ipAddressesLoaded = true;
}
}
private void loadFlavors() {
flavorNames = new String[Flavor.getFlavors().size()];
flavors = new Flavor[Flavor.getFlavors().size()];
Iterator<Flavor> iter = Flavor.getFlavors().values().iterator();
int i = 0;
while (iter.hasNext()) {
Flavor flavor = iter.next();
flavors[i] = flavor;
flavorNames[i] = flavor.getName() + ", " + flavor.getDisk() + " GB disk";
i++;
}
selectedFlavorId = flavors[0].getId();
}
private void setupButton(int resourceId, OnClickListener onClickListener) {
Button button = (Button) findViewById(resourceId);
button.setOnClickListener(onClickListener);
}
private void setupButtons() {
setupButton(R.id.view_server_soft_reboot_button, new OnClickListener() {
public void onClick(View v) {
showDialog(R.id.view_server_soft_reboot_button);
}
});
setupButton(R.id.view_server_hard_reboot_button, new OnClickListener() {
public void onClick(View v) {
showDialog(R.id.view_server_hard_reboot_button);
}
});
setupButton(R.id.view_server_resize_button, new OnClickListener() {
public void onClick(View v) {
showDialog(R.id.view_server_resize_button);
}
});
setupButton(R.id.view_server_delete_button, new OnClickListener() {
public void onClick(View v) {
showDialog(R.id.view_server_delete_button);
}
});
}
private void showAlert(String title, String message) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle(title);
alert.setMessage(message);
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
} });
alert.show();
}
/**
* @return the server
*/
public Server getServer() {
return server;
}
/**
* @param server the server to set
*/
public void setServer(Server server) {
this.server = server;
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case R.id.view_server_soft_reboot_button:
return new AlertDialog.Builder(ViewServerActivity.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle("Soft Reboot")
.setMessage("Are you sure you want to perform a soft reboot?")
.setPositiveButton("Reboot Server", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked OK so do some stuff
new SoftRebootServerTask().execute((Void[]) null);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked Cancel so do some stuff
}
})
.create();
case R.id.view_server_hard_reboot_button:
return new AlertDialog.Builder(ViewServerActivity.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle("Hard Reboot")
.setMessage("Are you sure you want to perform a hard reboot?")
.setPositiveButton("Reboot Server", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked OK so do some stuff
new HardRebootServerTask().execute((Void[]) null);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked Cancel so do some stuff
}
})
.create();
case R.id.view_server_resize_button:
return new AlertDialog.Builder(ViewServerActivity.this)
.setItems(flavorNames, new ResizeClickListener())
.setIcon(R.drawable.alert_dialog_icon)
.setTitle("Resize Server")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked Cancel so do some stuff
}
})
.create();
case R.id.view_server_delete_button:
return new AlertDialog.Builder(ViewServerActivity.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle("Delete Server")
.setMessage("Are you sure you want to delete this server? This operation cannot be undone and all backups will be deleted.")
.setPositiveButton("Delete Server", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked OK so do some stuff
new DeleteServerTask().execute((Void[]) null);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked Cancel so do some stuff
}
})
.create();
}
return null;
}
private class ResizeClickListener implements android.content.DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
selectedFlavorId = which + "";
new ResizeServerTask().execute((Void[]) null);
}
}
private CloudServersException parseCloudServersException(HttpResponse response) {
CloudServersException cse = new CloudServersException();
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
String body = responseHandler.handleResponse(response);
CloudServersFaultXMLParser parser = new CloudServersFaultXMLParser();
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(parser);
xmlReader.parse(new InputSource(new StringReader(body)));
cse = parser.getException();
} catch (ClientProtocolException e) {
cse = new CloudServersException();
cse.setMessage(e.getLocalizedMessage());
} catch (IOException e) {
cse = new CloudServersException();
cse.setMessage(e.getLocalizedMessage());
} catch (ParserConfigurationException e) {
cse = new CloudServersException();
cse.setMessage(e.getLocalizedMessage());
} catch (SAXException e) {
cse = new CloudServersException();
cse.setMessage(e.getLocalizedMessage());
} catch (FactoryConfigurationError e) {
cse = new CloudServersException();
cse.setMessage(e.getLocalizedMessage());
}
return cse;
}
// HTTP request tasks
private class PollServerTask extends AsyncTask<Void, Void, Server> {
@Override
protected Server doInBackground(Void... arg0) {
try {
server = (new ServerManager()).find(Integer.parseInt(server.getId()));
} catch (NumberFormatException e) {
// we're polling, so need to show exceptions
} catch (CloudServersException e) {
// we're polling, so need to show exceptions
}
return server;
}
@Override
protected void onPostExecute(Server result) {
server = result;
loadServerData();
}
}
private class SoftRebootServerTask extends AsyncTask<Void, Void, HttpResponse> {
private CloudServersException exception;
@Override
protected HttpResponse doInBackground(Void... arg0) {
HttpResponse resp = null;
try {
resp = (new ServerManager()).reboot(server, ServerManager.SOFT_REBOOT);
} catch (CloudServersException e) {
exception = e;
}
return resp;
}
@Override
protected void onPostExecute(HttpResponse response) {
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 202) {
CloudServersException cse = parseCloudServersException(response);
if ("".equals(cse.getMessage())) {
showAlert("Error", "There was a problem rebooting your server.");
} else {
showAlert("Error", "There was a problem rebooting your server: " + cse.getMessage());
}
}
} else if (exception != null) {
showAlert("Error", "There was a problem rebooting your server: " + exception.getMessage());
}
}
}
private class HardRebootServerTask extends AsyncTask<Void, Void, HttpResponse> {
private CloudServersException exception;
@Override
protected HttpResponse doInBackground(Void... arg0) {
HttpResponse resp = null;
try {
resp = (new ServerManager()).reboot(server, ServerManager.HARD_REBOOT);
} catch (CloudServersException e) {
exception = e;
}
return resp;
}
@Override
protected void onPostExecute(HttpResponse response) {
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 202) {
CloudServersException cse = parseCloudServersException(response);
if ("".equals(cse.getMessage())) {
showAlert("Error", "There was a problem rebooting your server.");
} else {
showAlert("Error", "There was a problem rebooting your server: " + cse.getMessage());
}
}
} else if (exception != null) {
showAlert("Error", "There was a problem rebooting your server: " + exception.getMessage());
}
}
}
private class ResizeServerTask extends AsyncTask<Void, Void, HttpResponse> {
private CloudServersException exception;
@Override
protected HttpResponse doInBackground(Void... arg0) {
HttpResponse resp = null;
try {
resp = (new ServerManager()).resize(server, Integer.parseInt(selectedFlavorId));
} catch (CloudServersException e) {
exception = e;
}
return resp;
}
@Override
protected void onPostExecute(HttpResponse response) {
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 202) {
new PollServerTask().execute((Void[]) null);
} else {
CloudServersException cse = parseCloudServersException(response);
if ("".equals(cse.getMessage())) {
showAlert("Error", "There was a problem deleting your server.");
} else {
showAlert("Error", "There was a problem deleting your server: " + cse.getMessage());
}
}
} else if (exception != null) {
showAlert("Error", "There was a problem resizing your server: " + exception.getMessage());
}
}
}
private class DeleteServerTask extends AsyncTask<Void, Void, HttpResponse> {
private CloudServersException exception;
@Override
protected HttpResponse doInBackground(Void... arg0) {
HttpResponse resp = null;
try {
resp = (new ServerManager()).delete(server);
} catch (CloudServersException e) {
exception = e;
}
return resp;
}
@Override
protected void onPostExecute(HttpResponse response) {
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 202) {
setResult(Activity.RESULT_OK);
finish();
} else {
CloudServersException cse = parseCloudServersException(response);
if ("".equals(cse.getMessage())) {
showAlert("Error", "There was a problem deleting your server.");
} else {
showAlert("Error", "There was a problem deleting your server: " + cse.getMessage());
}
}
} else if (exception != null) {
showAlert("Error", "There was a problem deleting your server: " + exception.getMessage());
}
}
}
}
| [
"[email protected]"
] | |
f83a1dbe8665eb1fce8e307c867b39657f06b560 | e553d647ce9e96e9bada404598d0bd3c7d717ea4 | /app/src/main/java/com/cy8018/iptv/player/VideoMediaPlayerGlue.java | 56959554e8dd196c9f618b75f76635e8bb063960 | [
"MIT"
] | permissive | LeslieZhang1314/IPTV.AndroidBox | 26679fd04a60132894acaa768ba347b32bb9c502 | 00a5c4134b1f4ad8675fd970da45f7db090eb70d | refs/heads/master | 2022-11-19T17:50:15.487828 | 2020-07-23T16:01:02 | 2020-07-23T16:01:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,446 | java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package com.cy8018.iptv.player;
import android.app.Activity;
import android.net.TrafficStats;
import android.os.Handler;
import androidx.leanback.media.PlaybackTransportControlGlue;
import androidx.leanback.media.PlayerAdapter;
import androidx.leanback.widget.PlaybackRowPresenter;
import androidx.leanback.widget.Presenter;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.cy8018.iptv.R;
import com.cy8018.iptv.model.Station;
import org.jetbrains.annotations.NotNull;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* PlayerGlue for video playback
* @param <T>
*/
public class VideoMediaPlayerGlue<T extends PlayerAdapter> extends PlaybackTransportControlGlue<T> {
private Station currentStation;
private String currentTime = "";
private String currentChannelId = "";
private String targetChannelId = "";
private long lastTotalRxBytes = 0;
private long lastTimeStamp = 0;
public static final int MSG_UPDATE_INFO = 0;
public static String gNetworkSpeed = "";
private static final String TAG = "VideoMediaPlayerGlue";
Activity mContext;
public void setCurrentTime (String time) { this.currentTime = time; }
public void setCurrentChannelId(String currentChannelId)
{
this.currentChannelId = currentChannelId;
}
public void setTargetChannelId(String channelId)
{
this.targetChannelId = channelId;
}
public Station getCurrentStation() {
return currentStation;
}
public String getTargetChannelId() {
return targetChannelId;
}
public void setCurrentStation(Station currentStation) {
this.currentStation = currentStation;
this.currentChannelId = String.valueOf(currentStation.index + 1);
}
public VideoMediaPlayerGlue(Activity context, T impl) {
super(context, impl);
mContext = context;
}
@Override
protected PlaybackRowPresenter onCreateRowPresenter() {
PlayControlPresenter presenter = new PlayControlPresenter();
presenter.setDescriptionPresenter(new MyDescriptionPresenter());
return presenter;
}
private long getNetSpeed() {
long nowTotalRxBytes = TrafficStats.getUidRxBytes(mContext.getApplicationContext().getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : TrafficStats.getTotalRxBytes();
long nowTimeStamp = System.currentTimeMillis();
long calculationTime = (nowTimeStamp - lastTimeStamp);
if (calculationTime == 0) {
return calculationTime;
}
long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / calculationTime);
lastTimeStamp = nowTimeStamp;
lastTotalRxBytes = nowTotalRxBytes;
return speed;
}
public String getNetSpeedText(long speed) {
String text = "";
if (speed >= 0 && speed < 1024) {
text = speed + " B/s";
} else if (speed >= 1024 && speed < (1024 * 1024)) {
text = speed / 1024 + " KB/s";
} else if (speed >= (1024 * 1024) && speed < (1024 * 1024 * 1024)) {
text = speed / (1024 * 1024) + " MB/s";
}
return text;
}
public String getCurrentTimeString()
{
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String dateNowStr = sdf.format(date);
return dateNowStr;
}
public void getNetSpeedInfo() {
gNetworkSpeed = getNetSpeedText(getNetSpeed());
Log.d(TAG, gNetworkSpeed);
}
public static boolean isContainChinese(String str) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
private class MyDescriptionPresenter extends Presenter {
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_tv_info, parent, false);
View infoBarView = view.findViewById(R.id.tv_info_bar);
View channelIdBg = view.findViewById(R.id.channel_id_bg);
//logo.setBackgroundColor(Color.DKGRAY);
infoBarView.getBackground().setAlpha(0);
channelIdBg.getBackground().setAlpha(100);
// TextView channelNameTextView = view.findViewById(R.id.channel_name);
// if (channelNameTextView.getText().length()>4)
// {
// channelNameTextView.setTextSize(60);
// }
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
VideoMediaPlayerGlue glue = (VideoMediaPlayerGlue) item;
String channelNameString = glue.getTitle().toString();
((ViewHolder)viewHolder).channelName.setText(channelNameString);
if ((channelNameString.length() > 4 && isContainChinese(channelNameString))
|| channelNameString.length() > 10
)
{
((ViewHolder)viewHolder).channelName.setTextSize(60);
}
else
{
((ViewHolder)viewHolder).channelName.setTextSize(78);
}
((ViewHolder)viewHolder).sourceInfo.setText(glue.getSubtitle());
((ViewHolder)viewHolder).currentTime.setText(currentTime);
((ViewHolder)viewHolder).channelId.setText(currentChannelId);
((ViewHolder)viewHolder).targetChannelId.setText(targetChannelId);
Glide.with(getContext())
.asBitmap()
.apply(RequestOptions.bitmapTransform(new RoundedCorners(10)))
.load(glue.getCurrentStation().logo)
.into(((ViewHolder)viewHolder).logo);
}
@Override
public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) {
}
class ViewHolder extends Presenter.ViewHolder {
TextView channelId;
TextView targetChannelId;
TextView currentTime;
TextView channelName;
TextView sourceInfo;
TextView networkSpeed;
ImageView logo;
private ViewHolder (View itemView)
{
super(itemView);
channelId = itemView.findViewById(R.id.channel_id);
targetChannelId = itemView.findViewById(R.id.target_channel_id);
currentTime = itemView.findViewById(R.id.current_time);
channelName = itemView.findViewById(R.id.channel_name);
sourceInfo = itemView.findViewById(R.id.source_info);
networkSpeed = itemView.findViewById(R.id.network_speed);
logo = itemView.findViewById(R.id.channel_logo);
new Thread(updateInfoRunnable).start();
}
public void UpdateDisplayInfo() {
networkSpeed.setText(gNetworkSpeed);
currentTime.setText(getCurrentTimeString());
targetChannelId.setText(getTargetChannelId());
}
public final MsgHandler mHandler = new MsgHandler(this);
public class MsgHandler extends Handler {
WeakReference<ViewHolder> mViewHolder;
MsgHandler(ViewHolder viewHolder) {
mViewHolder = new WeakReference<ViewHolder>(viewHolder);
}
@Override
public void handleMessage(@NotNull Message msg) {
super.handleMessage(msg);
ViewHolder vh = mViewHolder.get();
if (msg.what == MSG_UPDATE_INFO) {
getNetSpeedInfo();
vh.UpdateDisplayInfo();
}
}
}
Runnable updateInfoRunnable = new Runnable() {
@Override
public void run() {
while (true) {
try {
mHandler.sendEmptyMessage(MSG_UPDATE_INFO);
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
}
}
} | [
"[email protected]"
] | |
72dc30005f57e2b823e03a1bcd8b24943d78f996 | 319bceff7ae8f3f986952c6f44cd912a2f5f3e0f | /library/src/main/java/com/hyetec/hmdp/lifecycle/delegate/ActivityDelegateImpl.java | ba2be224f00e8fd493616230c96950db629ac458 | [] | no_license | JimHan1978/HMDP | 7dfa70b906972a3601a88e39a4c66118654f5625 | 295bac50c3f0d6d315d03afb1813efc3b929cc45 | refs/heads/master | 2020-04-16T21:43:48.758819 | 2019-02-22T09:42:44 | 2019-02-22T09:42:44 | 165,937,527 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,796 | java | package com.hyetec.hmdp.lifecycle.delegate;
import android.app.Activity;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import org.simple.eventbus.EventBus;
import javax.inject.Inject;
import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
/**
* @author xiaobailong24
* @date 2017/6/16
* Activity 生命周期代理接口实现类
*/
public class ActivityDelegateImpl implements ActivityDelegate, HasSupportFragmentInjector {
private Activity mActivity;
private IActivity iActivity;
@Inject
DispatchingAndroidInjector<Fragment> mFragmentInjector;
public ActivityDelegateImpl(Activity activity) {
this.mActivity = activity;
this.iActivity = (IActivity) activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
//如果要使用eventbus请将此方法返回true
if (iActivity.useEventBus()) {
//注册到事件主线
EventBus.getDefault().register(mActivity);
}
//Dagger.Android 依赖注入
if (iActivity.injectable()) {
AndroidInjection.inject(mActivity);
}
}
@Override
public void onStart() {
}
@Override
public void onResume() {
}
@Override
public void onPause() {
}
@Override
public void onStop() {
}
@Override
public void onSaveInstanceState(Bundle outState) {
}
@Override
public void onDestroy() {
//如果要使用eventbus请将此方法返回true
if (iActivity.useEventBus()) {
EventBus.getDefault().unregister(mActivity);
}
this.iActivity = null;
this.mActivity = null;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
protected ActivityDelegateImpl(Parcel in) {
this.mActivity = in.readParcelable(Activity.class.getClassLoader());
this.iActivity = in.readParcelable(IActivity.class.getClassLoader());
}
public static final Parcelable.Creator<ActivityDelegateImpl> CREATOR = new Parcelable.Creator<ActivityDelegateImpl>() {
@Override
public ActivityDelegateImpl createFromParcel(Parcel source) {
return new ActivityDelegateImpl(source);
}
@Override
public ActivityDelegateImpl[] newArray(int size) {
return new ActivityDelegateImpl[size];
}
};
@Override
public AndroidInjector<Fragment> supportFragmentInjector() {
return this.mFragmentInjector;
}
}
| [
"[email protected]"
] | |
36b9c1817dfba90ec429f41e33cb012a34573c76 | cc21233ae526ed74d7dfe0bc4313751bb16b18bc | /src/main/java/SimplePubSub.java | 035a93e5dcae4f9afc1c02c150dfbee4592e444e | [] | no_license | kimptoc/ibmmq-no-ssl-test | ec522b8a0c1e31a7cd519f38d40e71438eb02a93 | 696b7ec51b1dd8ae0356746626b6f20b8e5f720e | refs/heads/master | 2021-01-20T01:17:12.872304 | 2017-04-25T08:20:21 | 2017-04-25T08:20:21 | 89,248,614 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,595 | java | // SCCSID "@(#) MQMBID sn=p750-007-160812 su=_Q7L2EGB5EeavWqNpgfWvaA pn=MQJavaSamples/jms/simple/SimplePubSub.java"
/*
* <copyright
* notice="lm-source-program"
* pids="5724-H72,5655-R36,5655-L82,5724-L26,"
* years="2008,2012"
* crc="3812808746" >
* Licensed Materials - Property of IBM
*
* 5724-H72,5655-R36,5655-L82,5724-L26,
*
* (C) Copyright IBM Corp. 2008, 2012 All Rights Reserved.
*
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with
* IBM Corp.
* </copyright>
*/
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
/**
* A minimal and simple application for Publish-Subscribe messaging.
*
* Application makes use of fixed literals, any customisations will require re-compilation of this
* source file.
*
* Notes:
*
* API type: JMS API (v1.1, unified domain)
*
* Messaging domain: Publish-Subscribe
*
* Provider type: WebSphere MQ
*
* Connection mode: Client connection
*
* JNDI in use: No
*
*/
public class SimplePubSub {
// System exit status value (assume unset value to be 1)
private static int status = 1;
/**
* Main method
*
* @param args
*/
public static void main(String[] args) throws InterruptedException {
// Variables
Connection connection = null;
Session session = null;
Destination destination = null;
MessageProducer producer = null;
MessageConsumer consumer = null;
try {
// Create a connection factory
JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactory cf = ff.createConnectionFactory();
// Set the properties
cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, "ibmmq");
cf.setIntProperty(WMQConstants.WMQ_PORT, 1414);
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, "DEV.ADMIN.SVRCONN");
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, "QM1");
// cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, "SSL_RSA_WITH_AES_256_GCM_SHA384");
// cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SPEC, "TLS_RSA_WITH_AES_256_GCM_SHA384");
// Create JMS objects
connection = cf.createConnection("admin","passw0rd");
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createTopic("topic://foo");
producer = session.createProducer(destination);
consumer = session.createConsumer(destination);
long uniqueNumber = System.currentTimeMillis() % 1000;
TextMessage message = session.createTextMessage("SimplePubSub: Your lucky number today is "
+ uniqueNumber);
// Start the connection
connection.start();
// And, send the message
producer.send(message);
System.out.println("Sent message:\n" + message);
Thread.sleep(30000);
Message receivedMessage = consumer.receive(1500000); // in ms or 15 seconds
System.out.println("\nReceived message:\n" + receivedMessage);
recordSuccess();
}
catch (JMSException jmsex) {
recordFailure(jmsex);
}
finally {
if (producer != null) {
try {
producer.close();
}
catch (JMSException jmsex) {
System.out.println("Producer could not be closed.");
recordFailure(jmsex);
}
}
if (consumer != null) {
try {
consumer.close();
}
catch (JMSException jmsex) {
System.out.println("Consumer could not be closed.");
recordFailure(jmsex);
}
}
if (session != null) {
try {
session.close();
}
catch (JMSException jmsex) {
System.out.println("Session could not be closed.");
recordFailure(jmsex);
}
}
if (connection != null) {
try {
connection.close();
}
catch (JMSException jmsex) {
System.out.println("Connection could not be closed.");
recordFailure(jmsex);
}
}
}
System.exit(status);
return;
} // end main()
/**
* Process a JMSException and any associated inner exceptions.
*
* @param jmsex
*/
private static void processJMSException(JMSException jmsex) {
System.out.println(jmsex);
Throwable innerException = jmsex.getLinkedException();
if (innerException != null) {
System.out.println("Inner exception(s):");
}
while (innerException != null) {
System.out.println(innerException);
innerException = innerException.getCause();
}
return;
}
/**
* Record this run as successful.
*/
private static void recordSuccess() {
System.out.println("SUCCESS");
status = 0;
return;
}
/**
* Record this run as failure.
*
* @param ex
*/
private static void recordFailure(Exception ex) {
if (ex != null) {
if (ex instanceof JMSException) {
processJMSException((JMSException) ex);
}
else {
System.out.println(ex);
}
}
System.out.println("FAILURE");
status = -1;
return;
}
}
| [
"[email protected]"
] | |
ef7e1c6d24297fa8d6c3a9b6e77959c91f5a86ef | 1b4c3ec7953f6d1aea55c7a400d8fd08f17d6a8b | /src/main/java/com/example/mapper/base2/BusiAccountMapper.java | 81e61df76e5523be1c588fce1cca2cc992b2320b | [] | no_license | 82253452/bestMVC | d9dd07294501ed5a21c1f936a3f254e695bad4fc | 3d3169897647f6f7b235a33998af8037571e7496 | refs/heads/master | 2020-03-25T10:48:56.480524 | 2018-08-06T11:48:10 | 2018-08-06T11:48:10 | 143,706,500 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 181 | java | package com.example.mapper.base2;
import com.example.entity.BusiAccount;
import tk.mybatis.mapper.common.Mapper;
public interface BusiAccountMapper extends Mapper<BusiAccount> {
} | [
"[email protected]"
] | |
680a7440a40e73362230cf5190d93519dc85ed6c | e315c2bb2ea17cd8388a39aa0587e47cb417af0a | /backoffice/tn/com/smartsoft/backoffice/referentiel/saison/presentation/model/SaisonsModel.java | 1fe5f1aff9e9f4ee6a5b9ef33dc998ce66a96a48 | [] | no_license | wissem007/badges | 000536a40e34e20592fe6e4cb2684d93604c44c9 | 2064bd07b52141cf3cff0892e628cc62b4f94fdc | refs/heads/master | 2020-12-26T14:06:11.693609 | 2020-01-31T23:40:07 | 2020-01-31T23:40:07 | 237,530,008 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 277 | java | package tn.com.smartsoft.backoffice.referentiel.saison.presentation.model;
import tn.com.smartsoft.framework.presentation.model.GenericEntiteModel;
public class SaisonsModel extends GenericEntiteModel {
/**
*
*/
private static final long serialVersionUID = 1L;
}
| [
"[email protected]"
] | |
f98820b2bff5dc545383f9f4b782737bae10fcc9 | 1f679719b629bd9f04b00de7f4fe2ad6502e0dfa | /src/main/java/com/shnupbups/redstonebits/block/AdvancedRedstoneConnector.java | 349896e20e1da22d18c17481bd3a5f7ab46af714 | [] | no_license | piisawheel/redstone-bits | 79ec0dda3ba9822fe443a6564603d58981b19b2a | d98ea7fbf0e2d453f44253387455ca1fab9fcf02 | refs/heads/master | 2023-02-12T01:41:17.490568 | 2021-01-14T08:48:02 | 2021-01-14T08:48:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 312 | java | package com.shnupbups.redstonebits.block;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
public interface AdvancedRedstoneConnector {
default boolean connectsToRedstoneInDirection(BlockState state, Direction direction) {
return true;
}
}
| [
"[email protected]"
] | |
2d98341212929e75a20279038876005b8d21ce92 | 013b3febb1233983da0f9424037683cd011990bb | /Opdrachten AP/src/Opd15/Car.java | fba5255f6e47605b1a13f91cda1c2bb437c67c9b | [] | no_license | vlreinier/AP | c7df54b6937b8d4b406a14a3c7d63f033a4bc83f | faab2eaed9ed10f541a922f3590e610a49b67305 | refs/heads/master | 2022-02-01T16:24:02.484699 | 2019-07-03T18:23:22 | 2019-07-03T18:23:22 | 195,106,817 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 409 | java | package Opd15;
public class Car {
private String type;
private double priceperday;
public Car(String type, double priceperday){
this.type = type;
this.priceperday = priceperday;
}
public String getType() {
return type;
}
public double getPriceperday() {
return priceperday;
}
public String toString(){
return this.type;
}
}
| [
"[email protected]"
] | |
ca649e982fb818cb790d5e338b3d193558c76526 | 3eba7f9d133a325313d2a83795248acfb1f5e01f | /src/main/java/xdata/Overlap.java | ab42642dc06e9d21957e02c1c1af06dbd0a95acf | [] | no_license | schaban/AndroidEnvLighting | fe058ec61f604fe4def9771dd4cc7f089b6e87a7 | d9d6750be2c4f6814fbbbd1c421015e1624ce5c6 | refs/heads/master | 2020-03-21T11:11:59.025980 | 2019-03-19T11:54:18 | 2019-03-19T11:54:18 | 138,493,843 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,122 | java | // Author: Sergey Chaban <[email protected]>
package xdata;
public final class Overlap {
public static boolean spheres(float[] cA, float rA, float[] cB, float rB) {
float cds = Calc.distSq(cA, cB);
float rs = rA + rB;
return cds <= Calc.sq(rs);
}
public static boolean spheres(float[] a, float[] b) {
float ra = a.length < 4 ? 0.0f : a[3];
float rb = b.length < 4 ? 0.0f : b[3];
return spheres(a, ra, b, rb);
}
public static boolean boxes(float[] minmaxA, float[] minmaxB) {
for (int i = 0; i < 3; ++i) {
/* minA > maxB */
if (minmaxA[i] > minmaxB[3 + i]) return false;
}
for (int i = 0; i < 3; ++i) {
/* maxA < minB */
if (minmaxA[3 + i] < minmaxB[i]) return false;
}
return true;
}
public static boolean boxes(float[] minmaxA, int offsA, float[] minmaxB, int offsB) {
for (int i = 0; i < 3; ++i) {
/* minA > maxB */
if (minmaxA[offsA + i] > minmaxB[offsB + 3 + i]) return false;
}
for (int i = 0; i < 3; ++i) {
/* maxA < minB */
if (minmaxA[offsA + 3 + i] < minmaxB[offsB + i]) return false;
}
return true;
}
public static boolean sphereBox(float[] sphC, float sphR, float[] minmax) {
float[] pos = new float[3];
Calc.vclamp(pos, sphC, minmax);
float ds = Calc.distSq(pos, sphC);
return ds <= Calc.sq(sphR);
}
public static boolean sphereBox(float[] sph, float[] minmax) {
float r = 0.0f;
if (sph.length >= 4) {
r = sph[3];
}
return sphereBox(sph, r, minmax);
}
public static boolean pointSphere(float[] pos, float[] c, float r) {
float ds = Calc.distSq(pos, c);
float rs = Calc.sq(r);
return ds <= rs;
}
public static boolean pointSphere(float[] pos, float[] sph) {
float r = sph.length < 4 ? 0.0f : sph[3];
return pointSphere(pos, sph, r);
}
public static boolean pointBox(float x, float y, float z, float[] minmax, int offs) {
if (x < minmax[offs + 0] || x > minmax[offs + 3 + 0]) return false;
if (y < minmax[offs + 1] || y > minmax[offs + 3 + 1]) return false;
if (z < minmax[offs + 2] || z > minmax[offs + 3 + 2]) return false;
return true;
}
public static boolean segmentBox(
float p0x, float p0y, float p0z,
float p1x, float p1y, float p1z,
float[] minmax, int offs
) {
float dirx = p1x - p0x;
float diry = p1y - p0y;
float dirz = p1z - p0z;
float len = Calc.vecLen(dirx, diry, dirz);
if (len < 1.0e-7f) {
return pointBox(p0x, p0y, p0z, minmax, offs);
}
float tmin = 0.0f;
float tmax = len;
float bbminx = minmax[offs];
float bbmaxx = minmax[offs + 3];
if (dirx != 0) {
float dx = len / dirx;
float x1 = (bbminx - p0x) * dx;
float x2 = (bbmaxx - p0x) * dx;
float xmin = Math.min(x1, x2);
float xmax = Math.max(x1, x2);
tmin = Math.max(tmin, xmin);
tmax = Math.min(tmax, xmax);
if (tmin > tmax) {
return false;
}
} else {
if (p0x < bbminx || p0x > bbmaxx) return false;
}
float bbminy = minmax[offs + 1];
float bbmaxy = minmax[offs + 3 + 1];
if (diry != 0) {
float dy = len / diry;
float y1 = (bbminy - p0y) * dy;
float y2 = (bbmaxy - p0y) * dy;
float ymin = Math.min(y1, y2);
float ymax = Math.max(y1, y2);
tmin = Math.max(tmin, ymin);
tmax = Math.min(tmax, ymax);
if (tmin > tmax) {
return false;
}
} else {
if (p0y < bbminy || p0y > bbmaxy) return false;
}
float bbminz = minmax[offs + 2];
float bbmaxz = minmax[offs + 3 + 2];
if (dirz != 0) {
float dz = len / dirz;
float z1 = (bbminz - p0z) * dz;
float z2 = (bbmaxz - p0z) * dz;
float zmin = Math.min(z1, z2);
float zmax = Math.max(z1, z2);
tmin = Math.max(tmin, zmin);
tmax = Math.min(tmax, zmax);
if (tmin > tmax) {
return false;
}
} else {
if (p0z < bbminz || p0z > bbmaxz) return false;
}
if (tmax > len) return false;
return true;
}
public static boolean segmentBox(Vec p0, Vec p1, float[] minmax, int offs) {
return segmentBox(p0.x(), p0.y(), p0.z(), p1.x(), p1.y(), p1.z(), minmax, offs);
}
}
| [
"[email protected]"
] | |
ec324c28c1d94cb635ae43f45d0cced5977a1210 | c357a9c2748010f4c525929ccc2e4c8b5532ce3f | /jenkins/core/src/main/java/jenkins/model/Jenkins.java | 9be495e00105716761128c3763b5fefa3baa0f26 | [
"MIT"
] | permissive | jbbr245/mp3 | c9dfec24abe360906ded37ee6911e380179bd110 | 1db95a68c9a888092ecd7be6da120161780683d2 | refs/heads/master | 2023-01-05T11:29:52.236583 | 2020-10-31T00:35:26 | 2020-10-31T00:35:26 | 308,404,137 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 149,212 | java | /*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* 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 jenkins.model;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.LocalPluginManager;
import hudson.Lookup;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.init.InitMilestone;
import hudson.init.InitStrategy;
import hudson.init.TerminatorFinder;
import hudson.lifecycle.Lifecycle;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.logging.LogRecorderManager;
import hudson.markup.EscapedMarkupFormatter;
import hudson.markup.MarkupFormatter;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.LoadStatistics;
import hudson.model.ManagementLink;
import hudson.model.Messages;
import hudson.model.ModifiableViewGroup;
import hudson.model.NoFingerprintMatch;
import hudson.model.Node;
import hudson.model.OverallLoadStatistics;
import hudson.model.PaneStatusProperties;
import hudson.model.Project;
import hudson.model.Queue;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.WorkspaceCleanupThread;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.remoting.Callable;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.BasicAuthenticationFilter;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.EphemeralNode;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.IOUtils;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.NamingThreadFactory;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.security.SecurityListener;
import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.Timer;
import jenkins.util.io.FileBoolean;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static hudson.Util.*;
import static hudson.init.InitMilestone.*;
import hudson.util.LogTaskListener;
import static java.util.logging.Level.*;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback,
ModifiableViewGroup, AccessControlled, DescriptorByNameOwner,
ModelObjectWithContextMenu, ModelObjectWithChildren {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Jenkins whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Jenkins.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Jenkins.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* Disables the remember me on this computer option in the standard login screen.
*
* @since 1.534
*/
private volatile boolean disableRememberMe;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean();
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Jenkins system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
private void updateAndTrim() {
updateComputerList();
trimLabels();
}
/**
* Legacy store of the set of installed cluster nodes.
* @deprecated in favour of {@link Nodes}
*/
@Deprecated
protected transient volatile NodeList slaves;
/**
* The holder of the set of installed cluster nodes.
*
* @since 1.607
*/
private transient final Nodes nodes = new Nodes(this);
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and slaves.
*
* This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* slaves and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Jenkins.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
@CheckForNull Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public @CheckForNull Jenkins getInstance() {
return theInstance;
}
};
/**
* Gets the {@link Jenkins} singleton.
* {@link #getInstance()} provides the unchecked versions of the method.
* @return {@link Jenkins} instance
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
* @since 1.590
*/
public static @Nonnull Jenkins getActiveInstance() throws IllegalStateException {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
return instance;
}
/**
* Gets the {@link Jenkins} singleton.
* {@link #getActiveInstance()} provides the checked versions of the method.
* @return The instance. Null if the {@link Jenkins} instance has not been started,
* or was already shut down
*/
@CLIResolver
@CheckForNull
public static Jenkins getInstance() {
return HOLDER.getInstance();
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root,context,null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with slaves
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new java.util.Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = new LocalPluginManager(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
if(slaveAgentPort!=-1) {
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} catch (BindException e) {
new AdministrativeError(getClass().getName()+".tcpBind",
"Failed to listen to incoming slave connection",
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
}
} else
tcpSlaveAgentListener = null;
if (UDPBroadcastThread.PORT != -1) {
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e);
}
}
dnsMultiCast = new DNSMultiCast(this);
Timer.get().scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS);
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c, new LogTaskListener(LOGGER, INFO));
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
try {
l.onLoaded();
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, null, x);
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
@Deprecated
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
@Deprecated
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName,SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
@Deprecated
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Jenkins by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName,SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/** @deprecated Use {@link SCMListener#all} instead. */
@Deprecated
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public @Nonnull MarkupFormatter getMarkupFormatter() {
MarkupFormatter f = markupFormatter;
return f != null ? f : new EscapedMarkupFormatter();
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Jenkins.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
return new ArrayList(items.values());
}
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
return Items.getAllItems(this, type);
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(),Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view,oldName,newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Jenkins.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Jenkins forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
@Override public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return lhs.getName().compareTo(rhs.getName());
}
});
return r;
}
@CLIResolver
public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public List<JDK> getJDKs() {
if(jdks==null)
jdks = new ArrayList<JDK>();
return jdks;
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the slave node of the give name, hooked under this Jenkins.
*/
public @CheckForNull Node getNode(String name) {
return nodes.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return nodes.getNodes();
}
/**
* Adds one more {@link Node} to Jenkins.
*/
public void addNode(Node n) throws IOException {
nodes.addNode(n);
}
/**
* Removes a {@link Node} from Jenkins.
*/
public void removeNode(@Nonnull Node n) throws IOException {
nodes.removeNode(n);
}
public void setNodes(final List<? extends Node> n) throws IOException {
nodes.setNodes(n);
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
/*package*/ void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
public String getDisplayName() {
return "";
}
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
// do essentially what expandVariablesForDirectory does, without an Item
String replacedValue = expandVariablesForDirectory(value,
"doCheckRawBuildsDir-Marker:foo",
Jenkins.getInstance().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo");
File replacedFile = new File(replacedValue);
if (!replacedFile.isAbsolute()) {
return FormValidation.error(value + " does not resolve to an absolute path");
}
if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) {
return FormValidation.error(value + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects");
}
if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) {
// make sure platform can handle colon
try {
File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar");
tmp.delete();
} catch (IOException e) {
return FormValidation.error(value + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead");
}
}
File d = new File(replacedValue);
if (!d.isDirectory()) {
// if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to
d = d.getParentFile();
while (!d.exists()) {
d = d.getParentFile();
}
if (!d.canWrite()) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
}
return FormValidation.ok();
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); }
protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return views; }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}.
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link #getRootUrlFromRequest}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return null if this parameter is not configured by the user and the calling thread is not in an HTTP request; otherwise the returned URL will always have the trailing {@code /}
* @since 1.66
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public @Nullable String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}.
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* <p>Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy which has not been fully configured.
* Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set.
* <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a>
* shows some examples of configuration.
* @since 1.263
*/
public @Nonnull String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread");
}
StringBuilder buf = new StringBuilder();
String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme());
buf.append(scheme).append("://");
String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName());
int index = host.indexOf(':');
int port = req.getServerPort();
if (index == -1) {
// Almost everyone else except Nginx put the host and port in separate headers
buf.append(host);
} else {
// Nginx uses the same spec as for the Host header, i.e. hostanme:port
buf.append(host.substring(0, index));
if (index + 1 < host.length()) {
try {
port = Integer.parseInt(host.substring(index + 1));
} catch (NumberFormatException e) {
// ignore
}
}
// but if a user has configured Nginx with an X-Forwarded-Port, that will win out.
}
String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null);
if (forwardedPort != null) {
try {
port = Integer.parseInt(forwardedPort);
} catch (NumberFormatException e) {
// ignore
}
}
if (port != ("https".equals(scheme) ? 443 : 80)) {
buf.append(':').append(port);
}
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
/**
* Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
* header is the first header. If the originating header contains a comma separated list, the originating entry
* is the first one.
* @param req the request
* @param header the header name
* @param defaultValue the value to return if the header is absent.
* @return the originating entry of the header or the default value if the header was not present.
*/
private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath()));
}
@Restricted(NoExternalUse.class)
static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) {
return Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath(),
"ITEM_ROOTDIR", itemRootDir,
"ITEM_FULLNAME", itemFullName, // legacy, deprecated
"ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
@Restricted(NoExternalUse.class)
public void setRawBuildsDir(String buildsDir) {
this.buildsDir = buildsDir;
}
@Override public @Nonnull FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
@Override
public Callable<ClockDifference, IOException> getClockDifferenceCallable() {
return new MasterToSlaveCallable<ClockDifference, IOException>() {
public ClockDifference call() throws IOException {
return new ClockDifference(0);
}
};
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Jenkins would have to have crumb in it to protect
* Jenkins from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes in Jenkins.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
IdStrategy oldUserIdStrategy = this.securityRealm == null
? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load
: this.securityRealm.getUserIdStrategy();
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) {
User.rekey();
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public boolean isDisableRememberMe() {
return disableRememberMe;
}
public void setDisableRememberMe(boolean disableRememberMe) {
this.disableRememberMe = disableRememberMe;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.433
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
* @see ExtensionList#lookup
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Jenkins is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
if (this.numExecutors != n) {
this.numExecutors = n;
updateComputerList();
save();
}
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
@Override public TopLevelItem getItem(String name) throws AccessDeniedException {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
* <p>For compatibility, as a fallback when nothing else matches, a simple path
* like {@code foo/bar} can also be treated with {@link #getItemByFullName}.
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
* @throws AccessDeniedException as per {@link ItemGroup#getItem}
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) throws AccessDeniedException {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // TODO consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name, if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
* @see User#get(String,boolean)
*/
public @CheckForNull User getUser(String name) {
return User.get(name,hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Jenkins by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(job, oldName, newName);
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
ItemListener.fireOnDeleted(item);
items.remove(item.getName());
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
}
@Override public boolean canAdd(TopLevelItem item) {
return true;
}
@Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException {
if (items.containsKey(name)) {
throw new IllegalArgumentException("already an item '" + name + "'");
}
items.put(name, item);
return item;
}
@Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException {
items.remove(item.getName());
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles();
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
// if we are loading old data that doesn't have this field
if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) {
nodes.setNodes(slaves);
slaves = null;
} else {
nodes.load();
}
clouds.setOwner(Jenkins.this);
}
});
for (final File subdir : subdirs) {
g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
if(!Items.getConfigFile(subdir).exists()) {
//Does not have job config file, so it is not a jenkins job hence skip it
return;
}
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : nodes.getNodes())
// Note that not all labels are visible until the slaves have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Jenkins and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
if (useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
} else {
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
for (ItemListener l : ItemListener.all())
l.onBeforeShutdown();
try {
final TerminatorFinder tf = new TerminatorFinder(
pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader());
new Reactor(tf).execute(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
} catch (InterruptedException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
e.printStackTrace();
} catch (ReactorException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
}
Set<Future<?>> pending = new HashSet<Future<?>>();
terminating = true;
for( Computer c : computers.values() ) {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
}
if(udpBroadcastThread!=null)
udpBroadcastThread.shutdown();
if(dnsMultiCast!=null)
dnsMultiCast.close();
interruptReloadThread();
java.util.Timer timer = Trigger.timer;
if (timer != null) {
timer.cancel();
}
// TODO: how to wait for the completion of the last job?
Trigger.timer = null;
Timer.shutdown();
if(tcpSlaveAgentListener!=null)
tcpSlaveAgentListener.shutdown();
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
pluginManager.stop();
if(getRootDir().exists())
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
getQueue().save();
threadPoolForLoad.shutdown();
for (Future<?> f : pending)
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
}
LogFactory.releaseAll();
theInstance = null;
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if(a.getUrlName().equals(token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
jdks.clear();
jdks.addAll(req.bindJSONToList(JDK.class,json.get("jdks")));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
@RequirePOST
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
updateComputerList();
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
@RequirePOST
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
@RequirePOST // TODO does not seem to work on _either_ overload!
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
@RequirePOST
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
long waitUntil = timeout;
if (timeout > 0) waitUntil += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < waitUntil)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
@RequirePOST // TODO the cancel link needs to be updated accordingly
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
public HttpResponse doToggleCollapse() throws ServletException, IOException {
final StaplerRequest request = Stapler.getCurrentRequest();
final String paneId = request.getParameter("paneId");
PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId);
return HttpResponses.forwardToPreviousPage();
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all slaves (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang slaves.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return Collections.unmodifiableSortedMap(new TreeMap<String, Map<String, String>>(r));
}
@RequirePOST
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
@RequirePOST
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if(".".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName("."));
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
/**
* Makes sure that the given name is good as a job name.
* @return trimmed name if valid; throws Failure if not
*/
private String checkJobName(String name) throws Failure {
checkGoodName(name);
name = name.trim();
projectNamingStrategy.checkName(name);
if(getItem(name)!=null)
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
// looks good
return name;
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active)
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
* Used only by {@link LegacySecurityRealm}.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
// TODO fire something in SecurityListener?
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String user = getAuthentication().getName();
securityRealm.doLogout(req, rsp);
SecurityListener.fireLoggedOut(user);
}
/**
* Serves jar files for JNLP slave agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@CLIMethod(name="reload-configuration")
@RequirePOST
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
new JenkinsReloadFailed(e).publish(servletContext,root);
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
executeReactor(null, loadTasks());
User.reload();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
@RequirePOST
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
* @since 1.467
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getViewUrl(),view.getDisplayName());
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,FilePath.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
@RequirePOST
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Jenkins, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Jenkins for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
@Extension @Restricted(NoExternalUse.class)
public static class MasterRestartNotifyier extends RestartListener {
@Override
public void onRestart() {
Computer computer = Jenkins.getInstance().toComputer();
if (computer == null) return;
RestartCause cause = new RestartCause();
for (ComputerListener listener: ComputerListener.all()) {
listener.onOffline(computer, cause);
}
}
@Override
public boolean isReadyToRestart() throws IOException, InterruptedException {
return true;
}
private static class RestartCause extends OfflineCause.SimpleOfflineCause {
protected RestartCause() {
super(Messages._Jenkins_IsRestarting());
}
}
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
@RequirePOST
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
@RequirePOST
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static @Nonnull Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL());
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL());
}
/**
* @since 1.509.1
*/
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
acl.checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
if (!"POST".equals(req.getMethod())) {
throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
}
if (channel == null) {
throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline");
}
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, channel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(RUN_SCRIPTS);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if (getSecurityRealm().allowsSignup()) {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
return;
}
req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null)
throw new ServletException();
Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs));
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
@RequirePOST
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
@RequirePOST
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!value.equals(JDK.DEFAULT_NAME))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Makes sure that the given name is good as a job name.
*/
public FormValidation doCheckJobName(@QueryParameter String value) {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
checkPermission(Item.CREATE);
if(fixEmpty(value)==null)
return FormValidation.ok();
try {
checkJobName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Checks if a top-level view with the given name exists and
* make sure that the name is good as a view name.
*/
public FormValidation doCheckViewName(@QueryParameter String value) {
checkPermission(View.CREATE);
String name = fixEmpty(value);
if (name == null)
return FormValidation.ok();
// already exists?
if (getView(name) != null)
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name));
// good view name?
try {
checkGoodName(name);
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
return FormValidation.ok();
}
/**
* Checks if a top-level view with the given name exists.
* @deprecated 1.512
*/
@Deprecated
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
dependencyGraphDirty.set(false);
}
/**
* Rebuilds the dependency map asynchronously.
*
* <p>
* This would keep the UI thread more responsive and helps avoid the deadlocks,
* as dependency graph recomputation tends to touch a lot of other things.
*
* @since 1.522
*/
public Future<DependencyGraph> rebuildDependencyGraphAsync() {
dependencyGraphDirty.set(true);
return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() {
@Override
public DependencyGraph call() throws Exception {
if (dependencyGraphDirty.get()) {
rebuildDependencyGraph();
}
return dependencyGraph;
}
}, 500, TimeUnit.MILLISECONDS);
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
if(rest.startsWith("/login")
|| rest.startsWith("/logout")
|| rest.startsWith("/accessDenied")
|| rest.startsWith("/adjuncts/")
|| rest.startsWith("/error")
|| rest.startsWith("/oops")
|| rest.startsWith("/signup")
|| rest.startsWith("/tcpSlaveAgentListener")
// TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
|| rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))
|| rest.startsWith("/federatedLoginService/")
|| rest.startsWith("/securityRealm"))
return this; // URLs that are always visible without READ permission
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA
// TODO consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
names.add(a.getUrlName());
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Will always keep this guy alive so that it can function as a fallback to
* execute {@link FlyweightTask}s. See JENKINS-7291.
*/
@Override
protected boolean isAlive() {
return true;
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return FilePath.localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
@RequirePOST
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*
* @deprecated as of 1.558
* Use {@link FilePath#localChannel}
*/
@Deprecated
public static final LocalChannel localChannel = FilePath.localChannel;
}
/**
* Shortcut for {@code Jenkins.getInstance().lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstance();
return j != null ? j.lookup.get(type) : null;
}
/**
* Live view of recent {@link LogRecord}s produced by Jenkins.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM;
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load"));
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
InputStream is = null;
try {
is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
} finally {
IOUtils.closeQuietly(is);
}
String ver = props.getProperty("version");
if(ver==null) ver="?";
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* Version number of this Jenkins.
*/
public static String VERSION="?";
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
*/
public static VersionNumber getVersion() {
try {
return new VersionNumber(VERSION);
} catch (NumberFormatException e) {
try {
// for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate.
int idx = VERSION.indexOf(' ');
if (idx>0)
return new VersionNumber(VERSION.substring(0,idx));
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* @deprecated No longer used.
*/
@Deprecated
public static boolean FLYWEIGHT_SUPPORT = true;
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch a slave when Jenkins is initialized or a new slave is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS;
static {
try {
ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
XSTREAM = XSTREAM2 = new XStream2();
XSTREAM.alias("jenkins", Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk", JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
XSTREAM2.addCriticalField(Jenkins.class, "securityRealm");
XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy");
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS != null;
assert ADMINISTER != null;
} catch (RuntimeException e) {
// when loaded on a slave and this fails, subsequent NoClassDefFoundError will fail to chain the cause.
// see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847
// As we don't know where the first exception will go, let's also send this to logging so that
// we have a known place to look at.
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
} catch (Error e) {
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
}
}
}
| [
"[email protected]"
] | |
74aa5e4b9f3e9f19f1b21442aec8daf8d2ed1259 | 9c39465a935c4a55a17d825de7604e9527d09988 | /src/main/java/ai/wealth/boot/initiator/controller/PrimaryController.java | c15232a4de89f85d1858a7fb42b6af78e428473b | [] | no_license | xorasysgen/initiator-api | 88329ddcf0ab807b2e850a9e75a38506aadadcde | e7bcad9647c61938ab427f8e700526d3f476503e | refs/heads/master | 2020-06-29T00:46:00.709629 | 2019-11-14T11:31:12 | 2019-11-14T11:31:12 | 200,389,089 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,392 | java | package ai.wealth.boot.initiator.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import ai.wealth.boot.initiator.dto.ServerStatus;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/api")
public class PrimaryController {
//https://api.wealthkernel.com/swagger/v2/index.html
@ResponseBody
@ApiOperation(value = "Get Server information", notes="no addition parameters required", response=ServerStatus.class)
@GetMapping("/info")
public ServerStatus root() {
return new ServerStatus();
}
@ResponseBody
@ApiOperation(value = "say hi", notes="addition parameters required", response=String.class)
@GetMapping("/{name}")
@HystrixCommand(fallbackMethod = "fallbackMethodFailure")
public String hi(@PathVariable("name") String name) {
if(name!=null && !name.equals("name"))
return "Hello " + name;
else
throw new RuntimeException("Name should not be null");
}
public String fallbackMethodFailure(@PathVariable("name") String name) {
return "Home failue due to Name should not be null";
}
}
| [
"[email protected]"
] | |
66a4c570d5b4ec463329a7b987d8c491f21f1c30 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/8/8_5fc9d09e386a298265876b8a331f735c5b47333b/HashingUtils/8_5fc9d09e386a298265876b8a331f735c5b47333b_HashingUtils_t.java | ad07b92eae26ce71b84596c9df9e917244cce8b7 | [] | 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 | 3,101 | java | /*
Copyright 2011 Monits
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.monits.commons;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Hashing utilities.
*
* @author Franco Zeoli <[email protected]>
* @copyright 2011 Monits
* @license Apache 2.0 License
* @version Release: 1.0.0
* @link http://www.monits.com/
* @since 1.0.0
*/
public class HashingUtils {
/**
* Retrieves the file hashed by the given hashing algorithm.
* @param filename The path to the file to hash.
* @param algorithm Which hashing algorithm to use.
* @return The resulting hash
* @throws FileNotFoundException
*/
public static String getFileHash(String filename, HashingAlgorithm algorithm) throws FileNotFoundException {
return getHash(new FileInputStream(filename), algorithm);
}
/**
* Retrieves the given input string hashed with the given hashing algorithm.
* @param input The string to hash.
* @param algorithm Which hashing algorithm to use.
* @return The resulting hash
*/
public static String getHash(String input, HashingAlgorithm algorithm) {
return getHash(new ByteArrayInputStream(input.getBytes()), algorithm);
}
/**
* Retrieves the given input string hashed with the given hashing algorithm.
* @param input The source from which to read the input to hash.
* @param algorithm Which hashing algorithm to use.
* @return The resulting hash
*/
public static String getHash(InputStream input, HashingAlgorithm algorithm) {
byte[] buffer = new byte[1024];
try {
MessageDigest algo = MessageDigest.getInstance(algorithm.getName());
int readBytes;
do {
readBytes = input.read(buffer);
algo.update(buffer, 0, readBytes);
} while (readBytes == buffer.length);
byte messageDigest[] = algo.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String token = Integer.toHexString(0xFF & messageDigest[i]);
// Make sure each is exactly 2 chars long
if (token.length() < 2) {
hexString.append("0");
}
hexString.append(token);
}
return hexString.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
| [
"[email protected]"
] | |
3aee48672b5807ee47c1e496f97ab114ee7233e6 | 1ecfedc980ac8c052bd4ce1e7f9edb5764b2fede | /appHotelito/src/main/java/com/hotelito/model/Habitacion.java | dd991d03b6551215631579bbc055584275647c71 | [] | no_license | ramirezdchris/appHotelitoService | d4fa7782773fbfeb584393dfd5f527f53e615014 | ad380b964806906965a31f474d9547ac001c0c8c | refs/heads/master | 2022-12-30T07:51:23.871663 | 2020-10-19T00:12:24 | 2020-10-19T00:12:24 | 296,516,612 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,278 | java | package com.hotelito.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name = "habitacion")
@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public class Habitacion implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_habitacion")
private int idHabitacion;
@Column(name = "nombre_habitacion")
private String nombreHabitacion;
@Column(name ="estado")
private int estadoHabitacion;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name ="tipo_habitacion")
private TipoHabitacion tipoHabitacion;
public Habitacion() {
super();
}
public Habitacion(int idHabitacion, String nombreHabitacion, int estadoHabitacion,
TipoHabitacion tipoHabitacion) {
super();
this.idHabitacion = idHabitacion;
this.nombreHabitacion = nombreHabitacion;
this.estadoHabitacion = estadoHabitacion;
this.tipoHabitacion = tipoHabitacion;
}
public int getIdHabitacion() {
return idHabitacion;
}
public void setIdHabitacion(int idHabitacion) {
this.idHabitacion = idHabitacion;
}
public String getNombreHabitacion() {
return nombreHabitacion;
}
public void setNombreHabitacion(String nombreHabitacion) {
this.nombreHabitacion = nombreHabitacion;
}
public int getEstadoHabitacion() {
return estadoHabitacion;
}
public void setEstadoHabitacion(int estadoHabitacion) {
this.estadoHabitacion = estadoHabitacion;
}
public TipoHabitacion getTipoHabitacion() {
return tipoHabitacion;
}
public void setTipoHabitacion(TipoHabitacion tipoHabitacion) {
this.tipoHabitacion = tipoHabitacion;
}
@Override
public String toString() {
return "Habitacion [idHabitacion=" + idHabitacion + ", nombreHabitacion=" + nombreHabitacion
+ ", estadoHabitacion=" + estadoHabitacion + ", tipoHabitacion=" + tipoHabitacion + "]";
}
}
| [
"[email protected]"
] | |
480b9f7cd472ac2ad2b857278c0e8a4d3d2d35eb | c314325a88074867d1058c78d69f9ca50156d0bb | /src/com/jeecms/cms/entity/assist/CmsGuestbook.java | 5f921e2e5e43d34203aadc8ee139d77361372526 | [] | no_license | zhaoshunxin/jeecmsv8 | 88bd5995c87475f568544bb131280550bf323714 | 0df764a90f4dcf54e9b23854e988b8a78a7d0bda | refs/heads/master | 2020-03-27T22:18:42.905602 | 2017-03-29T16:14:44 | 2017-03-29T16:14:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,343 | java | package com.jeecms.cms.entity.assist;
import java.sql.Timestamp;
import org.json.JSONException;
import org.json.JSONObject;
import com.jeecms.cms.entity.assist.base.BaseCmsGuestbook;
import com.jeecms.common.util.DateUtils;
import com.jeecms.common.util.StrUtils;
public class CmsGuestbook extends BaseCmsGuestbook {
private static final long serialVersionUID = 1L;
public String getTitleHtml() {
return StrUtils.txt2htm(getTitle());
}
public String getContentHtml() {
return StrUtils.txt2htm(getContent());
}
public String getReplyHtml() {
return StrUtils.txt2htm(getReply());
}
public String getTitle() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getTitle();
} else {
return null;
}
}
public String getContent() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getContent();
} else {
return null;
}
}
public String getReply() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getReply();
} else {
return null;
}
}
public String getEmail() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getEmail();
} else {
return null;
}
}
public String getPhone() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getPhone();
} else {
return null;
}
}
public String getQq() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getQq();
} else {
return null;
}
}
public void init() {
if (getChecked() == null) {
setChecked(false);
}
if (getRecommend() == null) {
setRecommend(false);
}
if (getCreateTime() == null) {
setCreateTime(new Timestamp(System.currentTimeMillis()));
}
}
public JSONObject convertToJson()
throws JSONException{
JSONObject json=new JSONObject();
json.put("id", getId());
json.put("createTime", DateUtils.parseDateToTimeStr(getCreateTime()));
if(getReplayTime()!=null){
json.put("replayTime",DateUtils.parseDateToTimeStr(getReplayTime()));
}else{
json.put("replayTime", "");
}
json.put("recommend", getRecommend());
json.put("checked", getChecked());
if(getMember()!=null){
json.put("member", getMember().getUsername());
}else{
json.put("member", "");
}
if(getAdmin()!=null){
json.put("admin", getAdmin().getUsername());
}else{
json.put("admin", "");
}
json.put("ip", getIp());
json.put("ctg", getCtg().getName());
json.put("title", getTitle());
json.put("content", getContent());
json.put("reply", getReply());
json.put("email", getEmail());
json.put("phone", getPhone());
json.put("qq", getQq());
return json;
}
/* [CONSTRUCTOR MARKER BEGIN] */
public CmsGuestbook () {
super();
}
/**
* Constructor for primary key
*/
public CmsGuestbook (Integer id) {
super(id);
}
/**
* Constructor for required fields
*/
public CmsGuestbook (
Integer id,
com.jeecms.core.entity.CmsSite site,
com.jeecms.cms.entity.assist.CmsGuestbookCtg ctg,
String ip,
java.util.Date createTime,
Boolean checked,
Boolean recommend) {
super (
id,
site,
ctg,
ip,
createTime,
checked,
recommend);
}
/* [CONSTRUCTOR MARKER END] */
} | [
"[email protected]"
] | |
510f081adea03bcc9cc67abac03b4bd7e3d4e3ad | 814c6dedc1a4757fa578d88d7a90fd9aa747c122 | /IcePhoneNews - 副本/app/src/test/java/com/example/icephonenews/ExampleUnitTest.java | 3378bd42a7e7098fb3ef65e0c00eb92634116335 | [] | no_license | morichina/IcePhoneNews | 3fede9a9b041f5868f0d6bf50da6f6ec06168d88 | ac66c7f13b5c950cf53526598fa07889e19701b8 | refs/heads/master | 2020-06-16T15:48:18.310786 | 2019-07-07T08:29:47 | 2019-07-07T08:29:47 | 195,627,065 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 401 | java | package com.example.icephonenews;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
d65f8257e5903c8dd84851778b3e5b88d85625e7 | 707f572a136bb4192b5f7f7a05d8ccd670c2521c | /app/src/main/java/com/shervinf/blackbookstrength/LiftFragment.java | 0e589331dc8533a8893849276af69e11b7e18531 | [] | no_license | shervinf1/BlackBookStrength | f635e6b6df91d2fb78e8020b8886fbeeded64795 | 50f103a3d6c6f840ef49b1c94c4e9a5904014bba | refs/heads/master | 2021-07-12T01:41:12.683607 | 2020-09-30T03:55:25 | 2020-09-30T03:55:25 | 202,823,607 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,160 | java | package com.shervinf.blackbookstrength;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LiftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_lift,container,false);
//Code to setup tabs with their corresponding adapters
ViewPager viewPager = view.findViewById(R.id.pager);
LiftPagerAdapter myPagerAdapter = new LiftPagerAdapter(getFragmentManager());
viewPager.setAdapter(myPagerAdapter);
TabLayout tablayout = view.findViewById(R.id.tablayout);
tablayout.setupWithViewPager(viewPager);
return view;
}
}
| [
"[email protected]"
] | |
a1f8c80736975ba75567c6993472b8812822cbb4 | 47a1618c7f1e8e197d35746639e4480c6e37492e | /src/oracle/retail/stores/pos/services/instantcredit/DisplayInquiryInfoSite.java | 9dc12a1eaadb2e4a35c473ec148d0c10c70d22ee | [] | no_license | dharmendrams84/POSBaseCode | 41f39039df6a882110adb26f1225218d5dcd8730 | c588c0aa2a2144aa99fa2bbe1bca867e008f47ee | refs/heads/master | 2020-12-31T07:42:29.748967 | 2017-03-29T08:12:34 | 2017-03-29T08:12:34 | 86,555,051 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 16,545 | java | /* ===========================================================================
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* ===========================================================================
* $Header: rgbustores/applications/pos/src/oracle/retail/stores/pos/services/instantcredit/DisplayInquiryInfoSite.java /rgbustores_13.4x_generic_branch/10 2011/08/30 11:34:34 cgreene Exp $
* ===========================================================================
* NOTES
* <other useful comments, qualifications, etc.>
*
* MODIFIED (MM/DD/YY)
* cgreene 08/30/11 - check for RequestNotSupported first
* blarsen 06/30/11 - Setting ui's financial network status flag based on
* payment manager response. This will update the
* online/offline indicator on POS UI.
* sgu 06/21/11 - handle the case that response status will be null
* cgreene 06/15/11 - implement gift card for servebase and training mode
* sgu 06/13/11 - set training mode flag
* cgreene 05/27/11 - move auth response objects into domain
* sgu 05/24/11 - remove custom id from authorize instant credit
* request
* sgu 05/20/11 - refactor instant credit inquiry flow
* sgu 05/16/11 - move instant credit approval status to its own class
* sgu 05/12/11 - refactor instant credit formatters
* sgu 05/11/11 - define approval status for instant credit as enum
* type
* sgu 05/10/11 - convert instant credit inquiry by SSN to use new
* payment manager
* cgreene 02/15/11 - move constants into interfaces and refactor
* cgreene 05/26/10 - convert to oracle packaging
* cgreene 04/26/10 - XbranchMerge cgreene_tech43 from
* st_rgbustores_techissueseatel_generic_branch
* cgreene 04/02/10 - remove deprecated LocaleContantsIfc and currencies
* dwfung 02/05/10 - write masked SS# to EJ if search done by SSN
* abondala 01/03/10 - update header date
* vchengeg 02/20/09 - for I18N of HouseAccount Enquiry journal entry
* kulu 01/26/09 - Fix the bug that House Account enroll response data
* don't have padding translation at enroll franking
* slip
* kulu 01/22/09 - Switch to use response text instead of use status
* string based on status.
*
* ===========================================================================
* $Log:
* 13 360Commerce 1.12 5/29/2008 4:52:59 PM Maisa De Camargo CR
* 31672 - Setting fields required for the Instant Credit/House
* Account ISD Msg.
* 12 360Commerce 1.11 5/7/2008 8:55:11 PM Alan N. Sinton CR
* 30295: Code modified to present Function Unavailable dialog for
* House Account and Instant Credit when configured with ISD. Code
* reviewed by Anda Cadar.
* 11 360Commerce 1.10 4/27/2008 4:40:12 PM Alan N. Sinton CR
* 30295: Improvements to gift card handling, instant credit and house
* account in the ISD interface. Code was reviewed by Brett Larsen.
* 10 360Commerce 1.9 3/12/2008 12:34:41 PM Deepti Sharma
* changes to display house account number correctly
* 9 360Commerce 1.8 1/17/2008 5:24:06 PM Alan N. Sinton CR
* 29954: Refactor of EncipheredCardData to implement interface and be
* instantiated using a factory.
* 8 360Commerce 1.7 12/27/2007 10:39:29 AM Alan N. Sinton CR
* 29677: Check in changes per code review. Reviews are Michael
* Barnett and Tony Zgarba.
* 7 360Commerce 1.6 12/18/2007 5:47:48 PM Alan N. Sinton CR
* 29661: Changes per code review.
* 6 360Commerce 1.5 11/29/2007 5:15:58 PM Alan N. Sinton CR
* 29677: Protect user entry fields of PAN data.
* 5 360Commerce 1.4 11/27/2007 12:32:24 PM Alan N. Sinton CR
* 29661: Encrypting, masking and hashing account numbers for House
* Account.
* 4 360Commerce 1.3 1/25/2006 4:10:58 PM Brett J. Larsen merge
* 7.1.1 changes (aka. 7.0.3 fixes) into 360Commerce view
* 3 360Commerce 1.2 3/31/2005 4:27:48 PM Robert Pearse
* 2 360Commerce 1.1 3/10/2005 10:21:03 AM Robert Pearse
* 1 360Commerce 1.0 2/11/2005 12:10:39 PM Robert Pearse
*:
* 4 .v700 1.2.1.0 11/4/2005 11:44:43 Jason L. DeLeau 4202:
* Fix extensibility issues for instant credit service
* 3 360Commerce1.2 3/31/2005 15:27:48 Robert Pearse
* 2 360Commerce1.1 3/10/2005 10:21:03 Robert Pearse
* 1 360Commerce1.0 2/11/2005 12:10:39 Robert Pearse
*
* Revision 1.6 2004/08/02 19:59:54 blj
* @scr 6607 - fixed broken site an simulator code. Updated twiki page with new simulator info.
*
* Revision 1.5 2004/05/20 22:54:58 cdb
* @scr 4204 Removed tabs from code base again.
*
* Revision 1.4 2004/05/03 14:47:54 tmorris
* @scr 3890 -Ensures if the House Account variable is empty to respond with proper Error screen.
*
* Revision 1.3 2004/02/12 16:50:40 mcs
* Forcing head revision
*
* Revision 1.2 2004/02/11 21:51:22 rhafernik
* @scr 0 Log4J conversion and code cleanup
*
* Revision 1.1.1.1 2004/02/11 01:04:16 cschellenger
* updating to pvcs 360store-current
*
*
*
* Rev 1.11 Jan 09 2004 17:03:22 nrao
* Formatting the journal entries.
*
* Rev 1.10 Dec 19 2003 14:31:16 nrao
* Fixed potential null pointer exception.
*
* Rev 1.9 Dec 04 2003 17:31:58 nrao
* Code Review Changes.
*
* Rev 1.8 Dec 03 2003 17:25:50 nrao
* Moved screen display to new site.
*
* Rev 1.7 Dec 02 2003 18:10:26 nrao
* Corrected journal entry.
*
* Rev 1.6 Dec 02 2003 17:34:36 nrao
* Added account number to InstantCreditAuthRequest when it is sent to the authorizer. Added error dialog message.
*
* Rev 1.5 Nov 24 2003 19:16:42 nrao
* Using UIUtilities.
*
* Rev 1.4 Nov 21 2003 11:46:12 nrao
* Added ui display for card number.
*
* Rev 1.3 Nov 21 2003 11:36:02 nrao
* Changed card number size.
*
* Rev 1.2 Nov 20 2003 17:45:50 nrao
* Populated model with first name, last name and account number.
*
* Rev 1.1 Nov 20 2003 16:12:14 nrao
* Added journaling and removed "Authorizing ..." message for Inquiry.
*
* ===========================================================================
*/
package oracle.retail.stores.pos.services.instantcredit;
import java.util.Locale;
import oracle.retail.stores.common.parameter.ParameterConstantsIfc;
import oracle.retail.stores.common.utility.Util;
import oracle.retail.stores.domain.DomainGateway;
import oracle.retail.stores.domain.manager.ifc.PaymentManagerIfc;
import oracle.retail.stores.domain.manager.payment.AuthorizeInstantCreditRequestIfc;
import oracle.retail.stores.domain.manager.payment.AuthorizeInstantCreditResponseIfc;
import oracle.retail.stores.domain.manager.payment.AuthorizeRequestIfc;
import oracle.retail.stores.domain.manager.payment.AuthorizeResponseIfc;
import oracle.retail.stores.domain.manager.payment.PaymentServiceResponseIfc.ResponseCode;
import oracle.retail.stores.domain.utility.InstantCreditApprovalStatus;
import oracle.retail.stores.domain.utility.InstantCreditIfc;
import oracle.retail.stores.domain.utility.LocaleConstantsIfc;
import oracle.retail.stores.foundation.manager.ifc.JournalManagerIfc;
import oracle.retail.stores.foundation.manager.ifc.UIManagerIfc;
import oracle.retail.stores.foundation.tour.application.Letter;
import oracle.retail.stores.foundation.tour.gate.Gateway;
import oracle.retail.stores.foundation.tour.ifc.BusIfc;
import oracle.retail.stores.foundation.utility.LocaleMap;
import oracle.retail.stores.keystoreencryption.EncryptionServiceException;
import oracle.retail.stores.pos.manager.ifc.UtilityManagerIfc;
import oracle.retail.stores.pos.manager.utility.UtilityManager;
import oracle.retail.stores.pos.services.PosSiteActionAdapter;
import oracle.retail.stores.pos.services.common.CommonLetterIfc;
import oracle.retail.stores.pos.ui.DialogScreensIfc;
import oracle.retail.stores.pos.ui.POSUIManagerIfc;
import oracle.retail.stores.pos.ui.UIUtilities;
import oracle.retail.stores.pos.ui.beans.DialogBeanModel;
import oracle.retail.stores.pos.utility.ValidationUtility;
import oracle.retail.stores.utility.I18NConstantsIfc;
import oracle.retail.stores.utility.I18NHelper;
import oracle.retail.stores.utility.JournalConstantsIfc;
/**
* This site sends request to the authorizor for instant credit inquiry
*
* @version $Revision: /rgbustores_13.4x_generic_branch/10 $
*/
public class DisplayInquiryInfoSite extends PosSiteActionAdapter implements ParameterConstantsIfc
{
/**
* Serial Version UID
*/
private static final long serialVersionUID = -9083427640926904704L;
/** revision number supplied by version control **/
public static final String revisionNumber = "$Revision: /rgbustores_13.4x_generic_branch/10 $";
/** Constant for HOUSE_ACCOUNT_INQUIRY_FUNCTION_UNAVAILABLE */
public static final String HOUSE_ACCOUNT_INQUIRY_FUNCTION_UNAVAILABLE = "HouseAccountInquiryFunctionUnavailable";
public static final String MASKED_SOCIAL_SECURITY_NUMBER = "XXX-XX-XXXX";
/**
* Locale
*/
protected static Locale journalLocale = LocaleMap.getLocale(LocaleConstantsIfc.JOURNAL);
/* (non-Javadoc)
* @see oracle.retail.stores.foundation.tour.application.SiteActionAdapter#arrive(oracle.retail.stores.foundation.tour.ifc.BusIfc)
*/
@Override
public void arrive(BusIfc bus)
{
POSUIManagerIfc ui = (POSUIManagerIfc) bus.getManager(UIManagerIfc.TYPE);
InstantCreditCargo cargo = (InstantCreditCargo) bus.getCargo();
UtilityManager utility = (UtilityManager) bus.getManager(UtilityManagerIfc.TYPE);
PaymentManagerIfc paymentMgr = (PaymentManagerIfc)bus.getManager(PaymentManagerIfc.TYPE);
// Create Request to send to Authorizer
AuthorizeInstantCreditRequestIfc request = buildRequest(cargo);
AuthorizeResponseIfc response = paymentMgr.authorize(request);
UIUtilities.setFinancialNetworkUIStatus(response, (POSUIManagerIfc) bus.getManager(UIManagerIfc.TYPE));
if(ResponseCode.RequestNotSupported.equals(response.getResponseCode()))
{
//show the account not found acknowledgement screen
DialogBeanModel model = new DialogBeanModel();
model.setResourceID(HOUSE_ACCOUNT_INQUIRY_FUNCTION_UNAVAILABLE);
model.setType(DialogScreensIfc.ERROR);
model.setButtonLetter(DialogScreensIfc.BUTTON_OK, CommonLetterIfc.FAILURE);
ui.showScreen(POSUIManagerIfc.DIALOG_TEMPLATE, model);
}
else
{
InstantCreditApprovalStatus status = ((AuthorizeInstantCreditResponseIfc)response).getApprovalStatus();
cargo.setApprovalStatus(status);
if (InstantCreditApprovalStatus.APPROVED.equals(status))
{
// ssn/account number found and card information available
// build Instant Credit Card
InstantCreditIfc card = null;
try
{
card = ValidationUtility.createInstantCredit((AuthorizeInstantCreditResponseIfc)response, null, cargo.getSsn(), null);
}
catch(EncryptionServiceException ese)
{
logger.error("Could not encrypt house account number.", ese);
}
if(card != null)
{
cargo.setInstantCredit(card);
// write journal entry
writeJournal(cargo, utility);
// mail "Success" letter for displaying the account information screen
bus.mail(new Letter(CommonLetterIfc.SUCCESS), BusIfc.CURRENT);
}
else
{
UIUtilities.setDialogModel(ui, DialogScreensIfc.ACKNOWLEDGEMENT, "InquiryOffline",
null, CommonLetterIfc.NEXT);
}
}
// ssn not found
else if (InstantCreditApprovalStatus.REFERENCE_NOT_FOUND.equals(status))
{
UIUtilities.setDialogModel(ui, DialogScreensIfc.ACKNOWLEDGEMENT, "AccountNotFoundError",
null, CommonLetterIfc.NEXT);
}
// account number not found
else if (InstantCreditApprovalStatus.DECLINED.equals(status))
{
UIUtilities.setDialogModel(ui, DialogScreensIfc.ACKNOWLEDGEMENT, "AccountNotFoundError",
null, CommonLetterIfc.NEXT);
}
else
{
UIUtilities.setDialogModel(ui, DialogScreensIfc.ACKNOWLEDGEMENT, "InquiryOffline",
null, CommonLetterIfc.NEXT);
}
}
}
/**
* Builds request to be sent to the authorizer
* @param InstantCreditCargo cargo
* @param int timeout
* @return InstantCreditAuthRequest req
*/
protected AuthorizeInstantCreditRequestIfc buildRequest(InstantCreditCargo cargo)
{
AuthorizeInstantCreditRequestIfc req = DomainGateway.getFactory().getAuthorizeInstantCreditRequestInstance();
// set the request sub type for the inquiry
req.setRequestType(AuthorizeRequestIfc.RequestType.InstantCreditInquiry);
// set ssn
req.setSSN(cargo.getSsn());
req.setZipCode(cargo.getZipCode());
req.setHomePhone(cargo.getHomePhone());
if (cargo.getOperator() != null)
{
req.setEmployeeID(cargo.getOperator().getEmployeeID());
}
// set store ID and register ID
req.setWorkstation(cargo.getRegister().getWorkstation());
return req;
}
/**
* Writes the journal entry
* @param cargo InstantCreditCargo
*/
protected void writeJournal(InstantCreditCargo cargo, UtilityManager utility)
{
JournalManagerIfc journal = (JournalManagerIfc)Gateway.getDispatcher().getManager(JournalManagerIfc.TYPE);
if (journal != null)
{
StringBuffer sb = new StringBuffer();
Object data[];
sb.append(Util.EOL);
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE,
JournalConstantsIfc.HOUSE_ACCOUNT_INQUIRY_LABEL, null, journalLocale));
sb.append(Util.EOL);
data = new Object[] { cargo.getOperator().getLoginID() };
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE, JournalConstantsIfc.CASHIER_ID_LABEL, data,
journalLocale));
sb.append(Util.EOL);
data = new Object[] { cargo.getInstantCredit().getEncipheredCardData().getTruncatedAcctNumber() };
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE, JournalConstantsIfc.ACCOUNT_NUMBER_LABEL,
data, journalLocale));
if (cargo.getZipCode() != null)
{
sb.append(Util.EOL);
data = new Object[] { cargo.getZipCode() };
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE,
JournalConstantsIfc.ZIP_LABEL, data, journalLocale));
}
if (cargo.getHomePhone() != null)
{
sb.append(Util.EOL);
data = new Object[] { cargo.getHomePhone() };
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE,
JournalConstantsIfc.PHONE_NUMBER_LABEL, data, journalLocale));
}
if (cargo.getSsn() != null)
{
sb.append(Util.EOL);
data = new Object[] { MASKED_SOCIAL_SECURITY_NUMBER };
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE,
JournalConstantsIfc.SOCIAL_SECURITY_NUMBER_LABEL, data, journalLocale));
}
sb.append(Util.EOL);
journal.journal(sb.toString());
}
}
}
| [
"Ignitiv021@Ignitiv021-PC"
] | Ignitiv021@Ignitiv021-PC |
8c8927cded582c902fd5a257227a8d8037994e3f | c28e9356ee849c2a52a787cb12f2b4a3f27b5a0e | /app/src/main/java/hakan_akkurt_matthias_will/de/to_do_list/dialogs/DatePickerFragment.java | ff51d26753b8406e279315ab9119a8299e276726 | [] | no_license | HakanAkkurt/To-Do-List | 34f49a4cad2b68146341d9c75ed33cf5972bedc8 | 0142204b8d9ce3178b1ecd87e4da0b904b82a295 | refs/heads/master | 2021-04-29T07:33:26.755442 | 2017-01-31T20:23:15 | 2017-01-31T20:23:15 | 77,949,787 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,117 | java | package hakan_akkurt_matthias_will.de.to_do_list.dialogs;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import java.util.Calendar;
/**
* Created by Hakan Akkurt on 19.01.2017.
*/
public class DatePickerFragment extends DialogFragment {
private DatePickerDialog.OnDateSetListener listener;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this.listener, year, month, day);
}
@Override
public void onAttach(final Activity activity) {
if (activity instanceof DatePickerDialog.OnDateSetListener) {
this.listener = (DatePickerDialog.OnDateSetListener) activity;
}
super.onAttach(activity);
}
} | [
"[email protected]"
] | |
c097fa2d106081e3550fa5e540ceb9ebbf5081eb | cd9d753ecb5bd98e5e1381bc7bd2ffbd1eacc04d | /src/main/java/leecode/dfs/Solution39.java | 87dd6b124063c8bc17353211d49839d1b5c886f3 | [] | no_license | never123450/aDailyTopic | ea1bcdec840274442efa1223bf6ed33c0a394d3d | 9b17d34197a3ef2a9f95e8b717cbf7904c8dcfe4 | refs/heads/master | 2022-08-06T15:49:25.317366 | 2022-07-24T13:47:07 | 2022-07-24T13:47:07 | 178,113,303 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,457 | java | package leecode.dfs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @description: https://leetcode-cn.com/problems/combination-sum/
* 组合总和
* @author: xwy
* @create: 2021年08月12日16:42:26
**/
public class Solution39 {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates == null || candidates.length == 0) return null;
List<List<Integer>> lists = new ArrayList<>();
List<Integer> nums = new ArrayList<>();
// 配合 begin 用于去重,保证数字是有小到大的顺序选择的
Arrays.sort(candidates);
dfs(0, target, candidates, nums, lists);
return lists;
}
/**
* @param begin 从哪个位置的数开始选取(用于去重,保证数字是有小到大的顺序选择的)
* @param remain 还剩多少凑够 target
* @param candidates
* @param nums
* @param lists
*/
private void dfs(int begin, int remain, int[] candidates, List<Integer> nums, List<List<Integer>> lists) {
if (remain == 0) {
lists.add(new ArrayList<>(nums));
return;
}
for (int i = begin; i < candidates.length; i++) {
if (remain < candidates[i]) return;
nums.add(candidates[i]);
dfs(i, remain - candidates[i], candidates, nums, lists);
nums.remove(nums.size() - 1);
}
}
} | [
"[email protected]"
] | |
e3c0878e2aba424be1fe8e8a8b252b856cb9b8c9 | fd14b901fe3887ab5cc18301ad688a238feec358 | /src/org/ric/strukdat/project/Main.java | 19c47840d96b3dd02c9a6c98980d68dfb0802446 | [
"MIT"
] | permissive | angelbirth/calc | 484f1157716699d422ca94fe93d71f969ad14d5b | efa58414c55c0874b4e184a696ac2195e76c5757 | refs/heads/master | 2021-01-22T18:10:31.561992 | 2014-10-27T04:16:02 | 2014-10-27T04:16:02 | 25,800,643 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 959 | java | package org.ric.strukdat.project;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
if (args.length > 0) try {
if (!args[0].equals("-")) {
FileInputStream file = new FileInputStream(args[0]);
System.setIn(file);
}
} catch (FileNotFoundException e1) {
System.err.println("File tidak ditemukan.");
System.exit(1);
}
System.out
.println("Hai! Masukkan ekspresi matematika untuk dievaluasi:");
Scanner s = new Scanner(System.in);
try {
Evaluator e = new Evaluator(s.nextLine());
System.out.printf("Hasil perhitungannya adalah %f", e.evaluate());
} catch (IllegalArgumentException ex) {
System.err.println(ex.getMessage());
}
s.close();
}
}
| [
"[email protected]"
] | |
3fefc3ff6047afa1d9baf741c128027fb8b24ddb | 9fb4513e077fe4d797d7db83b9970c410aac8f21 | /src/main/java/com/github/kunalk16/excel/factory/SheetFactory.java | adce75e54e3a491758e26414965d0a4f486b7c79 | [
"MIT"
] | permissive | jrpedrianes/lightExcelReader | 23555189790689c2134147fb53a4bd30bc6d5457 | 4d5a82feccf66763fa9a65b3db7261905a933402 | refs/heads/master | 2022-12-31T14:06:56.609564 | 2020-10-17T13:16:20 | 2020-10-17T13:16:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,513 | java | package com.github.kunalk16.excel.factory;
import com.github.kunalk16.excel.factory.extractor.RowByNumberExtractor;
import com.github.kunalk16.excel.factory.filter.NonEmptyRowFilter;
import com.github.kunalk16.excel.model.factory.ExcelSheet;
import com.github.kunalk16.excel.model.jaxb.sharedstrings.SharedStringType;
import com.github.kunalk16.excel.model.jaxb.worksheet.SheetDataType;
import com.github.kunalk16.excel.model.jaxb.worksheet.WorkSheetType;
import com.github.kunalk16.excel.model.user.Row;
import com.github.kunalk16.excel.model.user.Sheet;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
class SheetFactory {
static Sheet create(SharedStringType sharedStrings, WorkSheetType workSheet, String sheetName) {
return Optional.ofNullable(getRows(sharedStrings, workSheet))
.map(new RowByNumberExtractor())
.map(rowByNumber -> new ExcelSheet(rowByNumber, sheetName))
.orElse(null);
}
private static List<Row> getRows(SharedStringType sharedStrings, WorkSheetType workSheet) {
return Optional.ofNullable(workSheet)
.map(WorkSheetType::getSheetData)
.map(SheetDataType::getRows)
.orElse(Collections.emptyList())
.stream()
.map(row -> RowFactory.create(sharedStrings, row))
.filter(new NonEmptyRowFilter())
.collect(Collectors.toList());
}
}
| [
"[email protected]"
] | |
1372f2a5fe9a9a31a9a30ee66e77fac0174f05c6 | 432816063f9d6e7ab90f5d3728dffaf42e73bc22 | /src/main/java/com/srichell/microservices/ratelimit/pojos/ApiKey.java | cf7d5ed047c6b8ae732d6b42cf5377a30c8a09a6 | [] | no_license | srichell/RateLimitingApis | 7b1173fa236af5ed185388158e85675799d94cba | 8a6e99207cadc18483141b6c74b8c77e8fc482a4 | refs/heads/master | 2021-01-11T12:28:05.651399 | 2016-12-18T17:25:57 | 2016-12-18T17:25:57 | 76,622,197 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 917 | java | package com.srichell.microservices.ratelimit.pojos;
/**
* Created by Sridhar Chellappa on 12/17/16.
*/
/*
* This class is an Abstraction for API keys. As of now, it just uses a plain string but
* it can be extended out to any other Data Type
*/
public class ApiKey {
private final String apiKey;
public ApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKey() {
return apiKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ApiKey)) return false;
ApiKey apiKey1 = (ApiKey) o;
return getApiKey().equals(apiKey1.getApiKey());
}
@Override
public int hashCode() {
return getApiKey().hashCode();
}
@Override
public String toString() {
return "ApiKey{" +
"apiKey='" + apiKey + '\'' +
'}';
}
}
| [
"[email protected]"
] | |
dbad81cd3087dea51e5024e889486ff59ed23e99 | fc90aea788f27ad5283b3724987151d35d91db1b | /aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/SolutionVersion.java | d0887ebe3c62c3897b7a1923aa897c63bca3021b | [
"Apache-2.0"
] | permissive | countVladimir/aws-sdk-java | bc63a06bbb51d93fb60e736e8b72fe75dbea5d48 | 631354f54ad5c41fa038217b1bda8161ab8d93e2 | refs/heads/master | 2023-02-12T17:31:12.240017 | 2021-01-07T22:44:04 | 2021-01-07T22:44:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 40,916 | java | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.personalize.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* An object that provides information about a specific version of a <a>Solution</a>.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/SolutionVersion" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SolutionVersion implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The ARN of the solution version.
* </p>
*/
private String solutionVersionArn;
/**
* <p>
* The ARN of the solution.
* </p>
*/
private String solutionArn;
/**
* <p>
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is <code>false</code>.
* </p>
*/
private Boolean performHPO;
/**
* <p>
* When true, Amazon Personalize searches for the most optimal recipe according to the solution configuration. When
* false (the default), Amazon Personalize uses <code>recipeArn</code>.
* </p>
*/
private Boolean performAutoML;
/**
* <p>
* The ARN of the recipe used in the solution.
* </p>
*/
private String recipeArn;
/**
* <p>
* The event type (for example, 'click' or 'like') that is used for training the model.
* </p>
*/
private String eventType;
/**
* <p>
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
* </p>
*/
private String datasetGroupArn;
/**
* <p>
* Describes the configuration properties for the solution.
* </p>
*/
private SolutionConfig solutionConfig;
/**
* <p>
* The time used to train the model. You are billed for the time it takes to train a model. This field is visible
* only after Amazon Personalize successfully trains a model.
* </p>
*/
private Double trainingHours;
/**
* <p>
* The scope of training used to create the solution version. The <code>FULL</code> option trains the solution
* version based on the entirety of the input solution's training data, while the <code>UPDATE</code> option
* processes only the training data that has changed since the creation of the last solution version. Choose
* <code>UPDATE</code> when you want to start recommending items added to the dataset without retraining the model.
* </p>
* <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* </important>
*/
private String trainingMode;
/**
* <p>
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing model.
* </p>
*/
private TunedHPOParams tunedHPOParams;
/**
* <p>
* The status of the solution version.
* </p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
* </ul>
*/
private String status;
/**
* <p>
* If training a solution version fails, the reason for the failure.
* </p>
*/
private String failureReason;
/**
* <p>
* The date and time (in Unix time) that this version of the solution was created.
* </p>
*/
private java.util.Date creationDateTime;
/**
* <p>
* The date and time (in Unix time) that the solution was last updated.
* </p>
*/
private java.util.Date lastUpdatedDateTime;
/**
* <p>
* The ARN of the solution version.
* </p>
*
* @param solutionVersionArn
* The ARN of the solution version.
*/
public void setSolutionVersionArn(String solutionVersionArn) {
this.solutionVersionArn = solutionVersionArn;
}
/**
* <p>
* The ARN of the solution version.
* </p>
*
* @return The ARN of the solution version.
*/
public String getSolutionVersionArn() {
return this.solutionVersionArn;
}
/**
* <p>
* The ARN of the solution version.
* </p>
*
* @param solutionVersionArn
* The ARN of the solution version.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withSolutionVersionArn(String solutionVersionArn) {
setSolutionVersionArn(solutionVersionArn);
return this;
}
/**
* <p>
* The ARN of the solution.
* </p>
*
* @param solutionArn
* The ARN of the solution.
*/
public void setSolutionArn(String solutionArn) {
this.solutionArn = solutionArn;
}
/**
* <p>
* The ARN of the solution.
* </p>
*
* @return The ARN of the solution.
*/
public String getSolutionArn() {
return this.solutionArn;
}
/**
* <p>
* The ARN of the solution.
* </p>
*
* @param solutionArn
* The ARN of the solution.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withSolutionArn(String solutionArn) {
setSolutionArn(solutionArn);
return this;
}
/**
* <p>
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is <code>false</code>.
* </p>
*
* @param performHPO
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is
* <code>false</code>.
*/
public void setPerformHPO(Boolean performHPO) {
this.performHPO = performHPO;
}
/**
* <p>
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is <code>false</code>.
* </p>
*
* @return Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is
* <code>false</code>.
*/
public Boolean getPerformHPO() {
return this.performHPO;
}
/**
* <p>
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is <code>false</code>.
* </p>
*
* @param performHPO
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is
* <code>false</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withPerformHPO(Boolean performHPO) {
setPerformHPO(performHPO);
return this;
}
/**
* <p>
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is <code>false</code>.
* </p>
*
* @return Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is
* <code>false</code>.
*/
public Boolean isPerformHPO() {
return this.performHPO;
}
/**
* <p>
* When true, Amazon Personalize searches for the most optimal recipe according to the solution configuration. When
* false (the default), Amazon Personalize uses <code>recipeArn</code>.
* </p>
*
* @param performAutoML
* When true, Amazon Personalize searches for the most optimal recipe according to the solution
* configuration. When false (the default), Amazon Personalize uses <code>recipeArn</code>.
*/
public void setPerformAutoML(Boolean performAutoML) {
this.performAutoML = performAutoML;
}
/**
* <p>
* When true, Amazon Personalize searches for the most optimal recipe according to the solution configuration. When
* false (the default), Amazon Personalize uses <code>recipeArn</code>.
* </p>
*
* @return When true, Amazon Personalize searches for the most optimal recipe according to the solution
* configuration. When false (the default), Amazon Personalize uses <code>recipeArn</code>.
*/
public Boolean getPerformAutoML() {
return this.performAutoML;
}
/**
* <p>
* When true, Amazon Personalize searches for the most optimal recipe according to the solution configuration. When
* false (the default), Amazon Personalize uses <code>recipeArn</code>.
* </p>
*
* @param performAutoML
* When true, Amazon Personalize searches for the most optimal recipe according to the solution
* configuration. When false (the default), Amazon Personalize uses <code>recipeArn</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withPerformAutoML(Boolean performAutoML) {
setPerformAutoML(performAutoML);
return this;
}
/**
* <p>
* When true, Amazon Personalize searches for the most optimal recipe according to the solution configuration. When
* false (the default), Amazon Personalize uses <code>recipeArn</code>.
* </p>
*
* @return When true, Amazon Personalize searches for the most optimal recipe according to the solution
* configuration. When false (the default), Amazon Personalize uses <code>recipeArn</code>.
*/
public Boolean isPerformAutoML() {
return this.performAutoML;
}
/**
* <p>
* The ARN of the recipe used in the solution.
* </p>
*
* @param recipeArn
* The ARN of the recipe used in the solution.
*/
public void setRecipeArn(String recipeArn) {
this.recipeArn = recipeArn;
}
/**
* <p>
* The ARN of the recipe used in the solution.
* </p>
*
* @return The ARN of the recipe used in the solution.
*/
public String getRecipeArn() {
return this.recipeArn;
}
/**
* <p>
* The ARN of the recipe used in the solution.
* </p>
*
* @param recipeArn
* The ARN of the recipe used in the solution.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withRecipeArn(String recipeArn) {
setRecipeArn(recipeArn);
return this;
}
/**
* <p>
* The event type (for example, 'click' or 'like') that is used for training the model.
* </p>
*
* @param eventType
* The event type (for example, 'click' or 'like') that is used for training the model.
*/
public void setEventType(String eventType) {
this.eventType = eventType;
}
/**
* <p>
* The event type (for example, 'click' or 'like') that is used for training the model.
* </p>
*
* @return The event type (for example, 'click' or 'like') that is used for training the model.
*/
public String getEventType() {
return this.eventType;
}
/**
* <p>
* The event type (for example, 'click' or 'like') that is used for training the model.
* </p>
*
* @param eventType
* The event type (for example, 'click' or 'like') that is used for training the model.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withEventType(String eventType) {
setEventType(eventType);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
* </p>
*
* @param datasetGroupArn
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
*/
public void setDatasetGroupArn(String datasetGroupArn) {
this.datasetGroupArn = datasetGroupArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
* </p>
*
* @return The Amazon Resource Name (ARN) of the dataset group providing the training data.
*/
public String getDatasetGroupArn() {
return this.datasetGroupArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
* </p>
*
* @param datasetGroupArn
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withDatasetGroupArn(String datasetGroupArn) {
setDatasetGroupArn(datasetGroupArn);
return this;
}
/**
* <p>
* Describes the configuration properties for the solution.
* </p>
*
* @param solutionConfig
* Describes the configuration properties for the solution.
*/
public void setSolutionConfig(SolutionConfig solutionConfig) {
this.solutionConfig = solutionConfig;
}
/**
* <p>
* Describes the configuration properties for the solution.
* </p>
*
* @return Describes the configuration properties for the solution.
*/
public SolutionConfig getSolutionConfig() {
return this.solutionConfig;
}
/**
* <p>
* Describes the configuration properties for the solution.
* </p>
*
* @param solutionConfig
* Describes the configuration properties for the solution.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withSolutionConfig(SolutionConfig solutionConfig) {
setSolutionConfig(solutionConfig);
return this;
}
/**
* <p>
* The time used to train the model. You are billed for the time it takes to train a model. This field is visible
* only after Amazon Personalize successfully trains a model.
* </p>
*
* @param trainingHours
* The time used to train the model. You are billed for the time it takes to train a model. This field is
* visible only after Amazon Personalize successfully trains a model.
*/
public void setTrainingHours(Double trainingHours) {
this.trainingHours = trainingHours;
}
/**
* <p>
* The time used to train the model. You are billed for the time it takes to train a model. This field is visible
* only after Amazon Personalize successfully trains a model.
* </p>
*
* @return The time used to train the model. You are billed for the time it takes to train a model. This field is
* visible only after Amazon Personalize successfully trains a model.
*/
public Double getTrainingHours() {
return this.trainingHours;
}
/**
* <p>
* The time used to train the model. You are billed for the time it takes to train a model. This field is visible
* only after Amazon Personalize successfully trains a model.
* </p>
*
* @param trainingHours
* The time used to train the model. You are billed for the time it takes to train a model. This field is
* visible only after Amazon Personalize successfully trains a model.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withTrainingHours(Double trainingHours) {
setTrainingHours(trainingHours);
return this;
}
/**
* <p>
* The scope of training used to create the solution version. The <code>FULL</code> option trains the solution
* version based on the entirety of the input solution's training data, while the <code>UPDATE</code> option
* processes only the training data that has changed since the creation of the last solution version. Choose
* <code>UPDATE</code> when you want to start recommending items added to the dataset without retraining the model.
* </p>
* <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* </important>
*
* @param trainingMode
* The scope of training used to create the solution version. The <code>FULL</code> option trains the
* solution version based on the entirety of the input solution's training data, while the
* <code>UPDATE</code> option processes only the training data that has changed since the creation of the
* last solution version. Choose <code>UPDATE</code> when you want to start recommending items added to the
* dataset without retraining the model.</p> <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* @see TrainingMode
*/
public void setTrainingMode(String trainingMode) {
this.trainingMode = trainingMode;
}
/**
* <p>
* The scope of training used to create the solution version. The <code>FULL</code> option trains the solution
* version based on the entirety of the input solution's training data, while the <code>UPDATE</code> option
* processes only the training data that has changed since the creation of the last solution version. Choose
* <code>UPDATE</code> when you want to start recommending items added to the dataset without retraining the model.
* </p>
* <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* </important>
*
* @return The scope of training used to create the solution version. The <code>FULL</code> option trains the
* solution version based on the entirety of the input solution's training data, while the
* <code>UPDATE</code> option processes only the training data that has changed since the creation of the
* last solution version. Choose <code>UPDATE</code> when you want to start recommending items added to the
* dataset without retraining the model.</p> <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* @see TrainingMode
*/
public String getTrainingMode() {
return this.trainingMode;
}
/**
* <p>
* The scope of training used to create the solution version. The <code>FULL</code> option trains the solution
* version based on the entirety of the input solution's training data, while the <code>UPDATE</code> option
* processes only the training data that has changed since the creation of the last solution version. Choose
* <code>UPDATE</code> when you want to start recommending items added to the dataset without retraining the model.
* </p>
* <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* </important>
*
* @param trainingMode
* The scope of training used to create the solution version. The <code>FULL</code> option trains the
* solution version based on the entirety of the input solution's training data, while the
* <code>UPDATE</code> option processes only the training data that has changed since the creation of the
* last solution version. Choose <code>UPDATE</code> when you want to start recommending items added to the
* dataset without retraining the model.</p> <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
* @see TrainingMode
*/
public SolutionVersion withTrainingMode(String trainingMode) {
setTrainingMode(trainingMode);
return this;
}
/**
* <p>
* The scope of training used to create the solution version. The <code>FULL</code> option trains the solution
* version based on the entirety of the input solution's training data, while the <code>UPDATE</code> option
* processes only the training data that has changed since the creation of the last solution version. Choose
* <code>UPDATE</code> when you want to start recommending items added to the dataset without retraining the model.
* </p>
* <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* </important>
*
* @param trainingMode
* The scope of training used to create the solution version. The <code>FULL</code> option trains the
* solution version based on the entirety of the input solution's training data, while the
* <code>UPDATE</code> option processes only the training data that has changed since the creation of the
* last solution version. Choose <code>UPDATE</code> when you want to start recommending items added to the
* dataset without retraining the model.</p> <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
* @see TrainingMode
*/
public SolutionVersion withTrainingMode(TrainingMode trainingMode) {
this.trainingMode = trainingMode.toString();
return this;
}
/**
* <p>
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing model.
* </p>
*
* @param tunedHPOParams
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing
* model.
*/
public void setTunedHPOParams(TunedHPOParams tunedHPOParams) {
this.tunedHPOParams = tunedHPOParams;
}
/**
* <p>
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing model.
* </p>
*
* @return If hyperparameter optimization was performed, contains the hyperparameter values of the best performing
* model.
*/
public TunedHPOParams getTunedHPOParams() {
return this.tunedHPOParams;
}
/**
* <p>
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing model.
* </p>
*
* @param tunedHPOParams
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing
* model.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withTunedHPOParams(TunedHPOParams tunedHPOParams) {
setTunedHPOParams(tunedHPOParams);
return this;
}
/**
* <p>
* The status of the solution version.
* </p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
* </ul>
*
* @param status
* The status of the solution version.</p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* The status of the solution version.
* </p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
* </ul>
*
* @return The status of the solution version.</p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* The status of the solution version.
* </p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
* </ul>
*
* @param status
* The status of the solution version.</p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withStatus(String status) {
setStatus(status);
return this;
}
/**
* <p>
* If training a solution version fails, the reason for the failure.
* </p>
*
* @param failureReason
* If training a solution version fails, the reason for the failure.
*/
public void setFailureReason(String failureReason) {
this.failureReason = failureReason;
}
/**
* <p>
* If training a solution version fails, the reason for the failure.
* </p>
*
* @return If training a solution version fails, the reason for the failure.
*/
public String getFailureReason() {
return this.failureReason;
}
/**
* <p>
* If training a solution version fails, the reason for the failure.
* </p>
*
* @param failureReason
* If training a solution version fails, the reason for the failure.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withFailureReason(String failureReason) {
setFailureReason(failureReason);
return this;
}
/**
* <p>
* The date and time (in Unix time) that this version of the solution was created.
* </p>
*
* @param creationDateTime
* The date and time (in Unix time) that this version of the solution was created.
*/
public void setCreationDateTime(java.util.Date creationDateTime) {
this.creationDateTime = creationDateTime;
}
/**
* <p>
* The date and time (in Unix time) that this version of the solution was created.
* </p>
*
* @return The date and time (in Unix time) that this version of the solution was created.
*/
public java.util.Date getCreationDateTime() {
return this.creationDateTime;
}
/**
* <p>
* The date and time (in Unix time) that this version of the solution was created.
* </p>
*
* @param creationDateTime
* The date and time (in Unix time) that this version of the solution was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withCreationDateTime(java.util.Date creationDateTime) {
setCreationDateTime(creationDateTime);
return this;
}
/**
* <p>
* The date and time (in Unix time) that the solution was last updated.
* </p>
*
* @param lastUpdatedDateTime
* The date and time (in Unix time) that the solution was last updated.
*/
public void setLastUpdatedDateTime(java.util.Date lastUpdatedDateTime) {
this.lastUpdatedDateTime = lastUpdatedDateTime;
}
/**
* <p>
* The date and time (in Unix time) that the solution was last updated.
* </p>
*
* @return The date and time (in Unix time) that the solution was last updated.
*/
public java.util.Date getLastUpdatedDateTime() {
return this.lastUpdatedDateTime;
}
/**
* <p>
* The date and time (in Unix time) that the solution was last updated.
* </p>
*
* @param lastUpdatedDateTime
* The date and time (in Unix time) that the solution was last updated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withLastUpdatedDateTime(java.util.Date lastUpdatedDateTime) {
setLastUpdatedDateTime(lastUpdatedDateTime);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getSolutionVersionArn() != null)
sb.append("SolutionVersionArn: ").append(getSolutionVersionArn()).append(",");
if (getSolutionArn() != null)
sb.append("SolutionArn: ").append(getSolutionArn()).append(",");
if (getPerformHPO() != null)
sb.append("PerformHPO: ").append(getPerformHPO()).append(",");
if (getPerformAutoML() != null)
sb.append("PerformAutoML: ").append(getPerformAutoML()).append(",");
if (getRecipeArn() != null)
sb.append("RecipeArn: ").append(getRecipeArn()).append(",");
if (getEventType() != null)
sb.append("EventType: ").append(getEventType()).append(",");
if (getDatasetGroupArn() != null)
sb.append("DatasetGroupArn: ").append(getDatasetGroupArn()).append(",");
if (getSolutionConfig() != null)
sb.append("SolutionConfig: ").append(getSolutionConfig()).append(",");
if (getTrainingHours() != null)
sb.append("TrainingHours: ").append(getTrainingHours()).append(",");
if (getTrainingMode() != null)
sb.append("TrainingMode: ").append(getTrainingMode()).append(",");
if (getTunedHPOParams() != null)
sb.append("TunedHPOParams: ").append(getTunedHPOParams()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus()).append(",");
if (getFailureReason() != null)
sb.append("FailureReason: ").append(getFailureReason()).append(",");
if (getCreationDateTime() != null)
sb.append("CreationDateTime: ").append(getCreationDateTime()).append(",");
if (getLastUpdatedDateTime() != null)
sb.append("LastUpdatedDateTime: ").append(getLastUpdatedDateTime());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SolutionVersion == false)
return false;
SolutionVersion other = (SolutionVersion) obj;
if (other.getSolutionVersionArn() == null ^ this.getSolutionVersionArn() == null)
return false;
if (other.getSolutionVersionArn() != null && other.getSolutionVersionArn().equals(this.getSolutionVersionArn()) == false)
return false;
if (other.getSolutionArn() == null ^ this.getSolutionArn() == null)
return false;
if (other.getSolutionArn() != null && other.getSolutionArn().equals(this.getSolutionArn()) == false)
return false;
if (other.getPerformHPO() == null ^ this.getPerformHPO() == null)
return false;
if (other.getPerformHPO() != null && other.getPerformHPO().equals(this.getPerformHPO()) == false)
return false;
if (other.getPerformAutoML() == null ^ this.getPerformAutoML() == null)
return false;
if (other.getPerformAutoML() != null && other.getPerformAutoML().equals(this.getPerformAutoML()) == false)
return false;
if (other.getRecipeArn() == null ^ this.getRecipeArn() == null)
return false;
if (other.getRecipeArn() != null && other.getRecipeArn().equals(this.getRecipeArn()) == false)
return false;
if (other.getEventType() == null ^ this.getEventType() == null)
return false;
if (other.getEventType() != null && other.getEventType().equals(this.getEventType()) == false)
return false;
if (other.getDatasetGroupArn() == null ^ this.getDatasetGroupArn() == null)
return false;
if (other.getDatasetGroupArn() != null && other.getDatasetGroupArn().equals(this.getDatasetGroupArn()) == false)
return false;
if (other.getSolutionConfig() == null ^ this.getSolutionConfig() == null)
return false;
if (other.getSolutionConfig() != null && other.getSolutionConfig().equals(this.getSolutionConfig()) == false)
return false;
if (other.getTrainingHours() == null ^ this.getTrainingHours() == null)
return false;
if (other.getTrainingHours() != null && other.getTrainingHours().equals(this.getTrainingHours()) == false)
return false;
if (other.getTrainingMode() == null ^ this.getTrainingMode() == null)
return false;
if (other.getTrainingMode() != null && other.getTrainingMode().equals(this.getTrainingMode()) == false)
return false;
if (other.getTunedHPOParams() == null ^ this.getTunedHPOParams() == null)
return false;
if (other.getTunedHPOParams() != null && other.getTunedHPOParams().equals(this.getTunedHPOParams()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
if (other.getFailureReason() == null ^ this.getFailureReason() == null)
return false;
if (other.getFailureReason() != null && other.getFailureReason().equals(this.getFailureReason()) == false)
return false;
if (other.getCreationDateTime() == null ^ this.getCreationDateTime() == null)
return false;
if (other.getCreationDateTime() != null && other.getCreationDateTime().equals(this.getCreationDateTime()) == false)
return false;
if (other.getLastUpdatedDateTime() == null ^ this.getLastUpdatedDateTime() == null)
return false;
if (other.getLastUpdatedDateTime() != null && other.getLastUpdatedDateTime().equals(this.getLastUpdatedDateTime()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getSolutionVersionArn() == null) ? 0 : getSolutionVersionArn().hashCode());
hashCode = prime * hashCode + ((getSolutionArn() == null) ? 0 : getSolutionArn().hashCode());
hashCode = prime * hashCode + ((getPerformHPO() == null) ? 0 : getPerformHPO().hashCode());
hashCode = prime * hashCode + ((getPerformAutoML() == null) ? 0 : getPerformAutoML().hashCode());
hashCode = prime * hashCode + ((getRecipeArn() == null) ? 0 : getRecipeArn().hashCode());
hashCode = prime * hashCode + ((getEventType() == null) ? 0 : getEventType().hashCode());
hashCode = prime * hashCode + ((getDatasetGroupArn() == null) ? 0 : getDatasetGroupArn().hashCode());
hashCode = prime * hashCode + ((getSolutionConfig() == null) ? 0 : getSolutionConfig().hashCode());
hashCode = prime * hashCode + ((getTrainingHours() == null) ? 0 : getTrainingHours().hashCode());
hashCode = prime * hashCode + ((getTrainingMode() == null) ? 0 : getTrainingMode().hashCode());
hashCode = prime * hashCode + ((getTunedHPOParams() == null) ? 0 : getTunedHPOParams().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
hashCode = prime * hashCode + ((getFailureReason() == null) ? 0 : getFailureReason().hashCode());
hashCode = prime * hashCode + ((getCreationDateTime() == null) ? 0 : getCreationDateTime().hashCode());
hashCode = prime * hashCode + ((getLastUpdatedDateTime() == null) ? 0 : getLastUpdatedDateTime().hashCode());
return hashCode;
}
@Override
public SolutionVersion clone() {
try {
return (SolutionVersion) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.personalize.model.transform.SolutionVersionMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| [
""
] | |
f8a691ec022c0ea7b4ce13cec233a1c88e69ec27 | b34a077d7f0dcd5dbb7c88f9d7df69d7d4dba6e1 | /src/main/java/org/Webgatherer/Controller/Base/EntryBase.java | f27f2a243c7dcaa429af80279eb7b6ab39319dd4 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | rickdane/WebGatherer---Scraper-and-Analyzer | 138b15c25d47ada5f14133ffc73d4f6df62ef314 | 6385db5e4a485132a4241a9670c62741545d8c90 | refs/heads/master | 2016-09-05T11:32:19.227440 | 2012-01-20T08:12:54 | 2012-01-20T08:12:54 | 2,817,230 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 791 | java | package org.Webgatherer.Controller.Base;
import com.google.gson.Gson;
import org.Webgatherer.Controller.EntityTransport.EntryTransport;
import org.Webgatherer.Utility.Service.WebServiceClient;
/**
* @author Rick Dane
*/
public class EntryBase {
protected static WebServiceClient webServiceClient = new WebServiceClient("http://localhost:8080/springservicesmoduleroo/entrys");
protected static String webServiceContentType = "application/json";
protected static void persistEntry(String data) {
EntryTransport entryTransport = new EntryTransport();
entryTransport.setDescription(data);
Gson gson = new Gson();
String jsonData = gson.toJson(entryTransport);
webServiceClient.servicePost("", jsonData, webServiceContentType);
}
}
| [
"[email protected]"
] | |
11f1a5622cebe22befd76b264339e9061724afa2 | 4da36b1f914659d6c685f88e1db8e705b8913f64 | /src/main/java/com/morben/restapi/service/impl/ProfileServiceImpl.java | 846678cf1eb0e9ebca1cff31ee25375f24691cdf | [] | no_license | OrbenMichele/rest-api | 6a9d12465de670a5e8b148e61af95c4d13f615e3 | 6e881864333f4403da65592bb63d9b590f049a14 | refs/heads/master | 2023-04-06T12:30:55.579621 | 2021-04-12T11:18:44 | 2021-04-12T11:18:44 | 356,342,660 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,097 | java | package com.morben.restapi.service.impl;
import com.morben.restapi.gateway.repository.ProfileRepository;
import com.morben.restapi.model.Profile;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
public class ProfileServiceImpl {
@Autowired
private ProfileRepository profileRepository;
public Profile save(Profile profile) {
return profileRepository.save(profile);
}
public Optional<Profile> findById(UUID id) {
return profileRepository.findById(id);
}
public List<Profile> findByAll() {
return profileRepository.findAll();
}
public void deleteById(UUID id) {
profileRepository.deleteById(id);
}
public Profile update(Profile pessoa, UUID id) {
Profile profileSaved = this.findById(id).get();
BeanUtils.copyProperties(pessoa, profileSaved, "id");
return profileRepository.save(profileSaved);
}
}
| [
"[email protected]"
] | |
a4b308a19a9eacb7d2605280447a30344d6fc1b3 | c72ab33625ef4565755406e59e732fc677c6eec7 | /DirectExchange-starter-code/Producer-starter-project/springboot-rabbitmq/src/main/java/com/poc/springbootrabbitmq/config/RabbitMQConfig.java | ec4d3f6b6c9f37112d0ed2cc7305c5ef1b3c0e47 | [] | no_license | Anand450623/RabbitMq | ebc474d7731482a0bffab647b7c49721045247ca | 8670aa4b3c72594269f8a13922c321a347e0be33 | refs/heads/master | 2023-04-27T23:17:12.333137 | 2019-10-04T19:00:24 | 2019-10-04T19:00:24 | 182,010,278 | 0 | 0 | null | 2023-04-14T17:48:52 | 2019-04-18T03:32:04 | Java | UTF-8 | Java | false | false | 1,142 | java | package com.poc.springbootrabbitmq.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig
{
@Value("${queueName}")
String queueName;
@Value("${exchangeName}")
String exchange;
@Value("${routingkey}")
private String routingkey;
@Bean
Queue queue() {
return new Queue(queueName, false);
}
@Bean
DirectExchange exchange() {
return new DirectExchange(exchange);
}
@Bean
Binding binding(Queue queue, DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(routingkey);
}
@Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
}
| [
"[email protected]"
] | |
dedbab9d2b09b4280d5f0e4eaefc69d06cc38132 | 3a7c8cca1af3ac5e831b3e4616a4b052bf5d9f1f | /app/src/main/java/com/example/dimpychhabra/capo/getCapo_Frag1.java | 526cdc4db381ab4f0bbe937fa42f3376fb7468f2 | [] | no_license | dimpy-chhabra/Capo_CarPoolingApp | d7bc86db106f3e22952798091e2784c5bf7e54bb | 759f592f59b68d28db2a11d69b4905ee23abf378 | refs/heads/master | 2021-08-24T02:10:06.048133 | 2017-12-07T15:46:33 | 2017-12-07T15:46:33 | 95,385,569 | 9 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,724 | java | package com.example.dimpychhabra.capo;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
/*
*Project : CAPO, fully created by
* Dimpy Chhabra, IGDTUW, BTech, IT
* Second year (as of 2017)
* Expected Class of 2019
* Please do not circulate as your own
* Criticism is appreciated to work on memory leaks and bugs
* Contact Info : Find me on Linked in : linkedin.com/in/dimpy-chhabra
*
*/
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class getCapo_Frag1 extends Fragment {
private static View view;
private static Button button;
private static EditText to;
private static FragmentManager fragmentManager;
public getCapo_Frag1() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_get_capo__frag1, container, false);
initViews();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String To;
To = to.getText().toString().trim().toUpperCase() ;
if (To.equals("")) {
Log.e("in lets capo frag1", " equals null");
new CustomToast().Show_Toast(getActivity(), view, "Please enter details in order to proceed.");
} else {
Fragment fragment = new getCapo_Frag2();
Bundle bundle = new Bundle();
bundle.putString("to:", To);
fragment.setArguments(bundle);
fragmentManager
.beginTransaction()
.setCustomAnimations(R.anim.right_enter, R.anim.left_out)
.replace(R.id.frameContainer, fragment,
BaseActivity.getCapo_Frag2)
.commit();
}
}
});
return view;
}
private void initViews() {
fragmentManager = getActivity().getSupportFragmentManager();
button = (Button) view.findViewById(R.id.b1);
to = (EditText) view.findViewById(R.id.to);
}
} | [
"[email protected]"
] | |
740756dd2e7885967555b98fff4032df61205565 | 748598e40201b8176deb013b04ea782cc1735698 | /src/unidad7/Ejercicio2.java | f34912eb5cef869fa365f342a1ec6c462b500758 | [] | no_license | tammy-creator/ejercicios2eval | f31c5e3ea55e3f53d8befb91863e0b7a9b7d0c1c | d546a017fa31627cb45ec392918a552f34aeb1cf | refs/heads/master | 2023-05-26T19:18:39.871059 | 2021-06-16T12:38:59 | 2021-06-16T12:38:59 | 347,685,484 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 457 | java | package unidad7;
public class Ejercicio2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Electrodomestico[] electrodomesticos=new Electrodomestico[3];
electrodomesticos[0]=new Lavadora(150,2,"B",25,9);
electrodomesticos[1]=new Frigorifico(185,2,"A",52);
electrodomesticos[2]=new Televisor(220,2,"C",15,50,"DVB-T");
for(Electrodomestico e:electrodomesticos) {
System.out.println(e.toString());
}
}
}
| [
"[email protected]"
] | |
f2224442ec162bd2508f4a13ca6a8527f7ea0e92 | 61385e624304cd1a38903d7ee60ca27196f0a984 | /3D Game(GDX Lib)/core/src/com/project/managers/EnemyAnimations.java | 15748ee5256b52c7085e4333027c923f7adf5a65 | [] | no_license | markoknezevic/Personal_projects | a8590e9a29432a7aaaf12f7ca3dbbc0029b46574 | e3427ee5371902eb9ea3f6b2ee45a58925e48e7c | refs/heads/master | 2020-04-16T08:56:08.122755 | 2019-07-23T21:56:19 | 2019-07-23T21:56:19 | 165,444,238 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,221 | java | package com.project.managers;
public class EnemyAnimations
{
public static final String [] __ATTACK_ANIMATION__ = new String[]
{
"Armature|attack1_l",
"Armature|attack1_r",
"Armature|attack2",
"Armature|attack3"
};
public static final String [] __DEAD_ANIMATION__ = new String[]
{
"Armature|dead1",
"Armature|dead2",
"Armature|dead3"
};
public static final String [] __HURT_ANIMATION__ = new String[]
{
"Armature|hurt",
"Armature|hurt_b",
"Armature|hurt_head",
"Armature|hurt_l",
"Armature|hurt_r"
};
public static final String [] __WALK_ANIMATION__ = new String[]
{
"Armature|walk",
"Armature|walk2"
};
public static final String __IDLE_ANIMATION__ = "Armature|idle";
public static final String __RUN_ANIMATION__ = "Armature|run";
public static final String __ENTER_ANIMATION__ = "Armature|enter_side";
}
| [
"[email protected]"
] | |
e9fe879b1811a3d264ac71498469aa29b58fe5c3 | 064cda386fc5850f7d859ca5aefd0c648acf061d | /src/bj2699/Main.java | 431e358dd8ba401d04c160678f381f034438c4b7 | [] | no_license | potionk/baekjoon | b0de5473bb2b324da404cd29e3b1d265c496f304 | fdbdccb75e5b4efc87fcb8788045d57b5b27454c | refs/heads/master | 2023-08-17T10:36:53.440645 | 2023-08-16T14:40:59 | 2023-08-16T14:40:59 | 195,223,018 | 8 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,440 | java | package bj2699;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int tc = Integer.parseInt(br.readLine());
while (tc-- > 0) {
int N = Integer.parseInt(br.readLine());
LinkedList<Point> points = new LinkedList<>();
for (int i = 0; i < N; i += 5) {
String[] pointInfo = br.readLine().split(" ");
for (int j = 0; j < pointInfo.length; j += 2) {
points.add(new Point(Integer.parseInt(pointInfo[j + 1]), Integer.parseInt(pointInfo[j])));
}
}
points.sort(Comparator.comparing(Point::getY).reversed().thenComparing(Point::getX));
Point p0 = points.pollFirst();
points.sort((p1, p2) -> ccwCompare(ccw(p0, p1, p2)));
points.addFirst(p0);
convexHull(points, bw);
}
br.close();
bw.close();
}
public static int convexHull(LinkedList<Point> points, BufferedWriter bw) throws IOException {
Stack<Point> stack = new Stack<>();
stack.push(points.pollFirst());
stack.push(points.pollFirst());
while (!points.isEmpty()) {
Point p3 = points.pop();
while (stack.size() >= 2 && ccw(p3, stack.get(stack.size() - 1), stack.get(stack.size() - 2)) <= 0) {
stack.pop();
}
stack.push(p3);
}
bw.write(stack.size() + "\n");
for (Point p : stack) {
bw.write(p.x + " " + p.y + "\n");
}
return stack.size();
}
public static long ccw(Point a, Point b, Point c) {
return a.x * b.y + b.x * c.y + c.x * a.y - b.x * a.y - c.x * b.y - a.x * c.y;
}
public static int ccwCompare(long ccw) {
if (ccw > 0) {
return 1;
} else if (ccw == 0) {
return 0;
} else {
return -1;
}
}
private static class Point {
long x;
long y;
public Point(long y, long x) {
this.y = y;
this.x = x;
}
public long getX() {
return x;
}
public long getY() {
return y;
}
}
} | [
"[email protected]"
] | |
4767dfc702a8b99cd5417a58d97ff52a188b8f2b | e6a719be6d33c1aba2009fca9497051044df405c | /Vpedometer/app/src/main/java/com/vincent/vpedometer/receiver/BootCompleteReceiver.java | c9c9adde2c59acdc38f07981034a1f2476449e14 | [] | no_license | IAm20cm/vpeodometer | 34e2569ccc9ae76423572ddab02b70536362203b | 0a31acd9724a141979c7c35d099f5e401c7e77b6 | refs/heads/master | 2023-08-22T03:11:16.832698 | 2021-10-29T03:50:01 | 2021-10-29T03:50:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 685 | java | package com.vincent.vpedometer.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.vincent.vpedometer.services.StepService;
/**
* when phone reboot, this class will do the open service job
*/
public class BootCompleteReceiver extends BroadcastReceiver {
public BootCompleteReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, StepService.class);
context.startService(i);
Log.i("reciver", "reboot");
// throw new UnsupportedOperationException("Not yet implemented");
}
}
| [
"[email protected]"
] | |
e5ff631ca02c1d3b3cfde055a7b9bb93a405a962 | c4759c6e2e1c399a82ebee0892dccdff8eefac56 | /sentry-core/src/main/java/io/sentry/core/Session.java | 17589825ae50916403c6324f39d5b0585579dbad | [
"MIT"
] | permissive | pulse00/sentry-android | 33028e0aad43321ed08845a988499315bffa1263 | fe11f70565c046b9e17592d652e0233bf28b22a7 | refs/heads/master | 2022-06-09T10:29:05.835350 | 2020-05-07T09:34:55 | 2020-05-07T09:34:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,544 | java | package io.sentry.core;
import io.sentry.core.protocol.User;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class Session {
/** Session state */
public enum State {
Ok,
Exited,
Crashed,
Abnormal
}
/** started timestamp */
private @Nullable Date started;
/** the timestamp */
private @Nullable Date timestamp;
/** the number of errors on the session */
private final @NotNull AtomicInteger errorCount;
/** The distinctId, did */
private final @Nullable String distinctId;
/** the SessionId, sid */
private final @Nullable UUID sessionId;
/** The session init flag */
private @Nullable Boolean init;
/** The session state */
private @Nullable State status;
/** The session sequence */
private @Nullable Long sequence;
/** The session duration (timestamp - started) */
private @Nullable Double duration;
/** the user's ip address */
private final @Nullable String ipAddress;
/** the user Agent */
private @Nullable String userAgent;
/** the environment */
private final @Nullable String environment;
/** the App's release */
private final @Nullable String release;
/** The session lock, ops should be atomic */
private final @NotNull Object sessionLock = new Object();
public Session(
final @Nullable State status,
final @Nullable Date started,
final @Nullable Date timestamp,
final int errorCount,
final @Nullable String distinctId,
final @Nullable UUID sessionId,
final @Nullable Boolean init,
final @Nullable Long sequence,
final @Nullable Double duration,
final @Nullable String ipAddress,
final @Nullable String userAgent,
final @Nullable String environment,
final @Nullable String release) {
this.status = status;
this.started = started;
this.timestamp = timestamp;
this.errorCount = new AtomicInteger(errorCount);
this.distinctId = distinctId;
this.sessionId = sessionId;
this.init = init;
this.sequence = sequence;
this.duration = duration;
this.ipAddress = ipAddress;
this.userAgent = userAgent;
this.environment = environment;
this.release = release;
}
public Session(
@Nullable String distinctId,
final @Nullable User user,
final @Nullable String environment,
final @Nullable String release) {
this(
State.Ok,
DateUtils.getCurrentDateTime(),
null,
0,
distinctId,
UUID.randomUUID(),
true,
0L,
null,
(user != null ? user.getIpAddress() : null),
null,
environment,
release);
}
public Date getStarted() {
final Date startedRef = started;
return startedRef != null ? (Date) startedRef.clone() : null;
}
public @Nullable String getDistinctId() {
return distinctId;
}
public @Nullable UUID getSessionId() {
return sessionId;
}
public @Nullable String getIpAddress() {
return ipAddress;
}
public @Nullable String getUserAgent() {
return userAgent;
}
public @Nullable String getEnvironment() {
return environment;
}
public @Nullable String getRelease() {
return release;
}
public @Nullable Boolean getInit() {
return init;
}
public int errorCount() {
return errorCount.get();
}
public @Nullable State getStatus() {
return status;
}
public @Nullable Long getSequence() {
return sequence;
}
public @Nullable Double getDuration() {
return duration;
}
public Date getTimestamp() {
final Date timestampRef = timestamp;
return timestampRef != null ? (Date) timestampRef.clone() : null;
}
/** Updated the session status based on status and errorcount */
private void updateStatus() {
// at this state it might be Crashed already, so we don't check for it.
if (status == State.Ok) {
status = State.Exited;
}
// fallback if status is null
if (status == null) {
// its ending a session and we don't have the current status, set it as Abnormal
status = State.Abnormal;
}
}
/** Ends a session and update its values */
public void end() {
end(DateUtils.getCurrentDateTime());
}
/**
* Ends a session and update its values
*
* @param timestamp the timestamp or null
*/
public void end(final @Nullable Date timestamp) {
synchronized (sessionLock) {
init = null;
updateStatus();
if (timestamp != null) {
this.timestamp = timestamp;
} else {
this.timestamp = DateUtils.getCurrentDateTime();
}
// fallback if started is null
if (started == null) {
started = timestamp;
}
duration = calculateDurationTime(this.timestamp, started);
sequence = getSequenceTimestamp();
}
}
/**
* Calculates the duration time in seconds timestamp (last update) - started
*
* @param timestamp the timestamp
* @param started the started timestamp
* @return duration in seconds
*/
private Double calculateDurationTime(final @NotNull Date timestamp, final @NotNull Date started) {
long diff = Math.abs(timestamp.getTime() - started.getTime());
return (double) diff / 1000; // duration in seconds
}
/**
* Updates the current session and set its values
*
* @param status the status
* @param userAgent the userAgent
* @param addErrorsCount true if should increase error count or not
* @return if the session has been updated
*/
public boolean update(final State status, final String userAgent, boolean addErrorsCount) {
synchronized (sessionLock) {
boolean sessionHasBeenUpdated = false;
if (status != null) {
this.status = status;
sessionHasBeenUpdated = true;
}
if (userAgent != null) {
this.userAgent = userAgent;
sessionHasBeenUpdated = true;
}
if (addErrorsCount) {
errorCount.addAndGet(1);
sessionHasBeenUpdated = true;
}
if (sessionHasBeenUpdated) {
init = null;
timestamp = DateUtils.getCurrentDateTime();
sequence = getSequenceTimestamp();
}
return sessionHasBeenUpdated;
}
}
/**
* Returns a logical clock.
*
* @return time stamp in milliseconds UTC
*/
private Long getSequenceTimestamp() {
return DateUtils.getCurrentDateTime().getTime();
}
}
| [
"[email protected]"
] | |
076850fb4c07500e68526b7f78243fc248b8c9c1 | 91d08b76658bc7dbda1b00b4cf4d3a5c4fa34dbb | /app/src/androidTest/java/com/example/viewpagertabs/ExampleInstrumentedTest.java | f91bed1c39bc783751e5f6386a36f9251e4da503 | [] | no_license | Utkarsh3118/ViewPagerExample-Tab-view- | 0575b98b696f417949ddd0e5f9277864f853a410 | d8a132dd45005f8e60558163b194325ef5810da9 | refs/heads/master | 2021-04-01T18:05:34.935891 | 2020-03-18T10:52:23 | 2020-03-18T10:52:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 755 | java | package com.example.viewpagertabs;
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.getInstrumentation().getTargetContext();
assertEquals("com.example.viewpagertabs", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
830873c5a4d31008f02474ad11f377bd4dc6d4e5 | 180e78725121de49801e34de358c32cf7148b0a2 | /dataset/protocol1/repairnator/learning/5092/NopolStatus.java | 455c00775c0c600ce0939c94123bc84a0eeab936 | [] | no_license | ASSERT-KTH/synthetic-checkstyle-error-dataset | 40e8d1e0a7ebe7f7711def96a390891a6922f7bd | 40c057e1669584bfc6fecf789b5b2854660222f3 | refs/heads/master | 2023-03-18T12:50:55.410343 | 2019-01-25T09:54:39 | 2019-01-25T09:54:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 185 | java | package fr.inria.spirals.repairnator.process.nopol;
/**
* Created by urli on 16/02/2017.
*/
public enum NopolStatus {
NOTLAUNCHED, RUNNING, NOPATCH, TIMEOUT, PATCH, EXCEPTION
}
| [
"[email protected]"
] | |
d36d763cf2f191dd2d92bb039bdc537535f844e6 | 10ad8ca683618d071b6fb44887d2053123adaf51 | /src/main/java/model/Food.java | 3e8a21c07836c9e8e3ff5dd6ec6bd1a72537cebf | [] | no_license | masinogns/neo | 2e9e2fe6bed6ee7b38b822f18e2cb41f2cc45be7 | b9bf62baf1411331f826cab69cc03fe0b952d7d9 | refs/heads/master | 2021-09-01T09:30:08.799902 | 2017-12-26T07:53:11 | 2017-12-26T07:53:11 | 107,079,186 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,645 | java | package model;
import javax.persistence.*;
/**
* Created by adaeng on 2017. 12. 12..
*/
@Entity
@Table(name = "food")
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String name;
@Column(name = "phone_number")
private String phoneNum;
@Column
private String address;
@Column
private double point;
@Column(name = "photo_url")
private String photoUrl;
@Column
private String lat;
@Column
private String lng;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getPoint() {
return point;
}
public void setPoint(double point) {
this.point = point;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
| [
"[email protected]"
] | |
674e5d16a9d1b1a9a24cc946a3bb09652c6a8641 | e7f6ea66cbe674b8c94f32a224dff74ddfb437fc | /JavaInterface/src/Interface/MultipleInterfaces.java | 62447058e031d500d433f29cc1c55da7bfbf2c0b | [] | no_license | yerizzz1/yeriyeri | 4cd83943dfc060f75fa5b4eb1c6ca9c12900ac6b | 423e2c3c1d9fcb8d7c6e6815d73d33d151bc5bbc | refs/heads/master | 2020-12-10T23:55:25.883845 | 2020-01-14T06:34:18 | 2020-01-14T06:34:18 | 233,746,324 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 878 | 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 Interface;
/**
*
* @author rosinaribka
*/
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
// DemoClass "implements" FirstInterface and SecondInterface
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class MultipleInterfaces {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
| [
"[email protected]"
] | |
986fe688be410ea5b83d612e2779dea518adf1bc | 5073dec48ac09dddf3c1a0ab78d6167849c7df4e | /51/GroupDataGenerator.java | 4535ae4ca0fd52b43cbe5f71b073224635a05065 | [
"Apache-2.0"
] | permissive | regina311/38 | 998ff2250a503f3e7e321c7e5bf862af06d2e5dd | 6a8228f338c01781aab5ef930509dd0fd5a9c908 | refs/heads/master | 2020-04-29T18:36:14.044483 | 2015-07-20T06:38:11 | 2015-07-20T06:38:11 | 39,001,925 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,759 | java | package com.example.tests;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class GroupDataGenerator {
public static void main(String[] args) throws IOException {
if (args.length <3){
System.out.println("parametr 3 need");
return;
}
int amount = Integer.parseInt(args[0]);
File file= new File(args[1]);
String format = args[2];
if (file.exists()) {
System.out.println("file exist,please remove it manually"+ file );
return;
}
List<GroupData>groups = generateRandomGroups(amount);
if ("csv".equals(format)){
saveGroupsToCsvFile(groups, file);
}else if ("xml".equals(format))
{
saveGroupsToXmlFile(groups, file);
} else {
System.out.println("unknown format"+ format);
return;
}
}
private static void saveGroupsToXmlFile(List<GroupData> groups, File file) {
}
private static void saveGroupsToCsvFile(List<GroupData> groups, File file) throws IOException {
FileWriter writer = new FileWriter(file);
for (GroupData group:groups){
writer.write(group.getName()+"," + group.getHeader()+"," +group.getFooter()+"\n");
}
writer.close();
}
public static List<GroupData> generateRandomGroups(int amount) {
List<GroupData> list = new ArrayList<GroupData>();
for (int i=0;i<amount; i++){
GroupData group = new GroupData()
.withName(generateRandomString())
.withHeader(generateRandomString())
.withFooter(generateRandomString());
list.add( group);
}
return list;
}
public static String generateRandomString(){
Random rnd = new Random();
if (rnd.nextInt(3)==0){
return "";
} else {
return "test"+rnd.nextInt();
}
}
}
| [
"[email protected]"
] | |
2a09430e6b38d7e556ec865b1af1a1fffba9db5a | 5d174c325b60f3797cf6993f30d02929081a64b6 | /teddy-backend/src/main/java/br/com/teddy/store/dto/ErrorDTO.java | 4e0dfbc82db7a8c939843e7b8c786c2e106871c9 | [] | no_license | diy-coder/teddy-world | 71ee9a746ee3ac78ef092db48e636a326f6db44e | 5edebc0eb3aaab50204a241b83af264119b18088 | refs/heads/main | 2023-08-01T09:34:26.468772 | 2021-09-14T22:58:37 | 2021-09-14T22:58:37 | 410,641,570 | 0 | 3 | null | 2021-09-26T19:20:25 | 2021-09-26T19:20:25 | null | UTF-8 | Java | false | false | 392 | java | package br.com.teddy.store.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class ErrorDTO extends AttrResponseDTO {
private boolean hasError = true;
private String message;
public ErrorDTO(String message) {
this.message = message;
}
}
| [
"[email protected]"
] | |
d8a829b6a315a8cc2c533e455bc4093fc808b04e | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/serge-rider--dbeaver/1d991820142f8df66b9f9fde2d28c2bbb603a84a/after/MySQLDialect.java | 911b2085bc1f922463c2e794fd1f2f0bf8785c5f | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,899 | java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* 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.jkiss.dbeaver.ext.mysql.model;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCDatabaseMetaData;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCSQLDialect;
import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import java.util.Arrays;
import java.util.Collections;
/**
* MySQL dialect
*/
class MySQLDialect extends JDBCSQLDialect {
public static final String[] MYSQL_NON_TRANSACTIONAL_KEYWORDS = ArrayUtils.concatArrays(
BasicSQLDialect.NON_TRANSACTIONAL_KEYWORDS,
new String[]{
"USE", "SHOW",
"CREATE", "ALTER", "DROP",
"EXPLAIN", "DESCRIBE", "DESC" }
);
public MySQLDialect() {
super("MySQL");
}
public void initDriverSettings(JDBCDataSource dataSource, JDBCDatabaseMetaData metaData) {
super.initDriverSettings(dataSource, metaData);
//addSQLKeyword("STATISTICS");
Collections.addAll(tableQueryWords, "EXPLAIN", "DESCRIBE", "DESC");
addFunctions(Arrays.asList("SLEEP"));
}
@Nullable
@Override
public String getScriptDelimiterRedefiner() {
return "DELIMITER";
}
@NotNull
@Override
public String escapeString(String string) {
return string.replace("'", "''").replace("\\", "\\\\");
}
@NotNull
@Override
public String unEscapeString(String string) {
return string.replace("''", "'").replace("\\\\", "\\");
}
@NotNull
@Override
public MultiValueInsertMode getMultiValueInsertMode() {
return MultiValueInsertMode.GROUP_ROWS;
}
@Override
public boolean supportsAliasInSelect() {
return true;
}
@Override
public boolean supportsCommentQuery() {
return true;
}
@Override
public String[] getSingleLineComments() {
return new String[] { "-- ", "#" };
}
@Override
public String getTestSQL() {
return "SELECT 1";
}
@NotNull
protected String[] getNonTransactionKeywords() {
return MYSQL_NON_TRANSACTIONAL_KEYWORDS;
}
} | [
"[email protected]"
] | |
0a008731d1aea1e341a815282f26aecf02cbdf94 | 3b5d3a99c0bcf4c62d32861b8a16fd2082ff58d2 | /Elibrary/src/main/java/com/elib/services/Bookservices.java | 78ac1563c006d44f3cb100f177131ee05e5af836 | [] | no_license | MestryNikhil/SpringBootProject | b068d2db82c9d2d3aeb095dc5e92da3e750ef56a | a607f38aa619c205c4c37f047b6940cef2ea5612 | refs/heads/master | 2020-03-13T12:20:22.852679 | 2018-05-22T12:10:05 | 2018-05-22T12:10:05 | 131,117,236 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 795 | java | package com.elib.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.elib.dao.BookRepository;
import com.elib.models.Book;
@Service
public class Bookservices {
@Autowired
private BookRepository bookRepository;
public void saveBook(Book book) {
bookRepository.save(book);
}
public List<Book> findAllBooks() {
List<Book> books=new ArrayList<Book>();
for (Book book : bookRepository.findAll()) {
books.add(book);
}
return books;
}
public void deleteBook(long id) {
bookRepository.delete(id);
}
public Book findOneBook(long id) {
return bookRepository.findOne(id);
}
}
| [
"Nikhil@DESKTOP-EH8LM9O"
] | Nikhil@DESKTOP-EH8LM9O |
1f97bcb3ff6bfa14a5078f2acd17af539e6b569c | 6acb7ca99d361e78b1624b299d7e85982d36cc98 | /Tanks Project/src/sprites/Bullet.java | 45b099b93887ed8a90b964950ad2a795531eaad1 | [] | no_license | jakobh7/Tanks | 24737a0bfa426a6d513da8343fe4acbe70d923eb | 4ba1c29cfcbec208c437563639636ee1847c5ffe | refs/heads/master | 2021-01-10T10:30:52.354520 | 2016-04-06T00:30:49 | 2016-04-06T00:30:49 | 55,183,849 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 744 | java | package sprites;
import javafx.scene.image.Image;
import main.ImageManager;
import main.Tanks;
public class Bullet extends Character {
private int bounces;
public Bullet(double initx, double inity, double initdx, double initdy){
super(initx, inity, initdx, initdy);
height = Tanks.BULLETSIZE;
width = Tanks.BULLETSIZE;
bounces = 0;
}
@Override
protected Image getImage() {
if(state == 0){return ImageManager.getBullet();}
else
return ImageManager.getExplosion(explosionNum);
}
public void reverseDx(){
super.reverseDx();
bounces++;
}
public void reverseDy(){
super.reverseDy();
bounces++;
}
public void update(){
super.update();
if(state == 0){
if(bounces > 1){
this.explode();
}
}
}
}
| [
"[email protected]"
] | |
866ac32d5e5d2ac0b1945e3fb31a75ff38e4b2a0 | 15202a875f903dbb6e2468518ae52b8726d1484b | /newUiproject/src/externalservices/Localservicetest.java | 068eb70936c51ed32eac365edccdd98f2736028b | [] | no_license | mohanpalsg/uiappcode | 948a67c73067a308f02944e5ac8d359aea914884 | 183355b42539f81cbaad8965141380f4553ed3dd | refs/heads/master | 2020-03-20T18:48:30.044483 | 2018-10-06T05:41:11 | 2018-10-06T05:41:11 | 137,605,170 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,647 | java | package externalservices;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.gson.Gson;
import dataobjects.StrategyinvestResult;
public class Localservicetest {
private LookupExternalService lkupextsrvc;
private String serviceurl;
public Localservicetest()
{
lkupextsrvc = new LookupExternalService();
serviceurl = "http://localhost:8080/restclear-0.0.1-SNAPSHOT/restservices/rest/";
}
public void callDataUpdate() {
// TODO Auto-generated method stub
lkupextsrvc.callDataUpdate(serviceurl);
}
public void callRTUpdate() {
// TODO Auto-generated method stub
lkupextsrvc.callRTUpdate(serviceurl);
}
public ArrayList<StrategyinvestResult> lookUpInvestTrend(String diff) {
// TODO Auto-generated method stub
return lookUpInvestTrend(serviceurl,diff);
}
private ArrayList<StrategyinvestResult> lookUpInvestTrend(String serviceurl, String diff) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
ArrayList<StrategyinvestResult> resultobj = new ArrayList<StrategyinvestResult>();
try
{
URL url = new URL(serviceurl+"InvestTrendHandlerService?diff="+diff+"&code=MuttonBriyani");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output="",result="";
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
result = result+output;
}
System.out.println(result);
Gson gson = new Gson();
resultobj = new ArrayList<StrategyinvestResult> (Arrays.asList(gson.fromJson(result, StrategyinvestResult[].class)));
System.out.println("Converted");
// conn.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
}
System.out.println(resultobj.size());
return resultobj;
}
public ArrayList<StrategyinvestResult> lookUpInvestWave(String diff) {
// TODO Auto-generated method stub
return lookUpInvestWave(serviceurl,diff);
}
private ArrayList<StrategyinvestResult> lookUpInvestWave(String serviceurl2, String diff) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
// TODO Auto-generated method stub
ArrayList<StrategyinvestResult> resultobj = new ArrayList<StrategyinvestResult>();
try
{
URL url = new URL(serviceurl+"InvestWaveHandlerService?diff="+diff+"&code=MuttonBriyani");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output="",result="";
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
result = result+output;
}
System.out.println(result);
Gson gson = new Gson();
resultobj = new ArrayList<StrategyinvestResult> (Arrays.asList(gson.fromJson(result, StrategyinvestResult[].class)));
System.out.println("Converted");
// conn.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
}
System.out.println(resultobj.size());
return resultobj;
}
}
| [
"citmo@DESKTOP-mohan"
] | citmo@DESKTOP-mohan |
92f2527715b41a193631646217c41afb9cf74d7d | e71f5d45a2dc979abcdd0295661fc48725aadf21 | /MJCompiler/src/rs/ac/bg/etf/pp1/ast/MyFactorNew.java | 757b6cd50c5df46341005909636a572b527ee84f | [] | no_license | jokara/MicroJava-Compiler | eb7cce205934495639bb4dc4d64f6b9ce2879674 | 70c345f637f392176c370fe89d65bc33d6852901 | refs/heads/main | 2023-03-17T22:39:03.328731 | 2021-03-06T16:02:07 | 2021-03-06T16:02:07 | 345,133,773 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,299 | java | // generated with ast extension for cup
// version 0.8
// 27/0/2020 20:37:8
package rs.ac.bg.etf.pp1.ast;
public class MyFactorNew extends Factor {
private Type Type;
public MyFactorNew (Type Type) {
this.Type=Type;
if(Type!=null) Type.setParent(this);
}
public Type getType() {
return Type;
}
public void setType(Type Type) {
this.Type=Type;
}
public void accept(Visitor visitor) {
visitor.visit(this);
}
public void childrenAccept(Visitor visitor) {
if(Type!=null) Type.accept(visitor);
}
public void traverseTopDown(Visitor visitor) {
accept(visitor);
if(Type!=null) Type.traverseTopDown(visitor);
}
public void traverseBottomUp(Visitor visitor) {
if(Type!=null) Type.traverseBottomUp(visitor);
accept(visitor);
}
public String toString(String tab) {
StringBuffer buffer=new StringBuffer();
buffer.append(tab);
buffer.append("MyFactorNew(\n");
if(Type!=null)
buffer.append(Type.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
buffer.append(tab);
buffer.append(") [MyFactorNew]");
return buffer.toString();
}
}
| [
"[email protected]"
] | |
a9f300fc19be0e6f83dd25ab8cdc08ed275ec109 | fed24d613eefe68217b5ade1fd65f7bedfdd813d | /core/src/test/java/com/linecorp/armeria/client/endpoint/dns/DnsNameEncoder.java | fd49752e6ed082b5ce1b925aa8b3769032ba0817 | [
"BSD-3-Clause",
"EPL-1.0",
"WTFPL",
"MIT",
"JSON",
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | anuraaga/armeria | 45f251337ecfe3eafb5d61fcd883cfb8f24ae6a4 | 7afa5bdbc25856568a49062a4195af94f3a3bf0f | refs/heads/master | 2021-11-04T04:51:12.220718 | 2020-05-15T06:41:56 | 2020-05-15T06:41:56 | 46,321,489 | 2 | 0 | Apache-2.0 | 2019-12-02T08:30:21 | 2015-11-17T03:43:26 | Java | UTF-8 | Java | false | false | 1,527 | java | /*
* Copyright 2018 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.client.endpoint.dns;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.dns.DefaultDnsRecordEncoder;
final class DnsNameEncoder {
static void encodeName(String name, ByteBuf out) {
DefaultDnsRecordEncoderTrampoline.INSTANCE.encodeName(name, out);
}
private DnsNameEncoder() {}
// Hacky trampoline class to be able to access encodeName
private static class DefaultDnsRecordEncoderTrampoline extends DefaultDnsRecordEncoder {
private static final DefaultDnsRecordEncoderTrampoline INSTANCE =
new DefaultDnsRecordEncoderTrampoline();
@Override
protected void encodeName(String name, ByteBuf buf) {
try {
super.encodeName(name, buf);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
}
| [
"[email protected]"
] | |
6d520d7c5d27670579f4b3b6e7f6f2d0d5b490e3 | 2fbfa1a2755ffa379c880f8f9d784a445ef79133 | /src/main/java/com/saving/myapp/config/JacksonConfiguration.java | 50716aed3cd4e6595556e76017228104378b60cb | [] | no_license | yogenmah04/friendsSaving | c96cdec1019a70996b8e61a134d0d99f8172ab0e | c6d76d939ba5520c8eedbf7c9fd35300d4aa8a1b | refs/heads/master | 2022-04-18T03:21:54.711921 | 2020-04-14T03:14:07 | 2020-04-14T03:14:07 | 255,498,452 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,642 | java | package com.saving.myapp.config;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.ProblemModule;
import org.zalando.problem.violations.ConstraintViolationProblemModule;
@Configuration
public class JacksonConfiguration {
/**
* Support for Java date and time API.
* @return the corresponding Jackson module.
*/
@Bean
public JavaTimeModule javaTimeModule() {
return new JavaTimeModule();
}
@Bean
public Jdk8Module jdk8TimeModule() {
return new Jdk8Module();
}
/*
* Support for Hibernate types in Jackson.
*/
@Bean
public Hibernate5Module hibernate5Module() {
return new Hibernate5Module();
}
/*
* Jackson Afterburner module to speed up serialization/deserialization.
*/
@Bean
public AfterburnerModule afterburnerModule() {
return new AfterburnerModule();
}
/*
* Module for serialization/deserialization of RFC7807 Problem.
*/
@Bean
ProblemModule problemModule() {
return new ProblemModule();
}
/*
* Module for serialization/deserialization of ConstraintViolationProblem.
*/
@Bean
ConstraintViolationProblemModule constraintViolationProblemModule() {
return new ConstraintViolationProblemModule();
}
}
| [
"[email protected]"
] | |
aa61c8954f571d8823d81252dc9a56c5769258d2 | 752d91d350aecb70e9cbf7dd0218ca034af652fa | /Winjit Deployment/Backend Source Code/src/main/java/com/fullerton/olp/wsdao/SoapLoggingInterceptor.java | d5a8c5c26b24787aff70466739ac1a7e1b80ee82 | [] | no_license | mnjdby/TEST | 5d0c25cf42eb4212f87cd4d23d1386633922f67e | cc2278c069e1711d4bd3f0a42eb360ea7417a6e7 | refs/heads/master | 2020-03-11T08:51:52.533185 | 2018-04-17T11:31:46 | 2018-04-17T11:31:46 | 129,894,682 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,653 | java | package com.fullerton.olp.wsdao;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ws.client.WebServiceClientException;
import org.springframework.ws.client.support.interceptor.ClientInterceptorAdapter;
import org.springframework.ws.context.MessageContext;
public class SoapLoggingInterceptor extends ClientInterceptorAdapter {
final static Logger log = LoggerFactory.getLogger(SoapLoggingInterceptor.class);
@Override
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
System.out.println("Request :");
try {
messageContext.getRequest().writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
@Override
public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
System.out.println("\nResponse : ");
try {
messageContext.getResponse().writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
@Override
public boolean handleFault(MessageContext messageContext) throws WebServiceClientException {
try {
messageContext.getResponse().writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
@Override
public void afterCompletion(MessageContext messageContext, Exception ex) throws WebServiceClientException {
log.info("=========================API CALL COMPLETED=========================");
}
} | [
"[email protected]"
] | |
02479ac0846f8c1f89a8f3eeb566768cea8fccfb | 8c01e11d3ed60645028d6dec02c8ae6b7a7d9be7 | /src/main/java/it/polimi/ingsw/networking/message/DiscardLeaderMessage.java | 7817ab4df217c52461ceb159169a0c68c8356de7 | [
"MIT"
] | permissive | cicabuca/ingswAM2021-Arbasino-Azzara-Bianco | 8477478c0d84e70cd9f032587e45bf9e768f1946 | adc996af03afdaaf76d9a35142499dd68c6c80d6 | refs/heads/main | 2023-06-26T19:13:33.734995 | 2021-07-31T12:09:57 | 2021-07-31T12:09:57 | 342,601,408 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 531 | java | package it.polimi.ingsw.networking.message;
/**
* Packet used to send to the server the will of the player to discard a certain LeaderCard
* It contains the index of the Leader Card he wants to discard (human readable)
*/
public class DiscardLeaderMessage extends Client2Server {
private static final long serialVersionUID = 2247524166072279266L;
private final int index;
public DiscardLeaderMessage(int index) {
this.index = index;
}
public int getLeaderIndex() {
return index;
}
}
| [
"[email protected]"
] | |
814805431cbc966fc59c8548b991154ec760719d | 2dffa4174257fa1319c1a09f78f6537de347ef7c | /src/OfficeHours/Practice_03_02_2021/PersonInfo.java | 7f81779631d7a02a13983a6371642523f21867fb | [] | no_license | VolodymyrPodoinitsyn/java-programming | a618ac811691028ce31377d5e0aa85b558e87388 | 2fae5d86a9c120fdb682fd8c1841b4f88c137183 | refs/heads/master | 2023-05-14T14:45:11.224117 | 2021-06-07T18:11:27 | 2021-06-07T18:11:27 | 374,758,971 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 774 | java | package OfficeHours.Practice_03_02_2021;
public class PersonInfo {
public static void main(String[] args) {
//Variable
String name, fullBirthDay, favoriteQuote;
byte age;
char gender;
boolean student;
short numberOfSiblings;
long favoriteNumbers;
int numberOfSeasons, year;
double birthDay;
// Assigment of data
name = "Volodymyr";
age = 38;
gender = 'M';
student = true;
numberOfSiblings = 5;
favoriteNumbers = 3L;
numberOfSeasons = 4;
birthDay = 3.2;
year = 2021;
fullBirthDay = "" + birthDay + "." + year;
favoriteQuote = "Have a good mindset";
System.out.println(fullBirthDay);
}
}
| [
"[email protected]"
] | |
2b99c25e22b1b43f8eaa8e1ec29249da68064082 | 6772404a102b2f98b02dcada7e46f1c98befc02f | /src/test/java/org/opensearch/security/ResolveAPITests.java | bdf5fca06e2d06ba7bb4898a0c9a65822b0bbea6 | [
"Apache-2.0"
] | permissive | xuezhou25/security | 5e3ac02288c5f4889fc78694680eba5763af0e67 | 0fc713b80a85078d10b518fa6b9c1de0259fcc0c | refs/heads/main | 2023-08-29T01:10:41.724046 | 2021-10-20T04:11:31 | 2021-10-20T04:11:31 | 419,181,230 | 0 | 0 | Apache-2.0 | 2021-10-20T04:11:08 | 2021-10-20T04:11:07 | null | UTF-8 | Java | false | false | 9,300 | java | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.opensearch.security;
import org.apache.http.HttpStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.opensearch.action.admin.indices.create.CreateIndexRequest;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.support.WriteRequest;
import org.opensearch.client.transport.TransportClient;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.security.test.DynamicSecurityConfig;
import org.opensearch.security.test.SingleClusterTest;
import org.opensearch.security.test.helper.rest.RestHelper;
public class ResolveAPITests extends SingleClusterTest {
protected final Logger log = LogManager.getLogger(this.getClass());
@Test
public void testResolveDnfofFalse() throws Exception {
Settings settings = Settings.builder().build();
setup(settings);
setupIndices();
final RestHelper rh = nonSslRestHelper();
RestHelper.HttpResponse res;
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertContains(res, "*vulcangov*");
assertContains(res, "*starfleet*");
assertContains(res, "*klingonempire*");
assertContains(res, "*xyz*");
assertContains(res, "*role01_role02*");
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertNotContains(res, "*vulcangov*");
assertNotContains(res, "*klingonempire*");
assertNotContains(res, "*xyz*");
assertNotContains(res, "*role01_role02*");
assertContains(res, "*starfleet*");
assertContains(res, "*starfleet_academy*");
assertContains(res, "*starfleet_library*");
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode());
log.debug(res.getBody());
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode());
log.debug(res.getBody());
assertContains(res, "*starfleet*");
assertContains(res, "*starfleet_academy*");
assertContains(res, "*starfleet_library*");
}
@Test
public void testResolveDnfofTrue() throws Exception {
final Settings settings = Settings.builder().build();
setup(Settings.EMPTY, new DynamicSecurityConfig().setConfig("config_dnfof.yml"), settings);
setupIndices();
final RestHelper rh = nonSslRestHelper();
RestHelper.HttpResponse res;
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertContains(res, "*vulcangov*");
assertContains(res, "*starfleet*");
assertContains(res, "*klingonempire*");
assertContains(res, "*xyz*");
assertContains(res, "*role01_role02*");
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertNotContains(res, "*vulcangov*");
assertNotContains(res, "*klingonempire*");
assertNotContains(res, "*xyz*");
assertNotContains(res, "*role01_role02*");
assertContains(res, "*starfleet*");
assertContains(res, "*starfleet_academy*");
assertContains(res, "*starfleet_library*");
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertNotContains(res, "*vulcangov*");
assertNotContains(res, "*kirk*");
assertContains(res, "*starfleet*");
assertContains(res, "*public*");
assertContains(res, "*xyz*");
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertNotContains(res, "*vulcangov*");
assertNotContains(res, "*kirk*");
assertNotContains(res, "*public*");
assertNotContains(res, "*xyz*");
assertContains(res, "*starfleet*");
assertContains(res, "*starfleet_academy*");
assertContains(res, "*starfleet_library*");
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("_resolve/index/vulcangov*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode());
log.debug(res.getBody());
}
private void setupIndices() {
try (TransportClient tc = getInternalTransportClient()) {
tc.admin().indices().create(new CreateIndexRequest("copysf")).actionGet();
tc.index(new IndexRequest("vulcangov").type("kolinahr").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("starfleet").type("ships").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("starfleet_academy").type("students").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("starfleet_library").type("public").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("klingonempire").type("ships").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("public").type("legends").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("spock").type("type01").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("kirk").type("type01").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("role01_role02").type("type01").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("xyz").type("doc").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(IndicesAliasesRequest.AliasActions.add().indices("starfleet","starfleet_academy","starfleet_library").alias("sf"))).actionGet();
tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(IndicesAliasesRequest.AliasActions.add().indices("klingonempire","vulcangov").alias("nonsf"))).actionGet();
tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(IndicesAliasesRequest.AliasActions.add().indices("public").alias("unrestricted"))).actionGet();
tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(IndicesAliasesRequest.AliasActions.add().indices("xyz").alias("alias1"))).actionGet();
}
}
}
| [
"[email protected]"
] | |
379d523575857cd84af5b465bceb63dbc0c3669e | 6d3ea5e5c45f074537ed2ba85f02ba4e9cede5ad | /src/cn/com/shxt/dialog/SearchSeat.java | a04dd201dc22b13f46034cefa9fcc6fa1fe9c13e | [] | no_license | viviant1224/rcpMovieSys | 15cf38d4bb22206924589b17c8a8474e26866af9 | 4ed7bae24e3d9de501132ea8d9089fc53a69aa50 | refs/heads/master | 2021-01-10T01:29:48.658989 | 2016-03-02T13:11:49 | 2016-03-02T13:11:49 | 52,963,544 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 8,118 | java | package cn.com.shxt.dialog;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wb.swt.ResourceManager;
import org.eclipse.wb.swt.SWTResourceManager;
import cn.com.shxt.tools.DbUtils;
public class SearchSeat extends Dialog {
protected Object result;
protected Shell shell;
private String id;
private String lie;
private String row;
private String roomname;
private static int crow;
private static int clie;
private Label lblNewLabel;
public static List myList = new ArrayList();
private String[] sss;
private boolean canUse = false;
private DbUtils db = new DbUtils();
/**
* Create the dialog.
*
* @param parent
* @param style
*/
public SearchSeat(Shell parent, int style) {
super(parent, style);
setText("SWT Dialog");
}
/**
* Open the dialog.
*
* @return the result
*/
public Object open(String id, String roomname) {
this.id = id;
this.roomname = roomname;
List<Map<String, Object>> list = db
.query("select lie,row from showroom where id = '" + id + "' ");
row = list.get(0).get("row").toString();
lie = list.get(0).get("lie").toString();
createContents();
shell.open();
shell.layout();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return result;
}
// 判断放映厅是否有上映电影
public boolean panduan() {
boolean a = false;
List<Map<String, Object>> list_1 = db
.query("select roomname from sell");
System.out.println("size=========" + list_1.size());
for (int i = 0; i < list_1.size(); i++) {
if (list_1.size() != 0) {
if (list_1.get(i).get("roomname").toString().equals(roomname)) {
a = true;
break;
}
}
}
return a;
}
/**
* Create contents of the dialog.
*/
private void createContents() {
shell = new Shell(getParent(), SWT.CLOSE);
shell.setSize(794, 579);
shell.setText("\u67E5\u770B\u5EA7\u4F4D");
final MessageBox box = new MessageBox(shell);
Label label = new Label(shell, SWT.NONE);
label.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
label.setBounds(570, 65, 61, 17);
label.setText("\u6E29\u99A8\u63D0\u793A:");
Label lblNewLabel_1 = new Label(shell, SWT.WRAP);
lblNewLabel_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
lblNewLabel_1.setBounds(570, 93, 215, 73);
lblNewLabel_1
.setText(" \u53CC\u51FB\uFF1A \u7EF4\u4FEE\u5EA7\u4F4D\u3001\u5355\u51FB\uFF1A\u6062\u590D\u5EA7\u4F4D \uFF08\u5982\u679C\u8BE5\u653E\u6620\u5385\u5DF2\u6709\u4E0A\u6620\u7535\u5F71\uFF0C\u4E0D\u80FD\u5BF9\u6B64\u653E\u6620\u5385\u7684\u72B6\u6001\u8FDB\u884C\u66F4\u6539\uFF01\uFF09");
Label lblNewLabel_2 = new Label(shell, SWT.NONE);
lblNewLabel_2.setBackground(SWTResourceManager
.getColor(SWT.COLOR_BLACK));
lblNewLabel_2.setBounds(47, 28, 502, 29);
lblNewLabel_2.setText("New Label");
Label label_1 = new Label(shell, SWT.NONE);
label_1.setBounds(10, 10, 61, 17);
label_1.setText("\u5C4F\u5E55\uFF1A");
Label label_2 = new Label(shell, SWT.NONE);
label_2.setBounds(10, 78, 45, 17);
label_2.setText("\u5EA7\u4F4D\uFF1A");
Label lblNewLabel_3 = new Label(shell, SWT.NONE);
lblNewLabel_3.setText("\u5165\u53E3");
lblNewLabel_3
.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLUE));
lblNewLabel_3.setBounds(0, 112, 31, 34);
int j = 0;
int k = 0;
for (int crow = 1; crow <= Integer.parseInt(row); crow++) {
for (int clie = 1; clie <= Integer.parseInt(lie); clie++) {
final String s = "" + crow + " " + clie;
final String[] ss = s.split(" ");
// System.out.println("crow="+ss[0]);
// System.out.println("clie="+ss[1]);
final Label lblNewLabel = new Label(shell, SWT.NONE);
lblNewLabel.setFont(SWTResourceManager.getFont("微软雅黑", 14, SWT.BOLD));
lblNewLabel.setText(ss[0] + "-" + ss[1]);
List<Map<String, Object>> list = db
.query("select state from zuowei where roomname = '"
+ roomname + "' " + " and row = '" + ss[0]
+ "' and lie = '" + ss[1] + "'");
if (list.get(0).get("state").toString().equals("可用")) {
// db.update("update zuowei set state = '不可用' where row = '"+ss[0]+"' and lie = '"+ss[1]+"'");
lblNewLabel.setBackgroundImage(ResourceManager
.getPluginImage("rcpyingyuanxitong",
"icons/QQ\u622A\u56FE20130615161817.jpg"));
} else if (list.get(0).get("state").toString().equals("维修")) {
// db.update("update zuowei set state = '可用' where row = '"+ss[0]+"' and lie = '"+ss[1]+"'");
lblNewLabel
.setBackgroundImage(ResourceManager.getPluginImage(
"rcpyingyuanxitong", "icons/bu.jpg"));
}
//
lblNewLabel.setBounds(102 + k * 60, 109 + j * 60, 39, 43);
lblNewLabel.addMouseListener(new MouseAdapter() {
@Override
/**
* @描述: 设置座位
* @作者:黄威威
* @版本:0.9
* @开发时间:2013-6-04上午11:20:59
*/
public void mouseDoubleClick(MouseEvent e) {
System.out.println("crow=" + ss[0]);
System.out.println("clie=" + ss[1]);
String str = "" + ss[0] + " " + ss[1];
if (panduan()) {
box.setText("系统消息");
box.setMessage("该放映厅已有上映电影,不能维修,请过段时间再操作");
box.open();
} else {
List<Map<String, Object>> list = db
.query("select state from zuowei where roomname = '"
+ roomname
+ "' and row = '"
+ ss[0]
+ "' and lie = '"
+ ss[1]
+ "'");
if (list.get(0).get("state").equals("可用")) {
myList.add(str);
lblNewLabel.setBackgroundImage(ResourceManager
.getPluginImage("rcpyingyuanxitong",
"icons/bu.jpg"));
box.setText("系统消息");
box.setMessage("座位维修");
box.open();
db.update("update zuowei set state = '维修' where roomname = '"
+ roomname
+ "' and row = '"
+ ss[0]
+ "' and lie = '" + ss[1] + "'");
}
System.out.println("" + myList);
}
}
public void mouseDown(MouseEvent e) {
System.out.println("crow=" + ss[0]);
System.out.println("clie=" + ss[1]);
String str = "" + ss[0] + " " + ss[1];
if (panduan()) {
box.setText("系统消息");
box.setMessage("该放映厅已有上映电影,不能维修,请过段时间再操作");
box.open();
} else {
List<Map<String, Object>> list = db
.query("select state from zuowei where roomname = '"
+ roomname
+ "' "
+ " and row = '"
+ ss[0]
+ "' and lie = '"
+ ss[1]
+ "'");
if (list.get(0).get("state").equals("维修")) {
myList.remove(str);
lblNewLabel.setBackgroundImage(ResourceManager
.getPluginImage("rcpyingyuanxitong",
"icons/QQ\u622A\u56FE20130615161817.jpg"));
db.update("update zuowei set state = '可用' where roomname = '"
+ roomname
+ "' and row = '"
+ ss[0]
+ "' and lie = '" + ss[1] + "'");
box.setText("系统消息");
box.setMessage("座位恢复");
box.open();
}
}
System.out.println("" + myList);
}
});
if (k % Integer.parseInt(lie) == Integer.parseInt(lie) - 1) {
j++;
k = -1;
}
k++;
}
}
}
}
| [
"[email protected]"
] | |
ed2b2f4726d7299574ea6f358c21ebecb817160f | 74d26f9c0954018cb1271f1ee2e3e2e00031bf77 | /CursoSelenium/src/main/java/br/ce/wcaquino/core/DSL.java | b95c77512a5a95527ce264bad28ecf08d70c8e40 | [] | no_license | GustAlves/Curso-Selenium-com-Cucumber | b6dcfbbd3cad81d106d83435efada200ad7cf1ea | 8dd958bdc17a2af5e60b96b68bc4cafafdf63654 | refs/heads/master | 2021-07-01T08:25:47.042117 | 2020-01-14T17:29:40 | 2020-01-14T17:29:40 | 227,842,851 | 0 | 0 | null | 2021-04-26T19:47:23 | 2019-12-13T13:09:42 | Java | UTF-8 | Java | false | false | 6,068 | java | package br.ce.wcaquino.core;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import static br.ce.wcaquino.core.DriverFactory.getDriver;
public class DSL {
/********* TextField e TextArea ************/
public void escrever(By by, String texto) {
getDriver().findElement(by).clear();
getDriver().findElement(by).sendKeys(texto);
}
public void escrever(String id_campo, String texto) {
escrever(By.id(id_campo), texto);
}
public String obterValorCampo(String id_campo) {
return getDriver().findElement(By.id(id_campo)).getAttribute("value");
}
/********* Radio e Check ************/
public void clicarRadio(By by) {
getDriver().findElement(by).click();
}
public void clicarRadio(String id) {
clicarRadio(By.id(id));
}
public boolean isRadioMarcado(String id) {
return getDriver().findElement(By.id(id)).isSelected();
}
public void clicarCheck(String id) {
getDriver().findElement(By.id(id)).click();
}
public boolean isCheckMarcado(String id) {
return getDriver().findElement(By.id(id)).isSelected();
}
/********* Combo ************/
public void selecionarCombo(String id, String valor) {
WebElement element = getDriver().findElement(By.id(id));
Select combo = new Select(element);
combo.selectByVisibleText(valor);
}
public void deselecionarCombo(String id, String valor) {
WebElement element = getDriver().findElement(By.id(id));
Select combo = new Select(element);
combo.deselectByVisibleText(valor);
}
public String obterValorCombo(String id) {
WebElement element = getDriver().findElement(By.id(id));
Select combo = new Select(element);
return combo.getFirstSelectedOption().getText();
}
public List<String> obterValoresCombo(String id) {
WebElement element = getDriver().findElement(By.id("elementosForm:esportes"));
Select combo = new Select(element);
List<WebElement> allSelectedOptions = combo.getAllSelectedOptions();
List<String> valores = new ArrayList<String>();
for (WebElement opcao : allSelectedOptions) {
valores.add(opcao.getText());
}
return valores;
}
public int obterQuantidadeOpcoesCombo(String id) {
WebElement element = getDriver().findElement(By.id(id));
Select combo = new Select(element);
List<WebElement> options = combo.getOptions();
return options.size();
}
public boolean verificarOpcaoCombo(String id, String opcao) {
WebElement element = getDriver().findElement(By.id(id));
Select combo = new Select(element);
List<WebElement> options = combo.getOptions();
for (WebElement option : options) {
if (option.getText().equals(opcao)) {
return true;
}
}
return false;
}
public void selecionarComboPrime(String radical, String valor) {
clicarRadio(By.xpath("//*[@id='" + radical + "_input']/../..//span"));
clicarRadio(By.xpath("//*[@id='" + radical + "_items']//li[.='" + valor + "']"));
}
/********* Botao ************/
public void clicarBotao(String id) {
getDriver().findElement(By.id(id)).click();
}
public String obterValueElemento(String id) {
return getDriver().findElement(By.id(id)).getAttribute("value");
}
/********* Link ************/
public void clicarLink(String link) {
getDriver().findElement(By.linkText(link)).click();
}
/********* Textos ************/
public String obterTexto(By by) {
return getDriver().findElement(by).getText();
}
public String obterTexto(String id) {
return obterTexto(By.id(id));
}
/********* Alerts ************/
public String alertaObterTexto() {
Alert alert = getDriver().switchTo().alert();
return alert.getText();
}
public String alertaObterTextoEAceita() {
Alert alert = getDriver().switchTo().alert();
String valor = alert.getText();
alert.accept();
return valor;
}
public String alertaObterTextoENega() {
Alert alert = getDriver().switchTo().alert();
String valor = alert.getText();
alert.dismiss();
return valor;
}
public void alertaEscrever(String valor) {
Alert alert = getDriver().switchTo().alert();
alert.sendKeys(valor);
alert.accept();
}
/********* Frames e Janelas ************/
public void entrarFrame(String id) {
getDriver().switchTo().frame(id);
}
public void sairFrame() {
getDriver().switchTo().defaultContent();
}
public void trocarJanela(String id) {
getDriver().switchTo().window(id);
}
/****** JAVA SCRIPT ******/
public Object executarJS(String cmd, Object... param) {
JavascriptExecutor js = (JavascriptExecutor) getDriver();
return js.executeScript(cmd, param);
}
/****** TABELA ******/
public void clicarBotaoTabela(String colunaBusca, String valor, String colunaBotao, String idTabela) {
// procurar coluna do registro
WebElement tabela = getDriver().findElement(By.xpath("//*[@id='" + idTabela + "']"));
int idColuna = obterIndiceColuna(colunaBusca, tabela);
// encontrar a linha do registro
int idLinha = obterIndiceLinha(valor, tabela, idColuna);
// procurar coluna do botao
int idColunaBotao = obterIndiceColuna(colunaBotao, tabela);
// clicar no botao da celula encontrada
WebElement celula = tabela.findElement(By.xpath(".//tr[" + idLinha + "]/td[" + idColunaBotao + "]"));
celula.findElement(By.xpath(".//input")).click();
}
protected int obterIndiceLinha(String valor, WebElement tabela, int idColuna) {
List<WebElement> linhas = tabela.findElements(By.xpath("./tbody/tr/td[" + idColuna + "]"));
int idLinha = -1;
for (int i = 0; i < linhas.size(); i++) {
if (linhas.get(i).getText().equals(valor)) {
idLinha = i + 1;
break;
}
}
return idLinha;
}
protected int obterIndiceColuna(String coluna, WebElement tabela) {
List<WebElement> colunas = tabela.findElements(By.xpath(".//th"));
int idColuna = -1;
for (int i = 0; i < colunas.size(); i++) {
if (colunas.get(i).getText().equals(coluna)) {
idColuna = i + 1;
break;
}
}
return idColuna;
}
}
| [
"[email protected]"
] | |
956835176a2f7ab8b6ca0baa27e4b580dde97b58 | 53727b3aec2bfe585d3a68eff70822d45b216767 | /src/crudv2projetolb3/Servlet.java | 0702598e69bea8fca5328a28885559fe0454cb08 | [] | no_license | MatheussAlves/projetoLAB3 | 50245beb4a62a04149dc402b51990d4034b76a20 | 2f9e2ae6825ba4a921e3a03c95b36a4be1c3e52e | refs/heads/master | 2021-08-22T07:40:24.726985 | 2017-11-29T17:02:18 | 2017-11-29T17:02:18 | 112,502,689 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,908 | java | package crudv2projetolb3;
import java.io.IOException;
import java.io.PrintWriter;
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 br.ucb.DAO.UsuarioDAO;
import br.ucb.entidades.Usuario;
/**
* Servlet implementation class Servlet
*/
@WebServlet("/Servlet")
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Servlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String login = request.getParameter("login");
String email = request.getParameter("email");
String senha = request.getParameter("senha");
Usuario user = new Usuario();
user.setEmail(email);
user.setLogin(login);
user.setSenha(senha);
new UsuarioDAO().salvar(user);
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<h3> DADOS ENVIADOS </h3>");
out.print("<h2> email: "+email+"</h2>");
out.print("<h2> login: "+login+"</h2>");
out.print("<h2> senha: "+senha+"</h2>");
out.print("<a href='index.html' > <button>Voltar</button> </a><br>");
//out.print("<input type='button' url='index.html'> voltar </input><br>");
out.print("</html>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| [
"[email protected]"
] | |
1a655ccf9894ad8d1eff15bbc47c011bff34db20 | afece0e242a522d603ba0d231a07901753a00810 | /ext/processor/src/main/java/org/omnifaces/serve/ext/processor/RootProcessor.java | c0a50d5b138a98dd9621829d7909a2f1aac95eb9 | [
"BSD-2-Clause"
] | permissive | omnifaces/omniserve | 24dc34c270873a7deacc27daf3742c178470a220 | bc7c07cdc166931eecbe3771239657c088d39419 | refs/heads/master | 2021-01-09T20:38:01.962253 | 2016-06-17T15:11:14 | 2016-06-17T15:11:14 | 61,379,983 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 197 | java | /*
* Copyright (c) 2016 OmniFaces.org. All Rights Reserved.
*/
package org.omnifaces.serve.ext.processor;
/**
* The root processor.
*/
public class RootProcessor extends ServeTagProcessor {
}
| [
"[email protected]"
] | |
de2e210c07696d39447a2d47e90b226979f86bd3 | dbe3e1cde0bc5110e9cc5e9837d8c1ccab301b77 | /app/src/main/java/ptrekaindo/absensi/assets/models/Shift.java | d177af70f0fbf83d4bbe13abcfbc3f105a42898a | [] | no_license | TamaraDhea/AbsensiOnlineREKA | fe6a83726faa00ecc770d61c385fa5d37802eaf1 | 83be67fa8a715626d77ddefacf1a03c44f248399 | refs/heads/master | 2022-12-29T07:43:34.333965 | 2020-10-21T01:43:01 | 2020-10-21T01:43:01 | 305,872,591 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,052 | java | package ptrekaindo.absensi.assets.models;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Shift implements Serializable {
@SerializedName("id_shift")
private String idShift;
@SerializedName("nama_shift")
private String namaShift;
@SerializedName("jam_mulai")
private String jamMulai;
@SerializedName("jam_selesai")
private String jamSelesai;
public String getIdShift() {
return idShift;
}
public void setIdShift(String idShift) {
this.idShift = idShift;
}
public String getNamaShift() {
return namaShift;
}
public void setNamaShift(String namaShift) {
this.namaShift = namaShift;
}
public String getJamMulai() {
return jamMulai;
}
public void setJamMulai(String jamMulai) {
this.jamMulai = jamMulai;
}
public String getJamSelesai() {
return jamSelesai;
}
public void setJamSelesai(String jamSelesai) {
this.jamSelesai = jamSelesai;
}
}
| [
"[email protected]"
] | |
0f8e30af20ed4f98da7ac0eb96cb3ee0eef68253 | a3dbab2349c9d34a9c0f762420b3ce0423a865b9 | /JavaStudy/src/B06_BreakContinue.java | c52c6223b61fa92b188106c2fe974b036b5ffed9 | [] | no_license | ParkCheonhyuk/JavaStudy | 0caa6b970d79742bf77110beeba8b00dc418a2d4 | ef2ee4419a972ff914021bfda64324c014e057d6 | refs/heads/main | 2023-06-12T00:27:43.804312 | 2021-07-08T12:43:08 | 2021-07-08T12:43:08 | 381,996,901 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 882 | java |
public class B06_BreakContinue {
public static void main(String[] args) {
/*
# break
- 반복문 내부에서 사용하면 속해있는 반복문을 하나만 탈출한다
- switch문은 내부에서 사용하면 switch문을 탈출한다
# continue
- 반복문 내부에서 사용하면 다음 번 반복으로 바로 넘어간다
- continue를 만난 시점에서 밑에 있는 반복문 블록은 모두 무시된다
*/
for(int i = 0; i < 10; i++) {
if (i==3 || i==4) {
continue;
}
System.out.println(i);
}
System.out.println("===========");
for(int i = 0; i < 10; i++) {
if (i==3 || i==4) {
break;
}
System.out.println(i);
}
// # for문의 무한 반복
for(int i = 0; true ; ++i) {
if(i == 1000) {
break;
}
System.out.println(i);
}
}
}
| [
"[email protected]"
] | |
9e2ac10445d538b670756f1606cafc9b4f03cda5 | 86801f77ee9328ce1f07ffae3a1f5684cfc103c0 | /src/main/java/com/juniorstart/juniorstart/model/audit/UserDateAudit.java | 8e6a00b1d33e91e704ef0938278bd4bb13bcdee9 | [] | no_license | Ejden/juniorstart-backend | dec2dce270e7cffbce198ef92e67310c0bfee085 | e623c6d164e25faf025ab5afe00506ac462c9bda | refs/heads/master | 2022-12-27T23:58:58.390379 | 2020-09-01T14:59:31 | 2020-09-01T14:59:31 | 291,681,797 | 1 | 0 | null | 2020-08-31T10:13:27 | 2020-08-31T10:13:27 | null | UTF-8 | Java | false | false | 564 | java | package com.juniorstart.juniorstart.model.audit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
@JsonIgnoreProperties(
value = {"createdBy", "updatedBy"},
allowGetters = true
)
@Data
public abstract class UserDateAudit extends DateAudit {
@CreatedBy
private Long createdBy;
@LastModifiedBy
private Long updatedBy;
} | [
"[email protected]"
] | |
279b6ff25ec019bdc7276cc6471185c7df39665c | 0e4db26d6db14d16d4dcb30aea81ecfd7120baa7 | /app/src/main/java/com/example/avengersassemble/model/ItemsDao.java | be657f1e39714d7fb2141881c2cab8f8a8c14be8 | [] | no_license | harsh4723/AvengersAssemble | a3d466f4b392ef52a8baa0dddb492205faf4fc4d | 5523fc57d61f629aa639658a170f77cc7ed45b91 | refs/heads/master | 2023-01-25T00:27:07.974679 | 2020-11-19T07:23:02 | 2020-11-19T07:23:02 | 313,925,615 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 540 | java | package com.example.avengersassemble.model;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface ItemsDao {
@Insert
void insertAll(ListItem items);
@Delete
void delete(ListItem item);
@Query("SELECT * FROM listitem")
List<ListItem> getAllItems();
@Query("SELECT * FROM listitem WHERE localid = :itemId")
ListItem getItem(int itemId);
@Query("DELETE FROM listitem")
void deleteAllItems();
} | [
"[email protected]"
] | |
ffcdad04ea8bc33586596289dcdc9ccd1a86bf8b | d1e863475c7df48e001f2ddd0544774fda114ddf | /Breeze/src/main/java/com/carmensol/data/Data/NewPolicyDetail.java | 9980a24d51e6ef9e6c18b3cdddc94cd1601244f3 | [] | no_license | ramandeepcarmen/BreezeAutomation | 95b7d19f36b62bd03211ecc2b7093d76c02bff60 | 080d59deab8bca13a8ada72c9c4dd05c61b107ce | refs/heads/master | 2021-08-07T18:34:43.414475 | 2020-03-22T12:40:56 | 2020-03-22T12:40:56 | 249,161,342 | 0 | 0 | null | 2021-04-26T20:04:59 | 2020-03-22T10:39:17 | HTML | UTF-8 | Java | false | false | 2,194 | java | package com.carmensol.data.Data;
public interface NewPolicyDetail
{
//Test data for test case 1915
String EffectiveDate1915 = "03/26/2021";
String EffectiveDate1915_ = "04/26/2021";
String ExpirationDate1915 = "03/25/2022";
String BusinessType1915 = "Individual";
String Company1915 = "James River Insurance";
String Division1915 = "General Casualty";
String GroupLine1915 ="Comm'l General Liab";
String PolicyType1915 = "Primary";
String ReinsuranceType1915 = "1 - Primary";
String HomeState1915 = "Alaska";
String UnderWriter1915 = "Ramandeep Singh";
String PolicyLimit1915 ="10000";
String MEP1915="20";
String BrokerAgent = "10671";
String BillingType1915 = "GROUP";
//Test data for Test case 669
String BrokerAgentN669 = "20271";
String BrokerageAgency669 = "AmWINS Brokerage of Alabama";
//Test data for Test case 666
String BrokerageAgency666 = "amwins insurance";
//Test data for Test case 683
String BrokerageAgency683 = "hhhhh";
//Test data for 865 and 870 and 875
String Name1 = "Ramandeep";
String Name2 = "Singh";
String EmailAddress = "[email protected]";
String Address1 = "Address1";
String Address2 = "Address2";
String State = "IN";
String City = "Allen";
String CityField = "City1";
String ZipCodeField = "1234";
String ZipCode ="46755";
String Name1_ = "Ramandeep1";
String AddressType = "Foreign";
String Country = "Australia";
//Test data for 935
String PolicyType935 = "Excess";
String AttachmentPoint935 = "1";
String TotalInsurableValue935 = "2";
String PartOfLimit935 = "3";
String AutoAttachmentPoint935 = "4";
//Test data for 934
String CommisionOverrideRate934 ="5";
String PolicyType934 = "Primary";
//Test data for 731 and 735
String BrokerNumber731="21023";
String SubBrokerageAgency731="all";
//Test data for 751
String SubBrokerAgency751="12890";
//Test data for 762
String BrokerAgentN762 = "21023";
String SubBrokerAgentN762 = "17084";
//TestData for 6474
String EffectiveDate6474 = "11/26/2018 ";
}
| [
"[email protected]"
] | |
6b60d324628244d147d15a90d5708c613aa85ba8 | e000510f5be13b52585f8299a01bb28da12304d1 | /SpringExample/src/main/java/info/_7chapters/spring/core/coreContainer/_12InstanceFactory/TestBean.java | 64716326871cc3bccfe84e1e0777da2f8130a43a | [] | no_license | 7chapters/springexample | a3d823af2e1ef5bb46c716de5091547241b62777 | bcb7fa945054b04007cba8fda9787b90df9557cb | refs/heads/master | 2021-01-22T23:58:27.026291 | 2013-05-18T04:02:31 | 2013-05-18T04:02:31 | 8,123,390 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 404 | java | package info._7chapters.spring.core.coreContainer._12InstanceFactory;
public class TestBean {
String msg;
public TestBean() {
super();
// TODO Auto-generated constructor stub
}
TestBean(String msg) {
this.msg = msg;
System.out.println("Constructor of TestBean class invoked");
}
public String toString() //to dispaly results
{
return msg;
}
}
| [
"[email protected]"
] | |
8b9b33a0065ec00685d8e3271240f94c5b8dc21a | a568d522706ef1e2f4c848d4956a1acc80006b41 | /ZizonBulls/src/main/java/com/java/dao/nanumDAOImpl.java | 71820708be2f5befa69bf266a77dba92d63b837d | [] | no_license | noruyam/academy_project | 4a95a823d1fe941f202f8be4c105ed31219ca3b9 | 809b4a0e7398a356958bcd9fd436090bc6a94d34 | refs/heads/master | 2023-08-13T04:52:43.975970 | 2021-10-15T05:05:43 | 2021-10-15T05:05:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,483 | java | package com.java.dao;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.java.domain.nanumVO;
@Repository("nanumDAO")
public class nanumDAOImpl implements namumDAO{
@Autowired
private SqlSessionTemplate mybatis;
@Override
public void insertBoard(nanumVO vo) {
// System.out.println(vo.getTitle());
System.out.println(">>>> nanumDAO.insertBoard() 호출");
mybatis.insert("nanumDAO.insertBoard",vo);
}
@Override
public void updateBoard(nanumVO vo) {
System.out.println(">>>> nanumDAO.updateBoard() 호출");
mybatis.update("nanumDAO.updateBoard",vo);
}
@Override
public void deleteBoard(nanumVO vo) {
System.out.println(">>>> nanumDAO.deleteBoard() 호출");
mybatis.delete("nanumDAO.deleteBoard",vo);
}
@Override
public nanumVO getBoard(nanumVO vo) {
System.out.println(">>>> nanumDAO.getBoard() 호출");
return mybatis.selectOne("nanumDAO.getBoard",vo);
}
@Override
public List<nanumVO> getBoardList() {
System.out.println(">>>> nanumDAO.getBoardList() 호출");
// BoardMapper.xml占쎈퓠 namespace
return mybatis.selectList("nanumDAO.getBoardList");
}
@Override
public void updatecnt(nanumVO vo) {
System.out.println(">>>> nanumDAO.getBoardList() 호출");
mybatis.update("nanumDAO.updatecnt",vo);
}
}
| [
"[email protected]"
] | |
000be4d6aeb8d81034a844385117f7b5fe5b7733 | e4cb5e99b95d8c05195bf01286318931ad5e66a6 | /modules/services/services-api/src/main/java/com/liferay/training/bookmarks/model/BookmarkModel.java | c0fcfc385cb67c4dae99ad7d540413d6b145e727 | [] | no_license | mahmoudhtayem87/LR-Bookmarks | 5d3cbc19c3ec06c7ce4c779a3170346e0c650242 | ac88f5bc95f56713c3d5cc577b93e6734b737d7c | refs/heads/master | 2023-08-30T12:26:35.321861 | 2021-10-24T08:20:46 | 2021-10-24T08:20:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,776 | java | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* 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.
*/
package com.liferay.training.bookmarks.model;
import com.liferay.portal.kernel.bean.AutoEscape;
import com.liferay.portal.kernel.model.BaseModel;
import com.liferay.portal.kernel.model.GroupedModel;
import com.liferay.portal.kernel.model.ShardedModel;
import com.liferay.portal.kernel.model.StagedAuditedModel;
import java.util.Date;
import org.osgi.annotation.versioning.ProviderType;
/**
* The base model interface for the Bookmark service. Represents a row in the "BOOKMARK_Bookmark" database table, with each column mapped to a property of this class.
*
* <p>
* This interface and its corresponding implementation <code>com.liferay.training.bookmarks.model.impl.BookmarkModelImpl</code> exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in <code>com.liferay.training.bookmarks.model.impl.BookmarkImpl</code>.
* </p>
*
* @author Brian Wing Shun Chan
* @see Bookmark
* @generated
*/
@ProviderType
public interface BookmarkModel
extends BaseModel<Bookmark>, GroupedModel, ShardedModel,
StagedAuditedModel {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this interface directly. All methods that expect a bookmark model instance should use the {@link Bookmark} interface instead.
*/
/**
* Returns the primary key of this bookmark.
*
* @return the primary key of this bookmark
*/
public long getPrimaryKey();
/**
* Sets the primary key of this bookmark.
*
* @param primaryKey the primary key of this bookmark
*/
public void setPrimaryKey(long primaryKey);
/**
* Returns the uuid of this bookmark.
*
* @return the uuid of this bookmark
*/
@AutoEscape
@Override
public String getUuid();
/**
* Sets the uuid of this bookmark.
*
* @param uuid the uuid of this bookmark
*/
@Override
public void setUuid(String uuid);
/**
* Returns the bookmark ID of this bookmark.
*
* @return the bookmark ID of this bookmark
*/
public long getBookmarkId();
/**
* Sets the bookmark ID of this bookmark.
*
* @param bookmarkId the bookmark ID of this bookmark
*/
public void setBookmarkId(long bookmarkId);
/**
* Returns the group ID of this bookmark.
*
* @return the group ID of this bookmark
*/
@Override
public long getGroupId();
/**
* Sets the group ID of this bookmark.
*
* @param groupId the group ID of this bookmark
*/
@Override
public void setGroupId(long groupId);
/**
* Returns the company ID of this bookmark.
*
* @return the company ID of this bookmark
*/
@Override
public long getCompanyId();
/**
* Sets the company ID of this bookmark.
*
* @param companyId the company ID of this bookmark
*/
@Override
public void setCompanyId(long companyId);
/**
* Returns the user ID of this bookmark.
*
* @return the user ID of this bookmark
*/
@Override
public long getUserId();
/**
* Sets the user ID of this bookmark.
*
* @param userId the user ID of this bookmark
*/
@Override
public void setUserId(long userId);
/**
* Returns the user uuid of this bookmark.
*
* @return the user uuid of this bookmark
*/
@Override
public String getUserUuid();
/**
* Sets the user uuid of this bookmark.
*
* @param userUuid the user uuid of this bookmark
*/
@Override
public void setUserUuid(String userUuid);
/**
* Returns the user name of this bookmark.
*
* @return the user name of this bookmark
*/
@AutoEscape
@Override
public String getUserName();
/**
* Sets the user name of this bookmark.
*
* @param userName the user name of this bookmark
*/
@Override
public void setUserName(String userName);
/**
* Returns the create date of this bookmark.
*
* @return the create date of this bookmark
*/
@Override
public Date getCreateDate();
/**
* Sets the create date of this bookmark.
*
* @param createDate the create date of this bookmark
*/
@Override
public void setCreateDate(Date createDate);
/**
* Returns the modified date of this bookmark.
*
* @return the modified date of this bookmark
*/
@Override
public Date getModifiedDate();
/**
* Sets the modified date of this bookmark.
*
* @param modifiedDate the modified date of this bookmark
*/
@Override
public void setModifiedDate(Date modifiedDate);
/**
* Returns the title of this bookmark.
*
* @return the title of this bookmark
*/
@AutoEscape
public String getTitle();
/**
* Sets the title of this bookmark.
*
* @param title the title of this bookmark
*/
public void setTitle(String title);
/**
* Returns the description of this bookmark.
*
* @return the description of this bookmark
*/
@AutoEscape
public String getDescription();
/**
* Sets the description of this bookmark.
*
* @param description the description of this bookmark
*/
public void setDescription(String description);
/**
* Returns the url of this bookmark.
*
* @return the url of this bookmark
*/
@AutoEscape
public String getUrl();
/**
* Sets the url of this bookmark.
*
* @param url the url of this bookmark
*/
public void setUrl(String url);
} | [
"[email protected]"
] | |
9e8abcdaec13ddfec0c03a0fbabc323187c53180 | 12a99ab3fe76e5c7c05609c0e76d1855bd051bbb | /src/main/java/com/alipay/api/domain/DisplayConfig.java | 85fa4fd5e441553a652a4fa1c6abf694a892eff9 | [
"Apache-2.0"
] | permissive | WindLee05-17/alipay-sdk-java-all | ce2415cfab2416d2e0ae67c625b6a000231a8cfc | 19ccb203268316b346ead9c36ff8aa5f1eac6c77 | refs/heads/master | 2022-11-30T18:42:42.077288 | 2020-08-17T05:57:47 | 2020-08-17T05:57:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 977 | java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 券的描述信息
*
* @author auto create
* @since 1.0, 2017-06-05 11:25:25
*/
public class DisplayConfig extends AlipayObject {
private static final long serialVersionUID = 3448669554245311969L;
/**
* 券的宣传语
含圈人的直领活动,且投放渠道选择了支付成功页或店铺的情况下必填
*/
@ApiField("slogan")
private String slogan;
/**
* 券的宣传图片文件ID
含圈人的直领活动,且投放渠道选择了店铺的情况下必填
*/
@ApiField("slogan_img")
private String sloganImg;
public String getSlogan() {
return this.slogan;
}
public void setSlogan(String slogan) {
this.slogan = slogan;
}
public String getSloganImg() {
return this.sloganImg;
}
public void setSloganImg(String sloganImg) {
this.sloganImg = sloganImg;
}
}
| [
"[email protected]"
] | |
db66227045d438c2e857c876a265730cd776cefa | 4e1171126b279c65da624092fd49b0713d26f596 | /src/test/java/com/ashwin/java/SwaggerDemoApplicationTests.java | 85a1438fccc554b5016765dcda2a92db048a1860 | [] | no_license | ashwindmk/springboot_swagger_demo | 8ba794502acd62c1d2c8130a5ecd0776f96dc446 | 0edf43ea676c65d3455bf7d2b22e70ce532ed265 | refs/heads/master | 2022-12-24T08:51:18.198541 | 2020-09-26T09:19:02 | 2020-09-26T09:19:02 | 298,774,569 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 212 | java | package com.ashwin.java;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SwaggerDemoApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
47deafec269298bc32d058efc3a0964242043f97 | d9b101ddb27677614fdf78eb7e0e7d2e9b2cf98c | /src/main/java/com/jiannei/duxin/controller/RoleResourceController.java | 1bdb90856be96b992acf3aa24e4b3da9a50e2a0e | [] | no_license | songbw/duxin | 8ef4d8297e97be0e209ff36ce23450643a59f38b | 03dcc20641e355715c2627e7e727943d64e7b810 | refs/heads/master | 2021-03-22T02:13:07.029675 | 2018-02-08T07:30:33 | 2018-02-08T07:30:33 | 119,036,835 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,885 | java | package com.jiannei.duxin.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import com.jiannei.duxin.service.IRoleResourceService;
import com.jiannei.duxin.dto.ResultBean;
import com.jiannei.duxin.query.RoleResourceQueryBean;
import com.jiannei.duxin.dto.RoleResourceDTO;
import com.jiannei.duxin.dto.SystemStatus;
import org.springframework.stereotype.Controller;
/**
* <p>
* 角色资源表 前端控制器
* </p>
*
* @author Songbw
* @since 2018-01-26
*/
@Controller
@RequestMapping("/duxin/roleResource")
public class RoleResourceController {
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(RoleResourceController.class);
@Autowired
private IRoleResourceService service;
@RequestMapping(value = "/page", method = RequestMethod.POST)
@ResponseBody
public ResultBean pageQuery(@RequestBody RoleResourceQueryBean queryBean) {
if (queryBean.getPageSize() <= 0) {
queryBean.setPageSize(20);
}
if (queryBean.getPageNo() < 0) {
queryBean.setPageNo(0);
}
ResultBean resultBean = new ResultBean();
try {
resultBean = service.listByPage(queryBean);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
}
return resultBean;
}
@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseBody
public ResultBean add(@RequestBody RoleResourceDTO dto) {
ResultBean resultBean = new ResultBean();
// if (StringUtils.isEmpty(usersDTO.getUsername())) {
// resultBean.setFailMsg(200101,"用户名不能为空");
// return resultBean;
// }
// if (StringUtils.isEmpty(usersDTO.getPassword())) {
// resultBean.setFailMsg(200102,"密码不能为空");
// return resultBean;
// }
try {
resultBean = service.insert(dto);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
return resultBean;
}
return resultBean;
}
@RequestMapping(value = "", method = RequestMethod.PUT)
@ResponseBody
public ResultBean update(@RequestBody RoleResourceDTO dto) {
ResultBean resultBean = new ResultBean();
// if (StringUtils.isEmpty(usersDTO.getId())) {
// resultBean.setFailMsg(200104,"ID不能为空");
// return resultBean;
// }
try {
resultBean = service.update(dto);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
return resultBean;
}
return resultBean;
}
@RequestMapping(value = "", method = RequestMethod.DELETE)
@ResponseBody
public ResultBean delete(int id) {
ResultBean resultBean = new ResultBean();
// if (id == 0) {
// resultBean.setFailMsg(200104,"ID不能为空");
// return resultBean;
// }
try {
resultBean = service.delete(id);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
return resultBean;
}
return resultBean;
}
@RequestMapping(value = "", method = RequestMethod.GET)
@ResponseBody
public ResultBean get(int id) {
ResultBean resultBean = new ResultBean();
// if (id == 0) {
// resultBean.setFailMsg(200104,"ID不能为空");
// return resultBean;
// }
try {
resultBean = service.get(id);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
return resultBean;
}
return resultBean;
}
/**
* 根据角色ID获取资源ID
*
* @param roleId
* @return
*/
@RequestMapping(value = "/role", method = RequestMethod.GET)
@ResponseBody
public ResultBean getByRole(int roleId) {
ResultBean resultBean = new ResultBean();
if (roleId == 0) {
resultBean.setFailMsg(SystemStatus.ROLEID_IS_NULL);
return resultBean;
}
try {
resultBean = service.getByRole(roleId);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
return resultBean;
}
return resultBean;
}
}
| [
"[email protected]"
] | |
79ac4b615da1f7aebb8ce5c9209c171022632c42 | b71e1f190701a54a324f6bf51ae29cd411d21556 | /src/main/java/com/tcs/appointment/Appointment/exception/UserNotFoundException.java | bb63d4b71a20a15b213fe1732bed191a52399be6 | [] | no_license | hussaint93/appoint | d5455dcbd9cd7e68710710358fcfef5d1e0ece4c | c3b6e71b7750fb796fbd0bcf32a5793e040601fe | refs/heads/main | 2023-07-10T09:51:04.034416 | 2021-08-27T13:04:20 | 2021-08-27T13:04:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 185 | java | package com.tcs.appointment.Appointment.exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
| [
"[email protected]"
] | |
d4a84e4fc8e6c41f86c80d5a8dd0e1925780759b | a15e6dae62a010e202d604ee0a703ecff0e364be | /src/main/java/code/swt/Menus.java | dff5704983640f1c5f9de88274d0bdcb327d0877 | [] | no_license | zhangzhef/java4 | 0ede3e1599a2c4767ce5baf9391e8feeb7d5a020 | e914642df32a7f5bc53155b6b2d7699d7d25487e | refs/heads/master | 2021-01-11T10:55:48.181391 | 2016-12-11T11:58:50 | 2016-12-11T11:58:50 | 76,162,456 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,479 | java | package code.swt;//: swt/Menus.java
// Fun with menus.
import swt.util.*;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import java.util.*;
import net.mindview.util.*;
public class Menus implements SWTApplication {
private static Shell shell;
public void createContents(Composite parent) {
shell = parent.getShell();
Menu bar = new Menu(shell, SWT.BAR);
shell.setMenuBar(bar);
Set<String> words = new TreeSet<String>(
new TextFile("Menus.java", "\\W+"));
Iterator<String> it = words.iterator();
while(it.next().matches("[0-9]+"))
; // Move past the numbers.
MenuItem[] mItem = new MenuItem[7];
for(int i = 0; i < mItem.length; i++) {
mItem[i] = new MenuItem(bar, SWT.CASCADE);
mItem[i].setText(it.next());
Menu submenu = new Menu(shell, SWT.DROP_DOWN);
mItem[i].setMenu(submenu);
}
int i = 0;
while(it.hasNext()) {
addItem(bar, it, mItem[i]);
i = (i + 1) % mItem.length;
}
}
static Listener listener = new Listener() {
public void handleEvent(Event e) {
System.out.println(e.toString());
}
};
void
addItem(Menu bar, Iterator<String> it, MenuItem mItem) {
MenuItem item = new MenuItem(mItem.getMenu(),SWT.PUSH);
item.addListener(SWT.Selection, listener);
item.setText(it.next());
}
public static void main(String[] args) {
SWTConsole.run(new Menus(), 600, 200);
}
} ///:~
| [
"zzf016"
] | zzf016 |
409f0bc32f962d68873878033d97e65611394707 | 99243d1d8b3d3bf161585f29c1cab11eec4ae1bc | /app/src/main/java/com/alion/accessibility/AccessibilityMainActivity.java | 88369415dd34cb08a6d4f601b7ea740272ebc4fa | [] | no_license | alion2015/AlionApplication | 9c7ca30277c93a620ed6c8ab1828753a68c71270 | c5304c3abaf3474db2aaf9c253c24a139f6a7322 | refs/heads/master | 2020-03-28T22:47:37.455433 | 2019-06-28T07:33:50 | 2019-06-28T07:33:50 | 149,258,464 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,632 | java | package com.alion.accessibility;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.alion.myapplication.R;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import static com.alion.accessibility.utils.AccessibilityUtil.jumpToSettingPage;
public class AccessibilityMainActivity extends Activity implements View.OnClickListener {
private View mOpenSetting;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accessibility_main);
initView();
AccessibilityOperator.getInstance().init(this);
test();
}
private void test() {
}
private void initView() {
mOpenSetting = findViewById(R.id.open_accessibility_setting);
mOpenSetting.setOnClickListener(this);
findViewById(R.id.accessibility_find_and_click).setOnClickListener(this);
}
@Override
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.open_accessibility_setting:
jumpToSettingPage(this);
break;
case R.id.accessibility_find_and_click:
Intent intent = new Intent();
intent.setClassName("com.jifen.qukan", "com.jifen.qkbase.main.MainActivity");
startActivity(intent);
break;
}
}
}
| [
"Gz20150721"
] | Gz20150721 |
4dfdd8bb1a268b10249431f7c337fc11c1087198 | 3714974b546f7fddeeea54d84b543c3b350a7583 | /myProjects/MGTV/src/com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson.java | 0f26403d6012e0e2b4e76bbfe50c893d02896112 | [] | no_license | lubing521/ideaProjects | 57a8dadea5c0d8fc3e478c7829e6897dce242bde | 5fd85e6dbe1ede8f094de65226de41321c1d0683 | refs/heads/master | 2022-01-18T23:10:05.057971 | 2018-10-26T12:27:00 | 2018-10-26T12:27:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,721 | java | package com.starcor.core.parser.json;
import com.starcor.core.domain.UserCenterInfo;
import com.starcor.core.interfaces.IXmlParser;
import java.io.InputStream;
public class GetUserCenterInfoSAXParserJson<Result>
implements IXmlParser<Result>
{
UserCenterInfo info = new UserCenterInfo();
public Result parser(InputStream paramInputStream)
{
return null;
}
// ERROR //
public Result parser(byte[] paramArrayOfByte)
{
// Byte code:
// 0: aload_1
// 1: ifnonnull +5 -> 6
// 4: aconst_null
// 5: areturn
// 6: new 27 java/lang/String
// 9: dup
// 10: aload_1
// 11: invokespecial 30 java/lang/String:<init> ([B)V
// 14: astore_2
// 15: ldc 32
// 17: new 34 java/lang/StringBuilder
// 20: dup
// 21: invokespecial 35 java/lang/StringBuilder:<init> ()V
// 24: ldc 37
// 26: invokevirtual 41 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 29: aload_2
// 30: invokevirtual 41 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 33: invokevirtual 45 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 36: invokestatic 51 com/starcor/core/utils/Logger:i (Ljava/lang/String;Ljava/lang/String;)V
// 39: new 53 org/json/JSONObject
// 42: dup
// 43: aload_2
// 44: invokespecial 56 org/json/JSONObject:<init> (Ljava/lang/String;)V
// 47: astore 4
// 49: aload 4
// 51: ldc 58
// 53: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 56: ifeq +17 -> 73
// 59: aload_0
// 60: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 63: aload 4
// 65: ldc 58
// 67: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 70: putfield 69 com/starcor/core/domain/UserCenterInfo:state Ljava/lang/String;
// 73: aload 4
// 75: ldc 71
// 77: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 80: ifeq +17 -> 97
// 83: aload_0
// 84: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 87: aload 4
// 89: ldc 71
// 91: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 94: putfield 73 com/starcor/core/domain/UserCenterInfo:reason Ljava/lang/String;
// 97: aload 4
// 99: ldc 75
// 101: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 104: ifeq +345 -> 449
// 107: new 53 org/json/JSONObject
// 110: dup
// 111: aload 4
// 113: ldc 75
// 115: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 118: invokespecial 56 org/json/JSONObject:<init> (Ljava/lang/String;)V
// 121: astore 5
// 123: aload 5
// 125: ldc 77
// 127: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 130: istore 6
// 132: iload 6
// 134: ifeq +23 -> 157
// 137: aload_0
// 138: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 141: aload 5
// 143: ldc 77
// 145: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 148: invokestatic 83 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 151: invokevirtual 87 java/lang/Integer:intValue ()I
// 154: putfield 90 com/starcor/core/domain/UserCenterInfo:err I
// 157: aload 5
// 159: ldc 92
// 161: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 164: ifeq +17 -> 181
// 167: aload_0
// 168: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 171: aload 5
// 173: ldc 92
// 175: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 178: putfield 94 com/starcor/core/domain/UserCenterInfo:status Ljava/lang/String;
// 181: aload 5
// 183: ldc 96
// 185: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 188: ifeq +261 -> 449
// 191: new 53 org/json/JSONObject
// 194: dup
// 195: aload 5
// 197: ldc 96
// 199: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 202: invokespecial 56 org/json/JSONObject:<init> (Ljava/lang/String;)V
// 205: astore 7
// 207: aload 7
// 209: ldc 98
// 211: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 214: istore 8
// 216: iload 8
// 218: ifeq +23 -> 241
// 221: aload_0
// 222: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 225: aload 7
// 227: ldc 98
// 229: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 232: invokestatic 83 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 235: invokevirtual 87 java/lang/Integer:intValue ()I
// 238: putfield 101 com/starcor/core/domain/UserCenterInfo:vipId I
// 241: aload 7
// 243: ldc 103
// 245: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 248: ifeq +17 -> 265
// 251: aload_0
// 252: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 255: aload 7
// 257: ldc 103
// 259: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 262: putfield 106 com/starcor/core/domain/UserCenterInfo:vipName Ljava/lang/String;
// 265: aload 7
// 267: ldc 108
// 269: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 272: istore 9
// 274: iload 9
// 276: ifeq +23 -> 299
// 279: aload_0
// 280: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 283: aload 7
// 285: ldc 108
// 287: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 290: invokestatic 83 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 293: invokevirtual 87 java/lang/Integer:intValue ()I
// 296: putfield 111 com/starcor/core/domain/UserCenterInfo:viPower I
// 299: aload 7
// 301: ldc 113
// 303: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 306: istore 10
// 308: iload 10
// 310: ifeq +23 -> 333
// 313: aload_0
// 314: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 317: aload 7
// 319: ldc 113
// 321: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 324: invokestatic 118 java/lang/Float:valueOf (Ljava/lang/String;)Ljava/lang/Float;
// 327: invokevirtual 122 java/lang/Float:floatValue ()F
// 330: putfield 125 com/starcor/core/domain/UserCenterInfo:balance F
// 333: aload 7
// 335: ldc 127
// 337: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 340: ifeq +17 -> 357
// 343: aload_0
// 344: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 347: aload 7
// 349: ldc 127
// 351: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 354: putfield 130 com/starcor/core/domain/UserCenterInfo:loginaccount Ljava/lang/String;
// 357: aload 7
// 359: ldc 132
// 361: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 364: istore 11
// 366: iload 11
// 368: ifeq +23 -> 391
// 371: aload_0
// 372: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 375: aload 7
// 377: ldc 132
// 379: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 382: invokestatic 83 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 385: invokevirtual 87 java/lang/Integer:intValue ()I
// 388: putfield 135 com/starcor/core/domain/UserCenterInfo:vipEndDays I
// 391: aload 7
// 393: ldc 137
// 395: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 398: ifeq +17 -> 415
// 401: aload_0
// 402: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 405: aload 7
// 407: ldc 137
// 409: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 412: putfield 140 com/starcor/core/domain/UserCenterInfo:vipEndDate Ljava/lang/String;
// 415: aload 7
// 417: ldc 142
// 419: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 422: istore 12
// 424: iload 12
// 426: ifeq +23 -> 449
// 429: aload_0
// 430: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 433: aload 7
// 435: ldc 142
// 437: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 440: invokestatic 83 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 443: invokevirtual 87 java/lang/Integer:intValue ()I
// 446: putfield 144 com/starcor/core/domain/UserCenterInfo:account_type I
// 449: aload_0
// 450: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 453: areturn
// 454: astore 18
// 456: aload_0
// 457: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 460: iconst_0
// 461: putfield 90 com/starcor/core/domain/UserCenterInfo:err I
// 464: goto -307 -> 157
// 467: astore_3
// 468: aload_3
// 469: invokevirtual 147 org/json/JSONException:printStackTrace ()V
// 472: goto -23 -> 449
// 475: astore 17
// 477: aload_0
// 478: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 481: iconst_0
// 482: putfield 101 com/starcor/core/domain/UserCenterInfo:vipId I
// 485: goto -244 -> 241
// 488: astore 16
// 490: aload_0
// 491: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 494: iconst_0
// 495: putfield 111 com/starcor/core/domain/UserCenterInfo:viPower I
// 498: goto -199 -> 299
// 501: astore 15
// 503: aload_0
// 504: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 507: fconst_0
// 508: putfield 125 com/starcor/core/domain/UserCenterInfo:balance F
// 511: goto -178 -> 333
// 514: astore 14
// 516: aload_0
// 517: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 520: iconst_0
// 521: putfield 135 com/starcor/core/domain/UserCenterInfo:vipEndDays I
// 524: goto -133 -> 391
// 527: astore 13
// 529: aload_0
// 530: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 533: iconst_0
// 534: putfield 144 com/starcor/core/domain/UserCenterInfo:account_type I
// 537: goto -88 -> 449
//
// Exception table:
// from to target type
// 137 157 454 java/lang/Exception
// 6 73 467 org/json/JSONException
// 73 97 467 org/json/JSONException
// 97 132 467 org/json/JSONException
// 137 157 467 org/json/JSONException
// 157 181 467 org/json/JSONException
// 181 216 467 org/json/JSONException
// 221 241 467 org/json/JSONException
// 241 265 467 org/json/JSONException
// 265 274 467 org/json/JSONException
// 279 299 467 org/json/JSONException
// 299 308 467 org/json/JSONException
// 313 333 467 org/json/JSONException
// 333 357 467 org/json/JSONException
// 357 366 467 org/json/JSONException
// 371 391 467 org/json/JSONException
// 391 415 467 org/json/JSONException
// 415 424 467 org/json/JSONException
// 429 449 467 org/json/JSONException
// 456 464 467 org/json/JSONException
// 477 485 467 org/json/JSONException
// 490 498 467 org/json/JSONException
// 503 511 467 org/json/JSONException
// 516 524 467 org/json/JSONException
// 529 537 467 org/json/JSONException
// 221 241 475 java/lang/Exception
// 279 299 488 java/lang/Exception
// 313 333 501 java/lang/Exception
// 371 391 514 java/lang/Exception
// 429 449 527 java/lang/Exception
}
}
/* Location: C:\Users\THX\Desktop\aa\aa\反编译工具包\out\classes_dex2jar.jar
* Qualified Name: com.starcor.core.parser.json.GetUserCenterInfoSAXParserJson
* JD-Core Version: 0.6.2
*/ | [
"[email protected]"
] | |
4456757237b3102633978677378487520ae31c17 | 983431b1b2b97e70409cef9da6989147545e3bb8 | /app/src/test/java/com/rab/telemetry/ExampleUnitTest.java | 97af66037b5a9f289c657f61f8c8b446ce067e6c | [] | no_license | Riddhish-Bharadva/Telemeter | 9414cd2cd5d3a7df04b428ffc6fc185d9ce6617c | 68dc29e9d53dad241700161444546eb15984ec67 | refs/heads/master | 2022-12-27T05:43:35.381810 | 2020-09-23T00:22:35 | 2020-09-23T00:22:35 | 297,762,124 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 378 | java | package com.rab.telemetry;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
e33828e6bbf3b2e0dfd8a9c28901eb180e630399 | 0676e1bf8e0d6a657847c3f31765ba5107ceb2ad | /src/main/java/com/BookServer2/myProject/BookServiceImpl.java | cee33221e1d8518fe67fb4344e070125d1e35801 | [] | no_license | MarchenkoMark/myProject | d6f9eb514cdb2dcddc5fdf2c48b593ddbff80218 | db439cb7bfb63323b0ede6e8b8f4cd6506390bab | refs/heads/master | 2022-12-11T10:30:03.068057 | 2020-09-10T12:50:39 | 2020-09-10T12:50:39 | 294,370,476 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 486 | java | package com.BookServer2.myProject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service("productService")
public class BookServiceImpl implements BookService{
@Qualifier("bookRepository")
@Autowired
private BookRepository bookRepository;
@Override
public Iterable<Book> findAll() {
return bookRepository.findAll();
}
}
| [
"[email protected]"
] | |
ed5e2993fe9f89d16e0dd5ff487fe4da28432934 | 78b6e133c361d4277b4073c94fe205f92b83ca98 | /src/main/java/com/xiaoshu/dao/MessageTempleMapper.java | 00ad1013ebc88412bd1b0a2e96ec48bb853df229 | [] | no_license | barrysandy/rabbitmq | 375763a78e5c35d7a75780ef4893f8279c089bbb | d4482d74c26c32aeaaedf7c83f4b8cafcb94b951 | refs/heads/master | 2020-03-16T04:42:39.145664 | 2018-09-05T22:40:03 | 2018-09-05T22:40:03 | 132,517,379 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,513 | java | package com.xiaoshu.dao;
import com.xiaoshu.entity.MessageTemple;
import org.apache.ibatis.annotations.*;
import java.util.List;
/** 标准版 */
public interface MessageTempleMapper {
/** save one */
@Insert("INSERT INTO message_temple (ID,COMMODITY_ID,TEMPLE_NAME, TEMPLE_ID,TEMPLE_TYPE, CREATE_TIME, UPDATE_TIME, DESC_M, STATUS ,SIGN) " +
"VALUES(#{id},#{commodityId},#{templeName},#{templeId},#{templeType},#{createTime},#{updateTime},#{descM},#{status},#{sign} )")
Integer save(MessageTemple bean);
/** update templeId */
@Update("UPDATE message_temple SET TEMPLE_ID=#{templeId},UPDATE_TIME=#{updateTime} where ID = #{id}")
Integer updateCodeStateAndCreateTimeById(@Param("templeId") Integer templeId ,@Param("updateTime") String updateTime, @Param("id") String id);
/** update all */
@Update("UPDATE message_temple SET COMMODITY_ID=#{commodityId},TEMPLE_NAME=#{templeName},TEMPLE_ID=#{templeId},TEMPLE_TYPE=#{templeType},CREATE_TIME=#{createTime},UPDATE_TIME=#{updateTime},DESC_M=#{descM}," +
"STATUS=#{status},SIGN=#{sign} WHERE ID=#{id} ")
Integer updateAll(MessageTemple bean);
/** delete ById */
@Delete("DELETE FROM message_temple WHERE ID=#{id}")
Integer deleteById(@Param("id") String id);
/** 按照 商品 id 查询 短信模板集合 */
@Select("SELECT * FROM message_temple WHERE COMMODITY_ID = #{commodityId}")
List<MessageTemple> listByCommodityId(@Param("commodityId") Integer commodityId);
/** select ByID */
@Select("SELECT * FROM message_temple WHERE ID = #{id}")
MessageTemple getById(@Param("id") String id);
/**
* 查询列表
* @param index 分页开始
* @param pageSize 分页每页最大数
* @param key 关键字
* @return 返回订单集合
* @throws Exception 抛出异常
*/
List<MessageTemple> listByKey(@Param("index") int index, @Param("pageSize") int pageSize, @Param("key") String key,@Param("status") Integer status, @Param("commodityId") Integer commodityId);
/**
* 统计
* @param key 关键字
* @return 返回数量
* @throws Exception 抛出异常
*/
Integer countByKey(@Param("key") String key,@Param("status") Integer status, @Param("commodityId") Integer commodityId);
/** 按照模板类型和商品ID统计模板数 用于查询某个类型的模板是否存在 */
@Select("SELECT COUNT(ID) FROM message_temple WHERE TEMPLE_TYPE = #{templeType} AND COMMODITY_ID = #{commodityId}")
Integer countByTTypeAndCId(@Param("templeType") String templeType, @Param("commodityId") Integer commodityId);
}
| [
"[email protected]"
] | |
7bb4b41057e346be953db95b83c4bd533cec8f9f | 5055dcd80cc1d40cf9a67a51ae20581ad1ed54d0 | /src/main/java/com/jk/faces/util/JKJsfUtil.java | 1e22ecd643e48fe818b7c535fa3cdecab5d6c911 | [
"Apache-2.0"
] | permissive | srikantha2/jk-faces | 00231f42614190778819865c487a058d0f67825e | 3abe304aaa17409651511ef0454dcc822f2016dc | refs/heads/master | 2020-12-25T23:36:16.023520 | 2016-05-16T19:02:31 | 2016-05-16T19:02:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 30,244 | java | /*
* Copyright 2002-2016 Jalal Kiswani.
*
* 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.jk.faces.util;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.component.StateHelper;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UIViewRoot;
import javax.faces.component.visit.VisitContext;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.view.ViewDeclarationLanguage;
import javax.faces.view.facelets.FaceletContext;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.junit.Assert;
import com.jk.annotations.Author;
import com.jk.exceptions.handler.ExceptionUtil;
import com.jk.faces.components.TagAttributeConstants;
import com.jk.util.ConversionUtil;
/**
* <B>JSFUtil</B> is class that contains JSF helpful methods, that helps to
* search, edit or manipulate JSF contents.
*
* @author Jalal H. Kiswani
* @version 1.0
*/
@Author(name = "Jalal Kiswani", date = "3/9/2014", version = "1.0")
public class JKJsfUtil {
/** The Constant CHECKSUM_POSTFIX. */
private static final String CHECKSUM_POSTFIX = "-checksum";
/** The logger. */
private static Logger logger = Logger.getLogger(JKJsfUtil.class.getName());
/**
* add String <code>contents</code> in HTML row.
*
* @param contents
* the contents
* @param colSpan
* the col span
* @param style
* the style
* @throws IOException
* if an input/output error occurs during response writing
*/
public static void addFullRow(final String contents, final int colSpan, final String style) throws IOException {
if (contents != null) {
final ResponseWriter writer = JKJsfUtil.context().getResponseWriter();
writer.startElement("tr", null);
writer.startElement("td", null);
writer.writeAttribute("align", "center", null);
writer.writeAttribute("colspan", colSpan, null);
writer.writeAttribute("class", style, null);
writer.writeText(contents, null);
writer.endElement("td");
writer.endElement("tr");
}
}
/**
* add component <code>comp</code> in HTML row.
*
* @param comp
* the comp
* @param colSpan
* the col span
* @param style
* the style
* @throws IOException
* if an input/output error occurs during response writing
*/
public static void addFullRow(final UIComponent comp, final int colSpan, final String style) throws IOException {
if (comp != null) {
final ResponseWriter writer = JKJsfUtil.context().getResponseWriter();
writer.startElement("tr", null);
writer.startElement("td", null);
// TODO : convert the following to use the TagConstants class
JKJsfUtil.writeAttribue(comp, "align", "center");
JKJsfUtil.writeAttribue(comp, "colspan", colSpan);
JKJsfUtil.writeAttribue(comp, "styleClass", "class", style);
comp.encodeAll(JKJsfUtil.context());
writer.endElement("td");
writer.endElement("tr");
}
}
/**
* Appends value to an existing attribute in component
* <code>component</code>.
*
* @param component
* the component
* @param sourceKey
* the source key
* @param targetKey
* the target key
* @param valueToAppend
* the value to append
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void appendAttribute(final UIComponent component, final String sourceKey, final String targetKey, final String valueToAppend)
throws IOException {
String value = (String) component.getAttributes().get(sourceKey);
if (value == null) {
value = valueToAppend;
} else {
value = value.concat(" ").concat(valueToAppend);
}
JKJsfUtil.context().getResponseWriter().writeAttribute(targetKey, value, null);
}
/**
* Builds the view.
*
* @param context
* the context
* @param viewId
* the view id
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static String buildView(final FacesContext context, final String viewId) throws IOException {
final UIViewRoot view = JKJsfUtil.createView(viewId);
view.encodeAll(FacesContext.getCurrentInstance());
final ResponseWriter originalWriter = context.getResponseWriter();
final StringWriter writer = new StringWriter();
try {
context.setResponseWriter(context.getRenderKit().createResponseWriter(writer, "text/html", "UTF-8"));
view.encodeAll(context);
} finally {
if (originalWriter != null) {
context.setResponseWriter(originalWriter);
}
}
return writer.toString();
}
/**
* Builds the view.
*
* @param viewId
* the view id
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static String buildView(final String viewId) throws IOException {
return JKJsfUtil.buildView(FacesContext.getCurrentInstance(), viewId);
}
/**
* Calculate checksum.
*
* @param component
* the component
* @return the long
*/
public static long calculateChecksum(final UIComponent component) {
try {
final Checksum checksumHandler = new CRC32();
final UIFacesVisitor visitors = JKJsfUtil.visitComponent(component);
final List<UIInput> inputs = visitors.getInputs();
for (final UIInput uiInput : inputs) {
if (uiInput.getValue() == null) {
checksumHandler.update("null".getBytes(), 0, 0);
} else {
final byte[] bytes = uiInput.getValue().toString().getBytes("UTF-8");
checksumHandler.update(bytes, 0, bytes.length);
}
}
return checksumHandler.getValue();
} catch (final Exception e) {
ExceptionUtil.handle(e);
// unreachable
return -1;
}
}
/**
* Calculate current view checksum.
*
* @return the long
*/
public static long calculateCurrentViewChecksum() {
return JKJsfUtil.calculateChecksum(FacesContext.getCurrentInstance().getViewRoot());
}
/**
* Clear view states.
*/
public static void clearViewStates() {
JKJsfUtil.getViewMap().clear();
}
/**
* Context.
*
* @return the faces context
*/
private static FacesContext context() {
return FacesContext.getCurrentInstance();
}
/*
*
*/
/**
* Creates the method expression.
*
* @param expression
* the expression
* @param returnType
* the return type
* @return the method expression
*/
public static MethodExpression createMethodExpression(final String expression, final Class<?> returnType) {
Assert.assertNotNull(expression);
// TODO : check the below line????
JKJsfUtil.logger.fine("createMethodEpression:".concat(expression));
final FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().getExpressionFactory().createMethodExpression(context.getELContext(), expression, returnType, new Class[0]);
}
/**
* Creates the value exception.
*
* @param value
* the value
* @return the value expression
*/
public static ValueExpression createValueException(final String value) {
return JKJsfUtil.createValueException(value, Object.class);
}
/**
* Creates the value exception.
*
* @param value
* the value
* @param clas
* the clas
* @return the value expression
*/
public static ValueExpression createValueException(final String value, final Class<?> clas) {
final ExpressionFactory expressionFactory = JKJsfUtil.getExpressionFactory();
if (expressionFactory != null) {
final ELContext elContext = FacesContext.getCurrentInstance().getELContext();
final ValueExpression ve1 = expressionFactory.createValueExpression(elContext, value, clas);
return ve1;
} else {
final ELContext elContext = FacesContext.getCurrentInstance().getELContext();
final ValueExpression ve1 = FacesContext.getCurrentInstance().getApplication().getExpressionFactory().createValueExpression(elContext,
value, clas);
return ve1;
}
}
/**
* Creates the value exception with value.
*
* @param originalValue
* the original value
* @return the value expression
*/
public static ValueExpression createValueExceptionWithValue(final Object originalValue) {
return FacesContext.getCurrentInstance().getApplication().getExpressionFactory().createValueExpression(originalValue,
originalValue.getClass());
}
/**
* Creates the view.
*
* @param viewId
* the view id
* @return the UI view root
*/
public static UIViewRoot createView(final String viewId) {
final FacesContext facesContext = FacesContext.getCurrentInstance();
final ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
final UIViewRoot view = viewHandler.createView(facesContext, viewId);
try {
viewHandler.getViewDeclarationLanguage(facesContext, viewId).buildView(facesContext, view);
} catch (final IOException e) {
throw new RuntimeException(e);
}
return view;
}
/**
* Error.
*
* @param message
* the message
*/
public static void error(final String message) {
final FacesMessage msg = new FacesMessage(message);
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
/**
* Evaluate expression to object.
*
* @param el
* the el
* @return the object
*/
public static Object evaluateExpressionToObject(final String el) {
if (el == null) {
return null;
}
final Application application = FacesContext.getCurrentInstance().getApplication();
return application.evaluateExpressionGet(FacesContext.getCurrentInstance(), el, Object.class);
}
/**
* Evaluate expression to object.
*
* @param valueExpression
* the value expression
* @return the object
*/
public static Object evaluateExpressionToObject(final ValueExpression valueExpression) {
if (valueExpression == null) {
return null;
}
return JKJsfUtil.evaluateExpressionToObject(valueExpression.getExpressionString());
}
/**
* Attempts to find a value associated with the specified <code>key</code> ,
* using the <code> stateHelper </code> if no such value is found it gets
* the attribute value, in component <code>component</code> with Key
* <code>key</code> if the attribute's value is <code>null</code> it return
* <code>null</code>.
*
* @param component
* the component
* @param stateHelper
* the state helper
* @param key
* the key
* @return {@link Object}
*/
public static Object getAttribute(final UIComponent component, final StateHelper stateHelper, final String key) {
final Object value = stateHelper.eval(key);
return value == null ? JKJsfUtil.getAttribute(component, key, null) : value;
}
/**
* gets the attribute value, in component <code>uiComponent</code> with Key
* <code>key</code> if the attribute's value is <code>null</code> it return
* the value of <code>defaultValue</code>.
*
* @param component
* the component
* @param key
* the key
* @param defaultValue
* the default value
* @return the attribute
*/
public static Object getAttribute(final UIComponent component, final String key, final Object defaultValue) {
final Object value = component.getAttributes().get(key);
return value == null ? defaultValue : value;
}
/**
* gets the attribute <code>Boolean</code> value, in component
* <code>uiComponent</code> with Key <code>key</code> </br>
* if the attribute's value is <code>null</code> it return the value of
* <code>defaultValue</code>.
*
* @param uiComponent
* the ui component
* @param key
* the key
* @param defaultValue
* the default value
* @return attribute value
*/
public static boolean getBooleanAttribute(final UIComponent uiComponent, final String key, final boolean defaultValue) {
return new Boolean(JKJsfUtil.getAttribute(uiComponent, key, defaultValue).toString());
}
/**
* Gets the checksum key.
*
* @param currentView
* the current view
* @return the checksum key
*/
private static String getChecksumKey(final String currentView) {
return currentView.concat(JKJsfUtil.CHECKSUM_POSTFIX);
}
/**
* Gets the component attribute.
*
* @param comp
* the comp
* @param attributeName
* the attribute name
* @return the component attribute
*/
public static Object getComponentAttribute(final UIComponent comp, final String attributeName) {
final Map map = JKJsfUtil.getComponentMap(comp);
return map.get(attributeName);
}
/**
* Gets the component map.
*
* @param comp
* the comp
* @return the component map
*/
private static Map getComponentMap(final UIComponent comp) {
final Map<String, Map<String, Map>> viewMap = JKJsfUtil.getViewMap();
Map componentMap = viewMap.get(comp.getClientId());
if (componentMap == null) {
componentMap = new HashMap();
viewMap.put(comp.getClientId(), componentMap);
}
return componentMap;
}
/**
* Gets the current view.
*
* @return the current view
*/
public static String getCurrentView() {
Object viewName = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(TagAttributeConstants.CURRENT_VIEW);
if (viewName != null) {
return viewName.toString();
}
viewName = FacesContext.getCurrentInstance().getAttributes().get(TagAttributeConstants.CURRENT_VIEW);
if (viewName != null) {
return viewName.toString();
}
return FacesContext.getCurrentInstance().getViewRoot().getViewId();
}
/**
* Gets the current view original checksum.
*
* @return the current view original checksum
*/
public static long getCurrentViewOriginalChecksum() {
final String currentView = JKJsfUtil.getCurrentView();
if (currentView == null) {
throw new IllegalStateException("current view is null");
}
final String key = JKJsfUtil.getChecksumKey(currentView);
final Object object = JKJsfUtil.getSessionMap().get(key);
if (object == null) {
throw new IllegalStateException("key : ".concat(key).concat(" not found on sessino ,call saveCurrentViewChecksum before this"));
}
return (Long) object;
}
/**
* Gets the expression factory.
*
* @return the expression factory
*/
public static ExpressionFactory getExpressionFactory() {
if (JKJsfUtil.getFaceletsContext() != null) {
return JKJsfUtil.getFaceletsContext().getExpressionFactory();
} else {
return null;
}
}
/**
* Gets the facelets context.
*
* @return the facelets context
*/
public static FaceletContext getFaceletsContext() {
return (FaceletContext) FacesContext.getCurrentInstance().getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
}
/**
* gets the attribute <code>int</code> value, in component
* <code>uiComponent</code> with Key <code>key</code> </br>
* if the attribute's value is <code>null</code> it return the value of
* <code>defaultValue</code>.
*
* @param component
* the component
* @param key
* the key
* @param defaultValue
* the default value
* @return attribute value
*/
public static int getIntegerAttribute(final UIComponent component, final String key, final Object defaultValue) {
return new Integer(JKJsfUtil.getAttribute(component, key, defaultValue).toString());
}
/**
* gets JSF information like JSF version and Faces context.
*
* @return the JSF info
*/
public static Map<String, Object> getJSFInfo() {
final LinkedHashMap<String, Object> details = new LinkedHashMap<String, Object>();
final FacesContext context = FacesContext.getCurrentInstance();
final Application application = context.getApplication();
final ViewHandler viewHandler = application.getViewHandler();
final ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(context, context.getViewRoot().getViewId());
final LifecycleFactory LifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
details.put("JSF-Version", FacesContext.class.getPackage().getImplementationVersion());
details.put("JSF-Version-Package", FacesContext.class.getPackage().getName());
details.put("FacesContext", context.getClass());
details.put("Application", application.getClass());
details.put("ViewHandler", viewHandler.getClass());
details.put("ViewDeclarationLanguage", vdl.getClass());
details.put("LifecycleFactory", LifecycleFactory.getClass());
return details;
}
/**
* Gets the request attribute as boolean.
*
* @param key
* the key
* @param defaultValue
* the default value
* @return the request attribute as boolean
*/
public static boolean getRequestAttributeAsBoolean(final String key, final Object defaultValue) {
final Object value = JKJsfUtil.getRequestMap().get(key);
return ConversionUtil.toBoolean(value == null ? defaultValue : value);
}
/**
* Gets the request map.
*
* @return the request map
*/
public static Map<String, Object> getRequestMap() {
return FacesContext.getCurrentInstance().getExternalContext().getRequestMap();
}
/**
* Gets the session map.
*
* @return the session map
*/
public static Map<String, Object> getSessionMap() {
return FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
}
/**
* Gets the view map.
*
* @return the view map
*/
private static Map<String, Map<String, Map>> getViewMap() {
final String viewName = JKJsfUtil.getCurrentView();
Map<String, Map<String, Map>> viewMap = (Map) JKJsfUtil.getSessionMap().get(viewName);
if (viewMap == null) {
viewMap = new HashMap<>();
JKJsfUtil.getSessionMap().put(viewName, viewMap);
}
return viewMap;
}
/**
* Checks if is JS f22.
*
* @return true, if is JS f22
*/
public static boolean isJSF22() {
final String version = FacesContext.class.getPackage().getImplementationVersion();
if (version != null) {
return version.startsWith("2.2");
} else {
// fallback
try {
Class.forName("javax.faces.flow.Flow");
return true;
} catch (final ClassNotFoundException ex) {
return false;
}
}
}
/**
* Save current view checksum.
*/
public static void saveCurrentViewChecksum() {
final String currentView = JKJsfUtil.getCurrentView();
if (currentView == null) {
throw new IllegalStateException("current view is null");
}
final long checksum = JKJsfUtil.calculateCurrentViewChecksum();
JKJsfUtil.getSessionMap().put(JKJsfUtil.getChecksumKey(currentView), checksum);
}
/**
* Sets the component attribute.
*
* @param comp
* the comp
* @param attributeName
* the attribute name
* @param atributeValue
* the atribute value
*/
public static void setComponentAttribute(final UIComponent comp, final String attributeName, final Object atributeValue) {
final Map componentMap = JKJsfUtil.getComponentMap(comp);
componentMap.put(attributeName, atributeValue);
System.err.println("Set Compnent Attribute : " + attributeName + " : " + atributeValue);
}
/**
* Sets the request attribute.
*
* @param key
* the key
* @param value
* the value
*/
public static void setRequestAttribute(final String key, final Object value) {
JKJsfUtil.getRequestMap().put(key, value);
}
/**
* Sets the session attribute.
*
* @param key
* the key
* @param value
* the value
*/
public static void setSessionAttribute(final String key, final Object value) {
JKJsfUtil.getSessionMap().put(key, value);
}
/**
* Success.
*
* @param message
* the message
*/
public static void success(final String message) {
final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success", message);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
/**
* Visit view.
*
* @param component
* the component
* @return the UI view visitor
*/
public static UIFacesVisitor visitComponent(final UIComponent component) {
final UIFacesVisitor visitor = new UIFacesVisitor();
component.visitTree(VisitContext.createVisitContext(FacesContext.getCurrentInstance()), visitor);
return visitor;
}
/**
* Visit current view.
*
* @return the UI faces visitor
*/
public static UIFacesVisitor visitCurrentView() {
return JKJsfUtil.visitComponent(FacesContext.getCurrentInstance().getViewRoot());
}
/**
* Visit view.
*
* @param viewId
* the view id
* @return the UI view visitor
*/
public static UIFacesVisitor visitView(final String viewId) {
final UIViewRoot view = JKJsfUtil.createView(viewId);
final UIFacesVisitor visitor = new UIFacesVisitor();
view.visitTree(VisitContext.createVisitContext(FacesContext.getCurrentInstance()), visitor);
return visitor;
}
/**
* Warning.
*
* @param message
* the message
*/
public static void warning(final String message) {
final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Warning", message);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
/**
* writes an attribute to component <code>component</code> with key
* <code>key</code> and default value <code>defaultValue</code>.
*
* @param component
* the component
* @param key
* the key
* @param defaultValue
* the default value
* @throws IOException
* if an input/output error occurs during response writing
*/
public static void writeAttribue(final UIComponent component, final String key, final Object defaultValue) throws IOException {
JKJsfUtil.writeAttribue(component, key, null, defaultValue);
}
/**
* reads the value of with Key <code>sourceKey</code> in component
* <code>component</code>, then gets the response writer and add attribute
* with with Key <code>targetKey</code> and value equal to the retrieved
* previous value in case the retrieved value equal null then the value of
* <code>defaultValue</code> will be used instead Also in case
* <code>targetKey</code> equal null then <code>sourceKey</code> will be
* used instead.
*
* @param component
* the component
* @param sourceKey
* the attribute's key in the UI component
* @param targetKey
* the attribute's key that will be used to add the attribute
* @param defaultValue
* the default value
* @throws IOException
* if an input/output error occurs during response writing
*/
public static void writeAttribue(final UIComponent component, final String sourceKey, final String targetKey, final Object defaultValue)
throws IOException {
final Object value = JKJsfUtil.getAttribute(component, sourceKey, defaultValue);
JKJsfUtil.context().getResponseWriter().writeAttribute(targetKey == null ? sourceKey : targetKey, value, null);
}
/**
*
* @param keepAttributes
*/
public static void invalidateSession(String... keepAttributes) {
if (FacesContext.getCurrentInstance() != null) {
// original map
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = new HashMap(context.getSessionMap());
context.invalidateSession();
HttpSession session = (HttpSession) context.getSession(true);
// restore original attributes
for (String attribute : keepAttributes) {
session.setAttribute(attribute, sessionMap.get(attribute));
}
}
}
public static String getLocalNameFromQName(final String qName) {
final String[] split = qName.split(":");
return split.length == 2 ? split[1] : split[0];
}
public static String getNamespaceLetterFromQName(final String qName) {
final String[] split = qName.split(":");
if (split.length == 1) {
return null;
}
return split[0];
}
public static UIComponent findComponentInRoot(String id) {
UIComponent component = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) {
UIComponent root = facesContext.getViewRoot();
component = findComponent(root, id);
}
return component;
}
public static UIComponent findComponent(UIComponent base, String id) {
if (id.equals(base.getId()))
return base;
UIComponent kid = null;
UIComponent result = null;
Iterator kids = base.getFacetsAndChildren();
while (kids.hasNext() && (result == null)) {
kid = (UIComponent) kids.next();
if (id.equals(kid.getId())) {
result = kid;
break;
}
result = findComponent(kid, id);
if (result != null) {
break;
}
}
return result;
}
///////////////////////////////////////////////////////////////////////////
public static List<UIComponent> findComponents(UIComponent parent, Class type) {
List<UIComponent> result = new Vector<>();
List<UIComponent> children = parent.getChildren();
for (UIComponent uiComponent : children) {
if (uiComponent.getClass().equals(type)) {
result.add(uiComponent);
}
result.addAll(findComponents(uiComponent, type));
}
return result;
}
/**
*
* @return
*/
public static String getRemoteHostName() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) {
HttpServletRequest httpServletRequest = (HttpServletRequest) facesContext.getExternalContext().getRequest();
String ip = httpServletRequest.getHeader("X-FORWARDED-FOR");
if (ip == null) {
ip = httpServletRequest.getRemoteAddr();
}
return ip;
}
return null;
}
/**
*
* @param path
* @throws IOException
*/
public static void redirect(String path) throws IOException {
FacesContext currentInstance = FacesContext.getCurrentInstance();
if (currentInstance != null) {
// ExternalContext externalContext =
// currentInstance.getExternalContext();
// HttpServletRequest request = (HttpServletRequest)
// externalContext.getRequest();
// HttpServletResponse response = (HttpServletResponse)
// externalContext.getResponse();
redirect(path, null, null);
} else {
throw new IllegalStateException("your are calling redirect assuming FacesContext is there!!!");
}
}
/**
* add full
*
* @param string
* @param request
* @param response
* relative to context
* @throws IOException
*/
public static void redirect(String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
FacesContext currentInstance = FacesContext.getCurrentInstance();
if (currentInstance != null) {
request = (HttpServletRequest) currentInstance.getExternalContext().getRequest();
response = (HttpServletResponse) currentInstance.getExternalContext().getResponse();
}
String fullPath = request.getContextPath() + path;
// if (currentInstance != null) {
// }
String facesRequest = request.getHeader("Faces-Request");
if (facesRequest != null && "partial/ajax".equals(facesRequest)) {
if (currentInstance != null) {
currentInstance.getExternalContext().redirect(fullPath);
currentInstance.responseComplete();
} else {
// // It's a JSF ajax request.
// // the below will useful in case of ajax requests which
// doesn't
// // Recognize redirect
response.setContentType("text/xml");
response.getWriter().append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.printf("<partial-response><redirect url=\"%s\"></redirect></partial-response>", fullPath);
}
} else {
// normal full request
response.sendRedirect(fullPath);
}
}
public static void forceClearCache(ServletResponse resp) {
HttpServletResponse response = (HttpServletResponse) resp;
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP
// 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
}
}
| [
"[email protected]"
] | |
d63ab5f3425fbf3f1a980d9c90eb6d1e46d8968c | a22499902c4f1ca38e39e17891451655b261e591 | /src/CF1091_A.java | 1fcb506ddf096afaef62290afb88f3be939b2251 | [] | no_license | krishnadwypayan/Codeforces | 7753b0dd023cea0a9a6df81b16ba9eb1f3dc0e75 | 67090e5c61b789da0465e452737406090b48a135 | refs/heads/master | 2020-04-09T01:23:24.493273 | 2018-12-31T17:48:11 | 2018-12-31T17:48:11 | 159,902,184 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 606 | java | import java.util.Scanner;
public class CF1091_A {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int y = scanner.nextInt(), b = scanner.nextInt(), r = scanner.nextInt();
int min = Math.min(y, Math.min(b, r));
int ans = 0;
if (min == r) {
ans += r + r-1 + r-2;
}
else if (min == b) {
r = Math.min(r, b+1);
ans += r + r-1 + r-2;
}
else {
r = Math.min(r, y+2);
ans += r + r-1 + r-2;
}
System.out.println(ans);
}
}
| [
"[email protected]"
] | |
dd8a7338bc36eca1db719207d33afa1d9603d14d | 418972d25f6d574bbc019c37b71d0cd93b6d9402 | /demo/src/main/java/de/quist/app/maps/example/MultiMapDemoActivity.java | 60155da31f2da1e7a4d4e260893835e2c56ef8d3 | [
"Apache-2.0"
] | permissive | tomquist/android-maps-abstraction | 37e950961a85cfa33d97769ac59b78d709f219d4 | eb5b133a4ba44cf2aa0a68daf610203a704a3c27 | refs/heads/master | 2021-01-10T00:53:29.109312 | 2015-03-21T13:10:59 | 2015-03-21T13:10:59 | 31,922,864 | 2 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,048 | java | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.quist.app.maps.example;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
/**
* This shows how to create a simple activity with multiple maps on screen.
*/
public class MultiMapDemoActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multimap_demo);
}
}
| [
"[email protected]"
] | |
d55291b11da8b7fc14e62f908063f88f4a418fac | 22cea9dc711c6ff2be711824e55c1f6fd4c75675 | /android/app/src/main/java/com/lettersgame/MainApplication.java | 3b8cb87c9996d4af3ac79a5a8e58ee5bd70e97c3 | [] | no_license | LaurenceM10/letters-game | b84695f54f121fd22719d4bb95f27d88924868ca | 4620cf71edafe6295f39a9ea82c4cd73a8185fd3 | refs/heads/main | 2023-07-12T10:00:51.065817 | 2021-08-17T10:55:55 | 2021-08-17T10:55:55 | 395,711,343 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,605 | java | package com.lettersgame;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.lettersgame.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.